python之发送邮件----html + 附件

行吟阁 2020-07-04

补充说明:文章两次邮件代码都是以163邮箱作为例子,不同的邮箱发送 连接该邮箱的smtp服务代码不进行备注说明了,详情说明科参考代码下面地址,或者博主上一篇文本类型代码import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipart# sender发送者 receiver接收者sender = ‘‘receiver = ‘xxxx.com‘auth_code = ‘xxxABC‘subject = ‘his测试报告A‘msg = MIMEMultipart()msg["Subject"] = subjectmsg["from"] = sendermsg["to"] = receiverwith open("文件", ‘rb‘) as f:   # 第一个参数文件在哪你写哪    mail_body = f.read()# 发送html格式文本html = MIMEText(mail_body, _subtype="html", _charset="utf-8")html["Subject"] = subjecthtml["from"] = senderhtml["to"] = receiver# html附件 将测试报告放在附录中发送att1 = MIMEText(mail_body, "base64", "gb2312")att1["Content-Type"] = ‘application/octet-stream‘# 这里的filename是附录名字,不建议写中文,最好以英文为准--中文格式可能会出问题att1["Content-Disposition"] = ‘attachment; filename="test.html"‘msg.attach(html)  # 将html附加在msg里msg.attach(att1)  # 新增一个附件try:    smtp = smtplib.SMTP()    smtp.connect("smtp.163.com")    smtp.login(sender, auth_code)    smtp.sendmail(sender, receiver, msg.as_string())    smtp.quit()    print(‘发送成功‘)except BaseException as msg:    print("邮件发送失败", msg)代码参考:https://www.runoob.com/python/python-email.html

相关推荐