Sendmail with Attachment script

Sendmail with Attachment script - 徐明的博客

Sendmail with Attachment script

四月 24th, 2008

This is the python script for linux sendmail programe or  with smtp server.

You can use it free.It's simple ,but support the attachment.

# -*- coding: utf-8 -*- #sendmail with mimebase import smtplib import os,sys,codecs,string import locale from optparse import OptionParser from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders def send_mail(send_from, send_to, subject, text, files, server): #assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = send_to msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', "octet-stream") s=open(f,"rb").read() part.set_payload( s ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) if(server): smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() cmd="sendmail %s"%send_to print 'sending...' p=os.popen(cmd,"w") p.write(msg.as_string()) p.close() def main(argv): locale.setlocale(locale.LC_CTYPE, "") encoding = locale.getlocale()[1] if not encoding: encoding = "us-ascii" sys.stdout = codecs.getwriter(encoding)(sys.stdout, errors = "replace") sys.stderr = codecs.getwriter(encoding)(sys.stderr, errors = "replace") usage = "usage: %prog [options] arg \nnote:Ctrl+D or ... to end the body edit!" parser = OptionParser(usage=usage,version="%prog 0.1") parser.add_option("-n", "--name", dest="name" , help="Your name.") parser.add_option("", "--server", dest="server", help="The smtp server address.") parser.add_option("-f", "--files", dest="files" , help="Attachment files. Split by ,") (options, args) = parser.parse_args() if not options.name: options.name=raw_input(u"From:") if len(args) != 1: options.to=raw_input(u"To:") else: options.to=args[0] subject=raw_input(u"Subject:") print 'Body:'; raw='' body='' while True: raw=raw_input(' ') if raw=='...' or raw=='\x04': break; else: body+=raw +'\n' files=[]; if options.files: files=string.split(options.files,',') send_mail(options.name,options.to, subject, body,files,options.server) if __name__ == "__main__": main(argv=sys.argv[1:])
原文地址:https://www.cnblogs.com/lexus/p/2782216.html