使用Python發(fā)送各種形式的郵件的方法匯總
我們平時需要使用 Python 發(fā)送各類郵件,這個需求怎么來實現(xiàn)?答案其實很簡單,smtplib 和 email 庫可以幫忙實現(xiàn)這個需求。smtplib 和 email 的組合可以用來發(fā)送各類郵件:普通文本,HTML 形式,帶附件,群發(fā)郵件,帶圖片的郵件等等。我們這里將會分幾節(jié)把發(fā)送郵件功能解釋完成。
smtplib 是 Python 用來發(fā)送郵件的模塊,email 是用來處理郵件消息。
發(fā)送 HTML 形式的郵件
發(fā)送 HTML 形式的郵件,需要 email.mime.text 中的 MIMEText 的 _subtype 設置為 html,并且 _text 的內(nèi)容應該為 HTML 形式。
import smtplib from email.mime.text import MIMEText sender = '***' receiver = '***' subject = 'python email test' smtpserver = 'smtp.163.com' username = '***' password = '***' msg = MIMEText(u'''<pre> <h1>你好</h1> </pre>''','html','utf-8') msg['Subject'] = subject smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit()
注意:這里的代碼并沒有把異常處理加入,需要讀者自己處理異常。
發(fā)送帶圖片的郵件
發(fā)送帶圖片的郵件是利用 email.mime.multipart 的 MIMEMultipart 以及 email.mime.image 的 MIMEImage:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'
msgText = MIMEText(
'''<b> Some <i> HTML </i> text </b > and an image.<img alt="" src="cid:image1"/>good!''', 'html', 'utf-8')
msgRoot.attach(msgText)
fp = open('/Users/1.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msgRoot.as_string())
smtp.quit()
發(fā)送帶附件的郵件
發(fā)送帶附件的郵件是利用 email.mime.multipart 的 MIMEMultipart 以及 email.mime.image 的 MIMEImage,重點是構(gòu)造郵件頭信息:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'
msgRoot = MIMEMultipart('mixed')
msgRoot['Subject'] = 'test message'
# 構(gòu)造附件
att = MIMEText(open('/Users/1.jpg', 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="1.jpg"'
msgRoot.attach(att)
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msgRoot.as_string())
smtp.quit()
相關(guān)文章
Python?pandas找出、刪除重復的數(shù)據(jù)實例
在面試中很可能遇到給定一個含有重復元素的列表,刪除其中重復的元素,下面這篇文章主要給大家介紹了關(guān)于Python?pandas找出、刪除重復數(shù)據(jù)的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-07-07
Pytorch實現(xiàn)神經(jīng)網(wǎng)絡的分類方式
今天小編就為大家分享一篇Pytorch實現(xiàn)神經(jīng)網(wǎng)絡的分類方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
python+html實現(xiàn)前后端數(shù)據(jù)交互界面顯示的全過程
最近項目中采用了前后端分離的技術(shù),感覺有必要給大家總結(jié)下,所以下面這篇文章主要給大家介紹了關(guān)于python+html實現(xiàn)前后端數(shù)據(jù)交互界面顯示的相關(guān)資料,需要的朋友可以參考下2022-06-06

