之前需要用Python发送报表邮件,在网上找了下资料,基本上符合要求了。
相关的示例如下,懂python的人应该都知道。
from email.mime.text import MIMEText from email.Message import Message from email.header import Header def send_mail(from_addr, to_list, sub, content) send_server = "smtp.163.com" msg = Message() msg['subject'] = sub msg['from'] = from_addr msg['to'] = ";".join(to_list) msg['date'] = time.strftime("%a, %d %b %Y %H:%M:%S %z") body = MIMEText(content, _subtype='html', _charset='utf-8') msg.attach(body) try: smtp = smtplib.SMTP(send_server) smtp.login(username, password) stmp.sendmail(from_addr, to_list, msg.as_string() except Exception, e: print str(e)
后来又有添加附件的需求,只需要添加几行代码即可。
from email.MIMEMultipart import MIMEMultipart msg = MIMEMultipart() att= MIMEText(open(attachment).read(), 'base64','utf-8') att["Content-Type"] = "application/octet-stream" att["Content-Disposition"] = "attachment;filename=%s"%attachment msg.attach(att); msg['subject'] = Header(sub,'utf-8')
msg['subject'] = Header(sub,'utf-8')
换成Header封装是由于收到的邮件有乱码,所以用Header了一下。
有需要的人拿去吧。