我們平時需要使用 Python 發送各類郵件,這個需求怎么來實現?答案其實很簡單,[smtplib](https://docs.python.org/2/library/smtplib.html)?和?[email](https://docs.python.org/2/library/email.html)庫可以幫忙實現這個需求。[smtplib](https://docs.python.org/2/library/smtplib.html)?和?[email](https://docs.python.org/2/library/email.html)?的組合可以用來發送各類郵件:普通文本,HTML 形式,帶附件,群發郵件,帶圖片的郵件等等。我們這里將會分幾節把發送郵件功能解釋完成。
[smtplib](https://docs.python.org/2/library/smtplib.html)?是 Python 用來發送郵件的模塊,[email](https://docs.python.org/2/library/email.html)?是用來處理郵件消息。
發送普通文本的郵件,只需要 email.mime.text 中的 MIMEText 的 _subtype 設置為 plain。首先導入 smtplib 和 mimetext。創建 smtplib.smtp 實例,connect 郵件 smtp 服務器,login 后發送:
~~~
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'
msg = MIMEText(u'你好','plain','utf-8')#中文需參數‘utf-8',單字節字符不需要
msg['Subject'] = Header(subject, 'utf-8')
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
~~~
注意:這里的代碼并沒有把異常處理加入,需要讀者自己處理異常。