Python 的 smtplib 模块提供了发送电子邮件的功能。测试报告出来后,然后就把报告发送到邮箱。
使用QQ邮箱发送邮件,使用的是授权码,需要先到QQ邮箱申请授权码。
邮箱设置-->账户
# coding:utf-8 import smtplib from email.mime.text import MIMEText # 参数配置 smtpserver = "smtp.qq.com" # 发送邮件的服务器 port = 465 # 端口 sender = "3437871062@qq.com" # 发送的邮箱 psw = " " # QQ授权码,这里填写上自己的授权码 receiver = "1039020476@qq.com" # 接收邮件的邮箱 # 写信模板 body = '<pre><h1>测试报告,请查收`</h1></pre>' msg = MIMEText(body, 'html', "utf-8") msg['from'] = sender msg['to'] = receiver msg['subject'] = "这是自动化测试报告" # 邮件的主题 # 写信流程 try: smtp1 = smtplib.SMTP_SSL(smtpserver, port) # 实例化 smtp1.login(sender, psw) # 登录 smtp1.sendmail(sender, receiver, msg.as_string()) # 配置发送邮箱,接收邮箱,以及发送内容 smtp1.quit() # 关闭发邮件服务 print("邮件发送成功!") except smtplib.SMTPException: print("Error: 抱歉!发送邮件失败。")
发送邮件给多个领导:
# coding:utf-8 import smtplib from email.mime.text import MIMEText # 参数配置 smtpserver = "smtp.qq.com" # 发送邮件的服务器 port = 465 # 端口 sender = "3437871062@qq.com" # 发送的邮箱 psw = "tdcejfnutrascjee" # QQ授权码,这里填写上自己的授权码 # receiver = "1039020476@qq.com" # 接收邮件的邮箱 receiver = ['3437871062@qq.com', '1039020476@qq.com'] # 用列表装多个领导的邮箱 # 写信模板 body = '<pre><h1>测试报告,请查收`</h1></pre>' msg = MIMEText(body, 'html', "utf-8") msg['from'] = sender msg['to'] = ','.join(receiver) # 用join处理一下,分别发送 msg['subject'] = "这是自动化测试报告" # 邮件的主题 # 写信流程 try: smtp1 = smtplib.SMTP_SSL(smtpserver, port) # 实例化 smtp1.login(sender, psw) # 登录 smtp1.sendmail(sender, msg['to'].split(','), msg.as_string()) # 配置发送邮箱,接收邮箱,以及发送内容 smtp1.quit() # 关闭发邮件服务 print("邮件发送成功!") except smtplib.SMTPException: print("Error: 抱歉!发送邮件失败。")
这是简单的邮件内容,正文是写死的,附件也没有
======== ========= ========== ========== ========= ============= ============= ================ ================
先看下文件目录
# coding:utf-8 import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import os def send_email(smtpserver, port, sender, psw, receiver): # 写信模板 msg = MIMEMultipart() msg['Subject'] = "这是ssp项目自动化测试报告" msg['From'] = sender msg['to'] = receiver # 通过os获取文件路径 current_path = os.getcwd() # 获取当前脚本所在的文件夹路径 annex_path = os.path.join(current_path, "result.html") # 附件内容的路径 annex = open(annex_path, "r", encoding="utf-8").read() main_path = os.path.join(current_path, "text.html") # 正文内容的路径 main_body = open(main_path, "r", encoding="utf-8").read() # 添加正文到容器 body = MIMEText(main_body, "html", "utf-8") msg.attach(body) # 添加附件到容器 att = MIMEText(annex, "base64", "utf-8") att["Content-Type"] = "application/octet-sream" att["Content-Disposition"] = 'attachment;filename="ssp_test_report.html"' msg.attach(att) # 连接发送邮件 smtp = smtplib.SMTP_SSL(smtpserver, port) smtp.login(sender, psw) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit() if __name__ == "__main__": send_email("smtp.qq.com", 465, "3437871062@qq.com", "你的授权码", "1039020476@qq.com")
看下结果: