在運維開發中,使用 Python 發送郵件是一個非常常見的應用場景。今天一起來探討一下,GitHub 的大牛門是如何使用 Python 封裝發送郵件代碼的。
一般發郵件方法
SMTP是發送郵件的協議,Python內置對SMTP的支持,可以發送純文本郵件、HTML郵件以及帶附件的郵件。
這裡也要注意:不管你是剛學Python還是想找python高薪工作,記住:項目開發經驗永遠是核心,如果你沒有python入門到高級實戰視頻教程,可以關注我,後臺私信我 ‘py’ 自動獲取最新python教程資料!還有老司機解答哦!
本文的文字及圖片來源於網絡加上自己的想法,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯繫我們以作處理。
我們以前在通過Python實現自動化郵件功能的時候是這樣的:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 發送郵箱服務器
smtpserver = 'smtp.sina.com'
# 發送郵箱用戶/密碼
user = '[email protected]'
password = '123456'
# 發送郵箱
sender = '[email protected]'
# 接收郵箱
receiver = '[email protected]'
# 發送郵件主題
subject = 'Python email test'
# 編寫HTML類型的郵件正文
msg = MIMEText('
你好!
','html','utf-8')msg['Subject'] = Header(subject, 'utf-8')
# 連接發送郵件
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(user, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
python發郵件需要掌握兩個模塊的用法,smtplib和email,這倆模塊是python自帶的,只需import即可使用。smtplib模塊主要負責發送郵件,email模塊主要負責構造郵件。
smtplib模塊主要負責發送郵件:是一個發送郵件的動作,連接郵箱服務器,登錄郵箱,發送郵件(有發件人,收信人,郵件內容)。
email模塊主要負責構造郵件:指的是郵箱頁面顯示的一些構造,如發件人,收件人,主題,正文,附件等。
其實,這段代碼也並不複雜,只要你理解使用過郵箱發送郵件,那麼以下問題是你必須要考慮的:
你登錄的郵箱帳號/密碼
對方的郵箱帳號
郵件內容(標題,正文,附件)
郵箱服務器(SMTP.xxx.com/pop3.xxx.com)
如果要把一個圖片嵌入到郵件正文中怎麼做?直接在HTML郵件中鏈接圖片地址行不行?答案是,大部分郵件服務商都會自動屏蔽帶有外鏈的圖片,因為不知道這些鏈接是否指向惡意網站。
要把圖片嵌入到郵件正文中,我們只需按照發送附件的方式,先把郵件作為附件添加進去,然後,在HTML中通過引用class="lazy" src="//p2.ttnews.xyz/loading.gif" data-original="//p2.ttnews.xyz/6013900fd7df042770ad0036.jpg"就可以把附件作為圖片嵌入了。如果有多個圖片,給它們依次編號,然後引用不同的cid:x即可。
yagmail 實現發郵件
yagmail 可以更簡單的來實現自動發郵件功能。
github項目地址: https://github.com/kootenpv/yagmail
代碼開源,解釋如下:
yag = SMTP(args.user, args.password)
yag.send(to=args.to, subject=args.subject, contents=args.contents, attachments=args.attachments)
安裝:
pip install yagmail
簡單例子:
import yagmail
#鏈接郵箱服務器
yag = yagmail.SMTP( user="[email protected]", password="1234", host='smtp.126.com')
# 郵箱正文
contents = ['This is the body, and here is just text http://somedomain/image.png',
'You can find an audio file attached.', '/local/path/song.mp3']
# 發送郵件
yag.send('[email protected]', 'subject', contents)
給多個用戶發郵件:
只需要將接收郵箱 變成一個list即可。
yag.send(['[email protected]','[email protected]','[email protected]'], 'subject', contents)
發送附件
如何發送附件呢?只要添加一個附件列表就可以了。
yag.send('[email protected]', '發送附件', contents, ["d://log.txt","d://baidu_img.jpg"])
抄送
# 郵箱正文 文本及附件
contents = ['This is the body, and here is just text http://somedomain/image.png',
'You can find an audio file attached.', '/local/path/song.mp3', '測試郵件', 'test.html', 'logo.jpg',
'yagmal_test.txt']
# 發送
yag.send(to='[email protected]', cc='[email protected]', subject='發送附件', contents=contents)
很簡單吧,開箱即用~~ 注意:不管你是剛學Python還是想找python高薪工作,記住:項目開發經驗永遠是核心,如果你沒有python入門到高級實戰視頻教程,可以關注我,後臺私信我 ‘py’ 自動獲取最新python教程資料!還有老司機解答哦!
本文的文字及圖片來源於網絡加上自己的想法,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯繫我們以作處理。
本文的文字及圖片來源於網絡加上自己的想法,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯繫我們以作處理。