关于用 python 发邮件,搜出来的大部分代码都是 legacy code,而系统带的是 python 3.6,因此想试试 email 标准库的最新用法。html
一番折腾,发现官方文档不够详尽,并且还引了一堆 rfc,涉及 email 的格式标准,头大,仍是耐着性子整完了。python
把最好的献给这世界,也许永远都不够。
———— 一位出家师父服务器
#!/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!")