前言:
以前寫過一篇使用smtplib發送郵件的文章
https://www.cnblogs.com/wwho/p/8609631.html
使用 yagmail 模塊發送郵件更加簡單,四行代碼
以下是官方文檔: https://github.com/kootenpv/yagmail
使用前先要安裝 yagmail
pip install yagmail -i https://pypi.douban.com/simple
例子:簡單發送郵件
# -*- coding:utf-8 -*-
import yagmail
# 鏈接郵箱服務器
yag = yagmail.SMTP( user="157540957@qq.com", password="授權碼", host='smtp.qq.com')
"""
user: 發送的郵箱
password: 授權碼
"""
# 郵箱正文
contents = ['測試發送郵件']
# 發送郵件
yag.send(to = '3437871062@qq.com', subject='subject', contents = contents, attachments=None)
"""
to : 接收者
subject : 郵件主題
contents: 正文
attachments: 附件
"""
yag.close()
print("郵件發送成功")
發送郵件給多個人
郵件發送給多個人,將接受的郵箱放在列表中即可
# 發送郵件
yag.send(to = ['3437871062@qq.com','2222@qq.com', '333@qq.com'], subject='subject', contents = contents, attachments="")
發送郵件帶附件
# -*- coding:utf-8 -*-
import yagmail
yag = yagmail.SMTP( user="157540957@qq.com",
password="kayzilfyziulbhbb1",
host='smtp.qq.com')
"""
user: 發送的郵箱
password: 授權碼
"""
# 郵箱正文
contents = ['測試發送郵件']
# 附件
attachments = "D:\\code\\0906\\api_test009\\report\\report.html"
# 發送郵件
try:
yag.send(to = '3437871062@qq.com',
subject='subject',
contents = contents,
attachments=attachments)
except Exception as e :
print("Error: 抱歉!發送郵件失敗。", e)
"""
to : 接收者
subject : 郵件主題
contents: 正文
attachments: 附件
"""
yag.close()
封裝
# -*- coding:utf-8 -*-
import yagmail
def send(user, password, receiver):
yag = yagmail.SMTP( user=user,
password=password,
host='smtp.qq.com')
"""
user: 發送的郵箱
password: 授權碼
"""
# 郵箱正文
contents = ['測試發送郵件']
# 附件
attachments = "D:\\code\\0906\\api_test009\\report\\report.html"
# 發送郵件
try:
yag.send(to=receiver,
subject='subject',
contents = contents,
attachments=attachments)
except Exception as e :
print("Error: 抱歉!發送郵件失敗。", e)
"""
to : 接收者
subject : 郵件主題
contents: 正文
attachments: 附件
"""
yag.close()
if __name__ == '__main__':
send("157540957@qq.com", "kayzilfyziulbhbb1", "3437871062@qq.com")
------分界線------
勤則百病消除,從現在開始努力,最差的結果也是大器晚成而已,不慌!