标签:password python 附件发送 email import
python发送邮件的脚本,带有邮件内容与附件,邮件内容为串格式,附件为文件。如果想把某个目录下的所有文件当作附件发送,那请去掉注释。
代码如下:
#!/usr/bin/python #coding utf-8 from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email import Utils, Encoders import types import smtplib import socket import base64 import mimetypes import os class syk_mail(object): def __init__(self,smtpserver,sender,password): self.smtpserver = smtpserver self.password = password self.s = None count = sender.find(‘@‘) if count > -1: self.postfix = sender[count:] self.sender = sender[0:count] else: self.postfix = ‘‘ self.sender = sender def sendmailattach(self,receiver,subject,body,path): try: msgatt = MIMEMultipart(_charset=‘gb2312‘) msgatt[‘To‘] =receiver msgatt[‘From‘] = self.sender + self.postfix msgatt[‘Subject‘] = subject msgatt[‘Date‘] = Utils.formatdate(localtime=1) msgatt[‘Message-ID‘] = Utils.make_msgid() #body = base64.encodestring(body) msg = MIMEText(body) msg.add_header(‘Content-Language‘,‘zh-cn‘) msg.add_header(‘Content-Transfer-Encoding‘,‘base64‘) msg.add_header(‘content-type‘,‘text/html;charset = "gb2312"‘) msg.add_header(‘Content-Disposition‘,‘inline‘) msgatt.attach(msg) msgatt.attach(self.attachment(path)) #for root,dirs,files in os.walk(path): # for filespath in files: # msgatt.attach(self.attachment(os.path.join(root,filespath))) if self.s == None: self.s = smtplib.SMTP(self.smtpserver) self.s.set_debuglevel(True) self.s.login(self.sender+self.postfix,self.password) self.s.sendmail(msgatt[‘From‘],msgatt[‘To‘].split(‘;‘),msgatt.as_string()) except (socket.gaierror,socket.error,socket.herror,smtplib.SMTPException),e: self.err = str(e) return False return True def attachment(self,filename): if os.path.exists(filename) == False: return fd = open(filename,‘rb‘) mimetype,mimeencoding = mimetypes.guess_type(filename) maintype,subtype = "","" if mimeencoding or (mimetype is None): mimetype = ‘application/octet-stream‘ maintype,subtype = mimetype.split(‘/‘,1) retval = MIMEBase(maintype,subtype) retval.set_payload(fd.read()) Encoders.encode_base64(retval) retval.add_header(‘Content-Disposition‘, ‘attchment‘,filename=filename) fd.close() return retval #end script
本文出自 “刚刚出壳的小鸟” 博客,请务必保留此出处http://qhd2004.blog.51cto.com/629417/1826273
标签:password python 附件发送 email import
原文地址:http://qhd2004.blog.51cto.com/629417/1826273