yagmail的GitHub地址:https://github.com/kootenpv/yagmail
import yagmail
#登陸自己的郵箱
yagmail.register('yourmail@163.com','password')
yag = yagmail.SMTP(user="yourmail@163.com", password="password",host='smtp.163.com')
#編輯郵件內容
contentsbody = ['這是一封測試郵件']
#發送郵件
yag.send(to = 'person1@163.com', subject='[title:測試郵件]', contents = contentsbody)
發送成功后,郵箱里就收到了你剛才編輯后的郵件了。
如果想要發送帶html格式的郵件:
先在文件目錄下編輯一個郵件模板html文檔,再讀取為內容:
# 編輯郵件
#讀取郵件模板
file_object = open('mailcontent.html')
try:
contentsbody = file_object.read()
finally:
file_object.close( )
contents = contentsbody
#發送郵件
yag.send(to = 'winterfzw@163.com', subject='[html郵件]', contents = contents)
print("郵件發送成功")
出現問題:
1、yagmail默認使用Gmail郵箱服務,因此在第一步登陸中,遇到服務器沒法發送的問題。
我一開始是修改了yagmail里sender.py中的配置信息,把host手動改成了host='smtp.163.com',后來發現可以直接在yag = yagmail.SMTP里設置參數。