博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
实现自动发邮件功能
阅读量:4323 次
发布时间:2019-06-06

本文共 5590 字,大约阅读时间需要 18 分钟。

在实际的项目中,当脚本执行完毕,生成测试报告,我们需要把报告通过邮件发送到对应的测试人员和开发人员,下面学习下在Python中如何实现邮件发送功能,在Python中提供了smtplib模块来发送邮件,导入smtplib,通过help函数可以查看smtp提供的方法。

在学习发邮件的过程中,只需要掌握两个模块的用法即可,smtplib和email,smtplib模块负责发送邮件(连接邮箱服务器,登录邮箱,发送邮件),email负责构造邮件(发件人,收件人,主题,正文,附件等)。

smtplib模块:

1 connect(host,port): 2 host:指定连接的邮箱服务器 3 port:指定连接服务器的端口号,默认为25 4 login(user,password): 5 usr:指定邮箱用户名 6 password:指定邮箱登录密码 7 sendmail(from_addr, to_addrs, msg): 8 from_addr:指定邮件发送者地址 9 to_addrs:指定邮箱接受者地址10 msg:发送消息:邮件内容,一般是msg.as_string()将msg(MIMEText对象或者MIMEMultipart对象)变为str。11 quit(): 用来结束SMTP回话。

email模块:

email模块下有mime包,该包下常用的三个模块是:text,image,multipart。

构造一个MIMEText对象,就表示一个文本邮件对象,构造一个MIMEImage对象,就表示一个作为附件的图片,如果要把多个对象组合到一起,则需要使用MIMEMultipart对象。

发送普通的文本:text_plain=MIMEText(text,"plain","utf-8")

发送HTML格式的文本:text_html=MIMEText(text,"html","utf-8")

在进行发送邮件时,我们需要把subject,from,to等添加到MIMEText或者MIMEMultipart对象中,因为只有这样,邮件才会显示主题,发件人,收件人等。

msg = MIMEMultipart()    msg["subject"] = "这是发送邮件的主题"    msg["from"] = sender    msg["to"] = recever

说明:如果只有一个html网页或者plain普通文本的话,msg可以是MIMEText,但是如果是多个的话(附件,文本,图片等),则msg类型要为MIMEMultipart。

1.发送HTML格式的邮件

# -*-coding:utf-8 -*-import smtplibfrom email.mime.text import MIMEText# ------1、设置发送邮件相关的参数------smtpserver ="smtp.126.com"  # 发送邮件服务器sender ="xxxxxx"  # 发送邮件的账号pwd = "xxxxxx"  # 发送邮件账号的密码receiver = "xxxxxx"  # 接收邮件的账号# ------2、编辑邮件的内容-----subject = "发送邮件的主题"  # 发送邮件的主题body = "这是发送的邮件的内容"  # 发送邮件的内容,邮件的正文为html格式msg = MIMEText(body, "html", "utf-8")  # 发送纯文本格式的邮件msg["Subject"] = subjectmsg['from'] = "xxxxxx"msg['to'] = "xxxxxx"# ------3、发送邮件------smtp = smtplib.SMTP()smtp.connect(smtpserver)  # 连接邮件服务器smtp.login(sender, pwd)  # 登录邮件服务器smtp.sendmail(sender, receiver, msg.as_string())  # 发送邮件smtp.quit()  # 关闭连接

2.发送带附件的邮件

上面的MIMEText只能发送正文格式的邮件,无法发送附件,如果想要发送带附件的邮件,需要另外一个类MIMEMultipart。

# -*-coding:utf-8 -*-import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMEText# ------1、设置发送邮件相关的参数------smtpserver ="smtp.126.com"  # 发送邮件服务器sender ="xxxxxx"  # 发送邮件的账号pwd = "xxxxxx"  # 发送邮件账号的密码receiver = "xxxxxx"  # 接收邮件的账号# ------2、编辑邮件的内容-----# 读文件file_path = "./testpro/testresult/2019-03-10 09-35-54result.html"with open(file_path, "rb") as fp:    mail_body = fp.read()msg = MIMEMultipart()msg['from'] = sendermsg['to'] = receivermsg["subject"] = "这是发送邮件的主题"# 正文body = MIMEText(mail_body, "html", "utf-8")msg.attach(body)# 附件attach = MIMEText(mail_body, "base64", "utf-8")attach["Content-Type"] = "application/octet-stream"attach["Content-Disposition"] = 'attachment; filename="testReport.html"'msg.attach(attach)# ------3、发送邮件------smtp = smtplib.SMTP()smtp.connect(smtpserver)  # 连接邮件服务器smtp.login(sender, pwd)  # 登录邮件服务器smtp.sendmail(sender, receiver, msg.as_string())  # 发送邮件smtp.quit()  # 关闭连接

 3.邮件发送最新的测试报告

# -*-coding:utf-8 -*-import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport osfrom email.header import Header# ------1、设置发送邮件相关的参数------smtpserver ="smtp.126.com"  # 发送邮件服务器sender ="xxxxxx"  # 发送邮件的账号pwd = "xxxxxx"  # 发送邮件账号的密码receiver = "xxxxxx"  # 接收邮件的账号# ------2、编辑邮件的内容-----result_dir = "./testpro/testresult/"file_list = os.listdir(result_dir)file_list.sort(key=lambda fn: os.path.getmtime(result_dir + "/" + fn))file = os.path.join(result_dir+file_list[-1])# 读文件with open(file, "rb") as fp:    mail_body = fp.read()msg = MIMEMultipart()msg["subject"] = "这是发送邮件的主题"msg["from"] = sendermsg["to"] =  receiver# 正文body = MIMEText(mail_body, "html", "utf-8")msg.attach(body)# 附件attach = MIMEText(mail_body, "base64", "utf-8")attach["Content-Type"] = "application/octet-stream"attach["Content-Disposition"] = 'attachment; filename="testReport.html"'msg.attach(attach)# ------3、发送邮件------smtp = smtplib.SMTP()smtp.connect(smtpserver)  # 连接邮件服务器smtp.login(sender, pwd)  # 登录邮件服务器smtp.sendmail(sender, receiver, msg.as_string())  # 发送邮件smtp.quit()  # 关闭连接

 4.整合自动发送邮件功能

下面根据上节的测试百度搜索和搜狗搜索的案例整合自动发送邮件功能。

# coding:utf-8import unittestfrom HTMLTestRunner import HTMLTestRunnerimport timefrom smtplib import SMTPfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartimport osdef send_mail(report):    # 设置发送邮件需要的参数    smtp_server = "smtp.126.com"    sender = "xxxxxx"    pwd = "xxxxxx"    recever = "xxxxxx"    # 设置发送邮件的内容    # 读文件    with open(report, "rb") as fp:        mail_body = fp.read()    msg = MIMEMultipart()    msg["subject"] = "这是发送邮件的主题"    msg["from"] = sender    msg["to"] = recever    # 内容    body = MIMEText(mail_body,"html","utf-8")    msg.attach(body)    # 附件    attach = MIMEText(mail_body, "base64", "utf-8")    attach["Content-Type"] = "application/octet-stream"    attach["Content-Disposition"] = 'attachment; filename="testReport.html"'    msg.attach(attach)    # 发送邮件    smtp = SMTP()    smtp.connect(smtp_server)    smtp.login(sender, pwd)    smtp.sendmail(sender, recever, msg.as_string())    smtp.quit()def find_report(file_path):    list_file = os.listdir(file_path)  # 列出该目录下的所有文件    list_file.sort(key=lambda fn: os.path.getmtime(file_path + "/" + fn))    report = os.path.join(file_path + list_file[-1])    return reportif __name__ == '__main__':    discover = unittest.defaultTestLoader.discover("./testpro/testcase/", "test*.py")    now_time = time.strftime("%Y-%m-%d %H-%M-%S")    file_name = "./testpro/testresult/"+now_time+"result.html"    file = open(file_name, "wb")    runner = HTMLTestRunner(stream=file, title="测试报告", description="测试用例执行情况")    runner.run(discover)    file.close()    new_report = find_report("./testpro/testresult/")    send_mail(new_report)    print("The end!")

 

转载于:https://www.cnblogs.com/zhuzhaoli/p/10510223.html

你可能感兴趣的文章
Java实现归并排序
查看>>
JQuery 前台传值到后台并调用后台方法
查看>>
Appium+Python3+ Android入门
查看>>
linux $ 类型变量 及Makefile 中 $ 类型变量的含义
查看>>
MyBatis插件及示例----打印每条SQL语句及其执行时间
查看>>
2.2
查看>>
[JS]事件捕获和冒泡
查看>>
【译】SQL Server误区30日谈-Day10-数据库镜像在故障发生后,马上就能发现
查看>>
linq之where子句
查看>>
Socket之UDP发送文件
查看>>
多语言在线代码编辑器,可运行程序
查看>>
C#:使用UPnP来穿透NAT使内网接口对外网可见
查看>>
js+css 实现遮罩居中弹出层(随浏览器窗口滚动条滚动)
查看>>
项目管理的小故事
查看>>
Visual Studio不显示智能提示代码,快捷键Alt+→也不出现
查看>>
多文件调用(函数、结构体)
查看>>
C# 获取本地电脑所有的盘符
查看>>
D3.js学习(三)
查看>>
汇编语言实验9
查看>>
window资源管理器下无法打开ftp站点
查看>>