1. 程式人生 > >python中三行程式碼搞定發郵件

python中三行程式碼搞定發郵件

一般發郵件方法

我以前在通過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

Github大牛封裝Python程式碼,如今實現自動傳送郵件只需三行程式碼

 

 

程式碼開源,解釋如下:

yag = SMTP(args.user, args.password)
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 audio file attached.', '/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"])

Github大牛封裝Python程式碼,如今實現自動傳送郵件只需三行程式碼

 

抄送

# 郵箱正文 文字及附件
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='傳送附件', contents=contents)

真是簡單,誰做得這個包,我真想給一個麼麼噠