以前寫過用標準庫使用Python Smtplib和email發送郵件,感受很繁瑣,久了不用以後便忘記了。前幾天看知乎哪些Python庫讓你相見恨晚?,看到了yagmail第三方庫,學習過程當中遇到一些問題,記錄在此處。html
以前使用的python的smtplib、email模塊發模塊的一步步驟是:python
1、先導入smtplib模塊 導入MIMEText庫用來作純文本的郵件模板
2、發郵件幾個相關的參數,每一個郵箱的發件服務器不同,以126爲例子百度搜索服務器是 smtp.126.com
3、寫郵件主題和正文,這裏的正文是HTML格式的
4、最後調用SMTP發件服務
看下代碼:
import uuid import smtplib from email.mime.text import MIMEText #發郵件相關參數
smtpsever = 'smtp.126.com' sender = 'sender@126.com' psw = "126mail@126.com" #126郵箱受權碼
receiver = 'receiver@qq.com'
#編輯郵件的內容 # subject=u"NBA"
body=str(uuid.uuid4()) msg=MIMEText(body,'html','utf-8') msg['from']='username@126.com' msg['to']='userename@qq.com'
# msg['subject']=subject
try: smtp = smtplib.SMTP() smtp.connect(smtpsever) smtp.login(sender,psw) smtp.sendmail(sender,receiver,msg.as_string()) print ("郵件發送成功") except smtplib.SMTPException: print ("Error: 沒法發送郵件")
要完成上面的郵件發送,須要如下信息:git
1.發件服務器
2.發件人帳號
3.發件人郵箱密碼[指受權碼]
4.收件人帳號
5.編輯郵件內容[正文、從哪裏、到哪裏]
6.連接郵箱服務器
7.登陸郵箱[提供發件人帳號和密碼(指受權碼)]
8.發送郵件
看起來整個過程有那麼一點點複雜,可是也還好吧,畢竟功能能夠實現。。。github
可是yagmail的出現會顛覆一些人對email的印象,由於yagmail對比email來講,實現上真的是太簡單了,yagmail 在Github上Home Page給出了yagmail的簡單介紹以及使用。下面給出一個簡潔的示例:服務器
yagmail安裝dom
pip install yagmail
給單個接受者發送郵箱學習
import yagmail #連接郵箱服務器
yag = yagmail.SMTP(user="sender@126.com", password="126郵箱受權碼", 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(receiver@qq.com', 'subject', contents)
發送結果以下:ui
對比email、smtp模塊,yagmail的實現真的是太簡單了,感動的要哭了~~~~spa
給多個接受者發送郵件3d
# 發送郵件
yag.send(['aa@126.com','bb@qq.com','cc@gmail.com'], 'subject', contents)
在()內新增多個收件人的郵箱便可,其餘參數不須要修改,是否是很簡單~~~
發送帶附件的郵件
yag.send('aaaa@126.com', '發送附件', contents, ["E://whitelist.txt","E://baidu_img.jpg"])
上面的["E://whitelist.txt","E://baidu_img.jpg"]是上傳附件的路徑。返回結果以下: