这里是代码,attachment函数不理解的,可以参考我的另一篇blog,http://blog.csdn.net/zmj_88888888/article/details/8725768
sendmail_mime.py
# -*- coding: utf8 -*- import smtplib from email import Utils,Encoders import mimetypes,sys from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase ############# #要发给谁,这里发给2个人 #mailto_list=["[email protected]","[email protected]"] ##################### #设置服务器,用户名、口令以及邮箱的后缀 mail_host="mail.xxxxx.com" mail_user="[email protected]" mail_pass="password" mail_postfix="xxxxx.com" ###################### #构造添加附件的函数attachment def attachment(filename): fd = open(filename,'rb') mimetype,mimeencoding = mimetypes.guess_type(filename) if mimetype or (mimeencoding is None): mimetype = 'application/octet-stream' maintype,subtype = mimetype.split('/') if maintype == 'text': retval = MIMEText(fd.read(),_subtype=subtype) else: retval = MIMEBase(maintype,subtype) retval.set_payload(fd.read()) Encoders.encode_base64(retval) retval.add_header('Content-Disposition','attachment',filename = filename) fd.close() return retval def send_mail(to_list,sub,content): ''' to_list:发给谁 sub:主题 content:内容 send_mail("[email protected]","sub","content") ''' me=mail_user msg = MIMEMultipart() msg['Subject'] = sub msg['From'] = me msg['To'] = to_list msg['Date'] = Utils.formatdate(localtime=1) msg['Message-ID'] = Utils.make_msgid() body = MIMEText(content) msg.attach(body) for filename in sys.argv[1:]: msg.attach(attachment(filename)) try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user,mail_pass) s.sendmail(me, to_list, msg.as_string()) s.close() return True except Exception, e: print str(e) return False if __name__ == '__main__': if send_mail("[email protected]","hello jason","do you know me!"): print "发送成功" else: print "发送失败"
python sendmail_mime.py mail.txt mail.txt.tar.gz这里发送了两个附件mail.txt和mail.txt.tar.gz