1. 程式人生 > >Github 大牛封裝 Python 代碼,實現自動發送郵件只需三行代碼

Github 大牛封裝 Python 代碼,實現自動發送郵件只需三行代碼

常見 from 自動 mime mp3 fff 如何使用 utf html

技術分享圖片
*註意:全文代碼可左右滑動觀看

在運維開發中,使用 Python 發送郵件是一個非常常見的應用場景。今天一起來探討一下,GitHub 的大牛門是如何使用 Python 封裝發送郵件代碼的。

一般發郵件方法

SMTP是發送郵件的協議,Python內置對SMTP的支持,可以發送純文本郵件、HTML郵件以及帶附件的郵件。

我們以前在通過Python實現自動化郵件功能的時候是這樣的:

import smtplib
from email.mime.text import MIMEText
from email.header import Header
#發送郵件服務器
smtpserver = ‘smtp. sina. com‘

#發送郵件用戶/密碼
user = ‘usernamee@sina. com‘
password = ‘123456‘
#發送郵件
sender = ‘username@sina. com"
#接收郵件
receiver = ‘receive@126. com‘
#發送郵件主題
subject = ‘Python email test‘
#編寫HTML類型的郵件正文
msg = MIMEText(‘<html><h1>你好 ! </h1></html>‘,‘html‘,‘utf-8‘)
msg[‘Subject‘] = Header(subject,‘utf-8‘)
#連接發送郵件
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(user,password)
satp.sendmail(sender, receiver, msg.as_ string())
satp.quit()

python發郵件需要掌握兩個模塊的用法,smtplib和email,這倆模塊是python自帶的,只需import即可使用。smtplib模塊主要負責發送郵件,email模塊主要負責構造郵件。

smtplib模塊主要負責發送郵件:是一個發送郵件的動作,連接郵箱服務器,登錄郵箱,發送郵件(有發件人,收信人,郵件內容)。

email模塊主要負責構造郵件:指的是郵箱頁面顯示的一些構造,如發件人,收件人,主題,正文,附件等。

其實,這段代碼也並不復雜,只要你理解使用過郵箱發送郵件,那麽以下問題是你必須要考慮的:

你登錄的郵箱帳號/密碼

對方的郵箱帳號

郵件內容(標題,正文,附件)

郵箱服務器(SMTP.xxx.com/pop3.xxx.com)

如果要把一個圖片嵌入到郵件正文中怎麽做?直接在HTML郵件中鏈接圖片地址行不行?答案是,大部分郵件服務商都會自動屏蔽帶有外鏈的圖片,因為不知道這些鏈接是否指向惡意網站。

要把圖片嵌入到郵件正文中,我們只需按照發送附件的方式,先把郵件作為附件添加進去,然後,在HTML中通過引用src="cid:0"就可以把附件作為圖片嵌入了。如果有多個圖片,給它們依次編號,然後引用不同的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 andio file atteched.‘,‘/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=‘發送附件‘,contend=contents)
很簡單吧,開箱即用~~

最後,如果你跟我一樣都喜歡python,也在學習python的道路上奔跑,歡迎你加入python學習群:839383765 群內每天都會分享最新業內資料,分享python免費課程,共同交流學習,讓學習變(編)成(程)一種習慣!

Github 大牛封裝 Python 代碼,實現自動發送郵件只需三行代碼