python 3.6 发邮件(html格式,带附件)

﹥>﹥吖頭↗ 提交于 2019-12-09 12:45:49

关于用 python 发邮件,搜出来的大部分代码都是 legacy code,而系统带的是 python 3.6,所以想试试 email 标准库的最新用法。

一番折腾,发现官方文档不够详尽,而且还引了一堆 rfc,涉及 email 的格式标准,头大,还是耐着性子整完了。

把最好的献给这世界,也许永远都不够。

———— 一位出家师父

#!/usr/bin/env python3

#~ 参考:
#~ https://docs.python.org/3.6/library/email.examples.html
#~ https://docs.python.org/3.6/library/email.message.html
#~ http://www.runoob.com/python3/python3-smtp.html

import smtplib
from email.message import EmailMessage
from email.headerregistry import Address, Group
import email.policy
import mimetypes

# 发送邮件服务器
smtp_server = "smtp.126.com"
user = "jack@126.com"
# 自己的客户端授权码
passwd = "客户端授权码"

# 发件人和收件人
# 直接用字符串也行,这里为了方便使用 display name
sender = Address("无明", "jack", "126.com") # 相当于 "无明 <jack@126.com>"
recipient = Group(addresses=(Address("解脱", "kate", "qq.com"), ))

# Use utf-8 encoding for headers. SMTP servers must support the SMTPUTF8 extension
# https://docs.python.org/3.6/library/email.policy.html
msg = EmailMessage(email.policy.SMTPUTF8)
# 邮件头和内容
msg['From'] = sender
msg['To'] = recipient
msg['Subject'] = 'smtp 测试'
msg.set_content("""
<html>
    <h2 style='color:red'>雪山偈</h2>
    <p>诸行无常,是生灭法。</p>
    <p>生灭灭已,寂灭为乐。</p>
</html>
""", subtype="html")

# 添加附件
filename = "test.zip"
ctype, encoding = mimetypes.guess_type(filename)
if ctype is None or encoding is not None:
    # No guess could be made, or the file is encoded (compressed), so
    # use a generic bag-of-bits type.
    ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
with open(filename, 'rb') as fp:
    msg.add_attachment(fp.read(), maintype, subtype, filename=filename)

# SSL
with smtplib.SMTP_SSL(smtp_server) as smtp:
    # HELO向服务器标志用户身份
    smtp.ehlo_or_helo_if_needed()
    # 登录邮箱服务器
    smtp.login(user, passwd)
    print(f"Email: {str(sender)} ==> {str(recipient)}")
    smtp.send_message(msg)
    print("Sent!")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!