幾乎每個網站都需要寄信:註冊時寄出確認信、忘記密碼時寄出重設連結、下單後寄出通知。Python 標準庫中的 smtplib 就是 SMTP(Simple Mail Transfer Protocol)的客戶端實作,讓寄信這件事變得相當輕鬆。
# coding=gbk
import smtplib
smtp = smtplib.SMTP()
smtp.connect("smtp.yeah.net", "25")
smtp.login('使用者名稱', '密碼')
smtp.sendmail(
'from@yeah.net',
'to@21cn.com',
'From: from@yeah.net\r\nTo: to@21cn.com\r\n'
'Subject: this is a email from python demo\r\n\r\nJust for test~_~'
)
smtp.quit()
smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])
這個類別代表與 SMTP 伺服器之間的一條連線,透過它可以送出指令並執行登入、寄信等操作。所有參數都是選填的:host 是主機名稱,port 預設為 25。若在建立物件時就提供了 host 與 port,初始化階段會自動呼叫 connect()。此外模組另有 SMTP_SSL 與 LMTP 兩個類別,操作方式與 SMTP 基本一致,現今的郵件服務商大多要求加密連線,實務上建議直接採用 SMTP_SSL。
set_debuglevel(level):開關除錯模式,預設為 False,不輸出任何除錯資訊。connect([host[, port]]):連線到指定伺服器。也可以把埠號寫進 host(例如 smtp.yeah.net:25)而省略 port 參數。docmd(cmd[, argstring]):直接對伺服器送出指令,argstring 是指令的參數。helo([hostname]):以 helo 指令向伺服器表明身分。has_extn(name):判斷伺服器是否支援某個擴充功能。基於安全考量,多數伺服器會封鎖此指令。verify(address):確認某個信箱是否存在於伺服器上。同樣常被伺服器停用。login(user, password):登入伺服器。目前幾乎所有 SMTP 服務都要求先通過身分驗證才允許寄信。sendmail(from_addr, to_addrs, msg):寄出郵件。quit():切斷連線,等同送出 quit 指令。下面完全透過 docmd() 手動完成寄信流程:
import smtplib, base64
userName = base64.encodestring('from').strip()
password = base64.encodestring('password').strip()
smtp = smtplib.SMTP()
smtp.connect("smtp.yeah.net:25")
print(smtp.docmd('helo', 'from'))
print(smtp.docmd('auth login'))
print(smtp.docmd(userName))
print(smtp.docmd(password))
print(smtp.docmd('mail from:', '<from@yeah.net>'))
print(smtp.docmd('rcpt to:', '<from@yeah.net>'))
# data 指令之後才是郵件內容
print(smtp.docmd('data'))
print(smtp.docmd('''
from: from@yeah.net
to: from@yeah.net
subject: subject
email body
.
'''))
smtp.quit()
sendmail() 的第三個參數是字串,內容必須符合 SMTP 協議定義的格式。例如:
From: from@yeah.net To: to@21cn.com Subject: test just for test
這代表寄件者、收件者、標題與內文。但若郵件內容包含圖片、音訊、附件等複雜結構,手工拼接 MIME 字串會非常痛苦。Python 已就此提供 email 模組,能輕鬆組出多部分郵件。
email.mime.multipart.MIMEMultipart:多個 MIME 物件的集合。email.mime.audio.MIMEAudio:MIME 音訊物件。email.mime.image.MIMEImage:MIME 二進位(圖片)物件。email.mime.text.MIMEText:MIME 純文字物件。# coding=gbk
import smtplib, mimetypes
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
msg = MIMEMultipart()
msg['From'] = "from@yeah.net"
msg['To'] = 'to@21cn.com'
msg['Subject'] = 'email for testing'
# 加入內文
txt = MIMEText("這是郵件內容~~")
msg.attach(txt)
# 加入二進位附件
fileName = r'e:/PyQt4.rar'
ctype, encoding = mimetypes.guess_type(fileName)
if ctype is None or encoding is not None:
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
att1 = MIMEImage(
(lambda f: (f.read(), f.close()))(open(fileName, 'rb'))[0],
_subtype=subtype
)
att1.add_header('Content-Disposition', 'attachment', filename=fileName)
msg.attach(att1)
# 寄送
smtp = smtplib.SMTP()
smtp.connect('smtp.yeah.net:25')
smtp.login('from', '密碼')
smtp.sendmail('from@yeah.net', 'to@21cn.com', msg.as_string())
smtp.quit()
print('郵件發送成功')
值得補充的是,上述範例是以 Python 2 語法撰寫的(例如 print 陳述式、base64.encodestring())。在 Python 3 中請改用 print() 函式、base64.encodebytes(),並建議改用 with smtplib.SMTP_SSL(...) as server: 的上下文管理器寫法,讓連線一定會被正確關閉。更多細節可參考官方手冊的 smtplib 章節。