#!/usr/bin/env python3"""Send the contents of a directory as a MIME message."""import osimport smtplib# For guessing MIME type based on file name extensionimport mimetypesfrom argparse import ArgumentParserfrom email.message import EmailMessagefrom email.policy import SMTPdef main():parser = ArgumentParser(description="""\Send the contents of a directory as a MIME message.Unless the -o option is given, the email is sent by forwarding to your localSMTP server, which then does the normal delivery process. Your local machinemust be running an SMTP server.""")parser.add_argument('-d', '--directory',help="""Mail the contents of the specified directory,otherwise use the current directory. Only the regularfiles in the directory are sent, and we don't recurse tosubdirectories.""")parser.add_argument('-o', '--output',metavar='FILE',help="""Print the composed message to FILE instead ofsending the message to the SMTP server.""")parser.add_argument('-s', '--sender', required=True,help='The value of the From: header (required)')parser.add_argument('-r', '--recipient', required=True,action='append', metavar='RECIPIENT',default=[], dest='recipients',help='A To: header value (at least one required)')args = parser.parse_args()directory = args.directoryif not directory:directory = '.'# Create the messagemsg = EmailMessage()msg['Subject'] = 'Contents of directory %s' % os.path.abspath(directory)msg['To'] = ', '.join(args.recipients)msg['From'] = args.sendermsg.preamble = 'You will not see this in a MIME-aware mail reader.\n'for filename in os.listdir(directory):path = os.path.join(directory, filename)if not os.path.isfile(path):continue# Guess the content type based on the file's extension. Encoding# will be ignored, although we should check for simple things like# gzip'd or compressed files.ctype, encoding = mimetypes.guess_type(path)if ctype is None or encoding is not None:# No guess could be made, or the file is encoded (compressed), so# use a generic bag-of-bits type.ctype = 'application/octet-stream'maintype, subtype = ctype.split('/', 1)with open(path, 'rb') as fp:msg.add_attachment(fp.read(),maintype=maintype,subtype=subtype,filename=filename)# Now send or store the messageif args.output:with open(args.output, 'wb') as fp:fp.write(msg.as_bytes(policy=SMTP))else:with smtplib.SMTP('localhost') as s:s.send_message(msg)if __name__ == '__main__':main()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。