Github 大牛封裝 Python 代

  • 2020 年 1 月 17 日
  • 筆記

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

一般發郵件方法

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

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

 1 import smtplib   2 from email.mime.text import MIMEText   3 from email.header import Header   4 #發送郵件伺服器   5 smtpserver = 'smtp. sina. com'   6 #發送郵件用戶/密碼   7 user = 'usernamee@sina. com'   8 password = '123456'   9 #發送郵件 python學習群984632579  10 sender = 'username@sina. com"  11 #接收郵件  12 receiver = 'receive@126. com'  13 #發送郵件主題  14 subject = 'Python email test'  15 #編寫HTML類型的郵件正文  16 msg = MIMEText('<html><h1>你好 ! </h1></html>','html','utf-8')  17 msg['Subject'] = Header(subject,'utf-8')  18 #連接發送郵件  19 smtp = smtplib.SMTP()  20 smtp.connect(smtpserver)  21 smtp.login(user,password)  22 satp.sendmail(sender, receiver, msg.as_ string())  23 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

程式碼開源,解釋如下:

1 yag = SMTP(args.user,args.password)  2 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)