在眾多以網路為基礎的應用裡,程式自動寄信是相當常見的需求。舉例來說,註冊系統會在你完成註冊時寄出一封確認信;使用者忘記密碼時,也能透過郵件找回帳號。Python 內建的 smtplib 模組,正是 SMTP(簡易郵件傳輸協定)的客戶端實作,讓我們能以極少的程式碼完成寄信工作。
先看一段不到十行就能寄出郵件的範例:
#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/nSubject: this is a email from python demo/r/n/r/nJust for test~_~') smtp.quit() 是不是相當直覺?接下來,我們就來逐一認識 smtplib 模組裡的類別與方法。
smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])
SMTP 類別的建構子代表與 SMTP 伺服器之間的一條連線。透過這條連線,我們得以向伺服器下達指令、執行登入與寄信等操作。它的所有參數都是選填的:host 指的是 SMTP 伺服器的主機名稱(範例中為「smtp.yeah.net」),port 則是服務埠,預設為 25。如果在建立 SMTP 物件時就提供了這兩個參數,初始化階段會自動呼叫 connect 方法完成連線。
此外,smtplib 還提供了 SMTP_SSL 與 LMTP 兩個類別,用法與 SMTP 大同小異。
SMTP.set_debuglevel(level)
設定是否進入除錯模式。預設為 False,也就是不輸出任何除錯資訊。
SMTP.connect([host[, port]])
連線到指定的 SMTP 伺服器,參數分別為主機與埠。值得注意的是,你也可以直接在 host 參數裡一併指定埠(例如 smtp.yeah.net:25),如此一來就不必再另外給定 port。
SMTP.docmd(cmd[, argstring])
向伺服器發送指令,選填參數 argstring 代表指令的參數。以下範例完全靠 docmd 方法發送指令來完成寄信(在 smtp.yeah.net 上測試通過,其他伺服器未逐一驗證):
import smtplib, base64, time 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() SMTP.helo([hostname]):以「helo」指令向伺服器表明身份,等同於告訴對方「我是誰」。
SMTP.has_extn(name):判斷某個名稱是否存在於伺服器的功能清單中。基於安全考量,多數伺服器已封鎖此指令。
SMTP.verify(address):確認指定郵件位址是否存在於伺服器上。同樣出於安全因素,這類指令往往被停用。
SMTP.login(user, password):登入 SMTP 伺服器。如今幾乎所有伺服器都要求先通過身分驗證,才允許寄信。
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]):寄送郵件。這裡要特別留意第三個參數 msg,它是一個字串,代表整封郵件。由於郵件通常包含標題、寄件人、收件人、內文與附件等部分,msg 必須遵循 SMTP 協定所定義的格式。以範例而言,msg 的值為:
'''''From: from@yeah.net To: to@21cn.com Subject: test just for test'''
這個字串表示寄件人為「from@yeah.net」、收件人為「to@21cn.com」、標題為「test」,內文則是「just for test」。細心的你可能會想:若郵件內容相當複雜,還得包含圖片、影片與附件,那豈不是要依照 MIME 格式辛苦拼接字串?好消息是,Python 早就替我們想好了——它提供了 email 模組,能輕鬆處理這類複雜內容。稍後我會簡單示範 email 模組的用法。
SMTP.quit():中斷與伺服器的連線,等同於送出「quit」指令。
email 模組專門用來處理郵件訊息,涵蓋 MIME 以及其他基於 RFC 2822 的規範。用它來定義郵件內容相當簡便,以下是幾個常用的類別:
光看說明或許有點抽象,其實大多數時候我們只要會用就足夠了。下面這個範例示範如何寄出一封帶附件的郵件:
#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 tesing' #添加郵件內容 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 的魅力所在。若想深入了解 smtplib,建議查閱官方文件中的 smtplib 章節。