python 3.6 發郵件(html格式,帶附件)

關於用 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!")
相關文章
相關標籤/搜索