之前寫過用標准庫使用Python Smtplib和email發送郵件,感覺很繁瑣,久了不用之后便忘記了。前幾天看知乎哪些Python庫讓你相見恨晚?,看到了yagmail第三方庫,學習過程中遇到一些問題,記錄在此處。
之前使用的python的smtplib、email模塊發模塊的一步步驟是:
一、先導入smtplib模塊 導入MIMEText庫用來做純文本的郵件模板
二、發郵件幾個相關的參數,每個郵箱的發件服務器不一樣,以126為例子百度搜索服務器是 smtp.126.com
三、寫郵件主題和正文,這里的正文是HTML格式的
四、最后調用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: 無法發送郵件")
要完成上面的郵件發送,需要以下信息:
1.發件服務器
2.發件人賬號
3.發件人郵箱密碼[指授權碼]
4.收件人賬號
5.編輯郵件內容[正文、從哪里、到哪里]
6.鏈接郵箱服務器
7.登錄郵箱[提供發件人賬號和密碼(指授權碼)]
8.發送郵件
看起來整個過程有那么一點點復雜,但是也還好吧,畢竟功能可以實現。。。
但是yagmail的出現會顛覆一些人對email的印象,因為yagmail對比email來說,實現上真的是太簡單了,yagmail 在Github上Home Page給出了yagmail的簡單介紹以及使用。下面給出一個簡潔的示例:
yagmail安裝
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)
發送結果如下:
對比email、smtp模塊,yagmail的實現真的是太簡單了,感動的要哭了~~~~
給多個接受者發送郵件
# 發送郵件
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"]是上傳附件的路徑。返回結果如下: