出處:蟲師 python自動發郵件庫yagmail
一般發郵件方法
我以前在通過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()
其實,這段代碼也并不複雜,隻要你了解使用過郵箱發送郵件,那麼以下問題是你必須要考慮的:
你登入的郵箱帳号/密碼
對方的郵箱帳号
郵件内容(标題,正文,附件)
郵箱伺服器(SMTP.xxx.com/pop3.xxx.com)
yagmail 實作發郵件
yagmail 可以更簡單的來實作自動發郵件功能。
github項目位址:
https://github.com/kootenpv/yagmail 安裝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)
總共四行代碼搞定,是不是比上面的例子簡單太多了。
給多個使用者發送郵件yag.send(['[email protected]','[email protected]','[email protected]'],'subject', contents)
隻需要将接收郵箱 變成一個list即可。
發送帶附件的郵件yag.send('[email protected]','發送附件', contents, ["d://log.txt","d://baidu_img.jpg"])
隻需要添加要發送的附件清單即可。

我都快感動哭了,到哪兒去找這麼良心庫去?簡單的有點不像程式設計語言!