开发小学生

导航

python 发送邮件-带附件

"""
使用yagmail 第三方库实现发送邮件
"""

import yagmail
import re


class send_email():
# 初始化参数
# subject='这是测试邮件标题',contents=None,report = None
def __init__(self, user='****@hoperun.com'):
self.to_user = user
# self.subject = subject
# self.contents = contents
# self.report = report

# 邮件发送
def send_mail(self, subject='这是测试邮件标题', contents='邮件发送成功', report=None):
# 判断report的路径格式是否正确
re_windows = "[a-zA-Z.]:*?((\\\)\w+)+(\\\)[\d+ _-]*\w+.html"
if not re.match(re_windows, report):
return "report路径错误"
# 建立邮箱连接
yag = yagmail.SMTP(user='*****@163.com', password='hj19881018', host='smtp.163.com')
# 判断是否带附件发送
if report:
yag.send(self.to_user, subject, contents, report)
print("带有report的邮件发送成功")
else:
yag.send(self.to_user, subject, contents)
print("无report的邮件发送成功")


if __name__ == "__main__":
# 邮件标题
subject = '这是一个测试'

# 邮件正文
contents = ['正文1\n', '正文2\n']
# 附件地址
report_path = "D:\\unittest\\test_report\\2021-08-05 16_44_48result.html"
mail = send_email()
mail.send_mail(report=report_path)

posted on 2021-08-06 16:33  开发小学生  阅读(239)  评论(0编辑  收藏  举报