为什么要写下了呢? 因为本人找了好久,网上都是 “发送带有正文的邮件”或者“发送带有附件的邮件”。就没见到一篇是“发送带有正文+附件的邮件”。导致本人折腾这个折腾了好久,太浪费时间了。写下来留作后续参考。
下面是在邮件里面,正文显示 a.html内容,并且附件附上a.html。
# coding: utf-8import smtplibfrom email.header import Headerfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom os.path import basenamedef send_report(): smtpserver = "smtp.xx.com" user = "user1" sender = "user1@xx.com" password = "pw1" receivers = "user1@xx.com;user2@xx.com"# receivers_list = ['user1@xx.com','user2@xx.com']# receivers=";".join(receivers_list) mail_subject='Send Email Test' send_file="a.html" send_mail(smtpserver, user, password, sender, receivers, mail_subject,send_file,send_file) print('Email has send out successfully!') def send_mail(smtpserver,user,password,sender,receivers,m_subject,m_content,m_attachment): msg=MIMEMultipart('alternative') msg['Subject']=Header(m_subject,'utf-8') msg['From']=sender msg['To']=receivers #mail content with open(m_content,"rb") as f: mail_content=f.read() msg.attach(MIMEText(mail_content,'html','utf-8')) #mail attachment with open(m_attachment,"rb") as f: mail_attach=f.read() send_attachment=MIMEText(mail_attach,'html','utf-8') send_attachment["Content-Type"]='application/octet-stream' send_attachment["Content-Disposition"]='attachment;filename='+basename(m_attachment) msg.attach(send_attachment) try: smtp=smtplib.SMTP() smtp.connect(smtpserver) smtp.login(user, password) smtp.sendmail(sender,receivers.split(";"),msg.as_string()) smtp.quit() except Exception as e: print("Send Email Failed!!!") raise e if __name__ == "__main__": send_report()