python之发送邮件----html + 附件
Posted Let凡
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python之发送邮件----html + 附件相关的知识,希望对你有一定的参考价值。
补充说明:文章两次邮件代码都是以163邮箱作为例子,不同的邮箱发送 连接该邮箱的smtp服务
代码不进行备注说明了,详情说明科参考代码下面地址,或者博主上一篇文本类型代码
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# sender发送者 receiver接收者
sender = ‘xxx@163.com‘
receiver = ‘xxxx.com‘
auth_code = ‘xxxABC‘
subject = ‘his测试报告A‘
msg = MIMEMultipart()
msg["Subject"] = subject
msg["from"] = sender
msg["to"] = receiver
with open("文件", ‘rb‘) as f: # 第一个参数文件在哪你写哪
mail_body = f.read()
# 发送html格式文本
html = MIMEText(mail_body, _subtype="html", _charset="utf-8")
html["Subject"] = subject
html["from"] = sender
html["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
以上是关于python之发送邮件----html + 附件的主要内容,如果未能解决你的问题,请参考以下文章