Python最良心的郵件發送庫--yagmail

發現一個特別良心的庫,能把我們從發郵件的繁複代碼中解救出來,下面我們來看一下它和我們平常實用最多的smtplib的使用對比。

原文鏈接:
http://www.cnblogs.com/fnng/p/7967213.html

一般發郵件方法

我以前在通過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><h1>你好!</h1></html>','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"])

只需要添加要發送的附件列表即可。
image
我都快感動哭了,到哪兒去找這麼良心庫去?簡單的有點不像編程語言!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章