python 邮件发送

各种邮件类型参考https://www.runoob.com/python/python-email.html

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import  formataddr
import os,sys
import time
from config.config import  reportpath
reportPath = reportpath  # 测试报告的路径

class SendEmail():
    def __init__(self):
        #第三方SMTP服务
        self.email_host = "smtp.exmail.qq.com"# 设置服务器
        self.send_user = "xx@qq.com"  # 登录邮箱的用户名
        self.password= "xxxxx"  # 授权码

    def get_report(self):# 该函数的作用是为了在测试报告的路径下找到最新的测试报告
        dirs = os.listdir(reportPath)
        dirs.sort()
        print("路径%s"%dirs)
        newreportname = dirs[0]
        print('The new report name: {0}'.format(newreportname))
        return newreportname  # 返回的是测试报告的名字

    def send_mail(self,user_list,sub,content):
        #创建一个带附件的实例
        message=MIMEMultipart()
        message['Subject']=sub#发送邮件主题
        message['From']=self.send_user#发送邮件用户
        message['To']=";".join(user_list)#发送对象
        newreport = self.get_report()#获取最新报告文件
        message['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z')
        with open(os.path.join(reportPath, newreport), 'rb') as f:
            mailbody = f.read()  # 读取测试报告的内容
        html = MIMEText(mailbody, _subtype='html', _charset='utf-8')  # 将测试报告的内容放在 邮件的正文当中
        message.attach(html)  # 将html附加在msg里
        # html附件    下面是将测试报告放在附件中发送
        att1 = MIMEText(mailbody, 'base64', 'gb2312')
        att1["Content-Type"] = 'application/octet-stream'
        att1["Content-Disposition"] = 'attachment; filename="TestReport.html"'  # 这里的filename可以任意写,写什么名字,附件的名字就是什么
        message.attach(att1)

        # 异常处理
        try:
            #连接邮箱服务
            server=smtplib.SMTP()
            server.connect(self.email_host)
            server.login(self.send_user,self.password)
            server.sendmail(self.send_user,user_list,message.as_string())
            print("发送成功")
            server.close()

        except smtplib.SMTPException:
            print ("Error:无法发送邮件")


    def send_main(self,pass_list=[],fail_list=[]):

        pass_num=float(len(pass_list))
        fail_num=float(len(fail_list))
        count_num=pass_num +fail_num
        user_list = ['jenny.zhang@wetax.com.cn']
        sub = "接口自动化测试报告"
        content = "此次一共运行接口个数为%s个,通过个数为%s个,失败个数为%s" % (count_num, pass_num, fail_num)
        self.send_mail(user_list, sub, content)#调用发送邮件的方法


if __name__=="__main__":#发送邮件包含成功与失败个数调试
    sen=SendEmail()
    user_list=["jenny.zhang@wetax.com.cn"]
    sub="接口自动化测试"
    content='hehheheheh'
    sen.send_mail(user_list,sub,content)
    

 

posted @ 2019-06-08 22:33  行走的小z  阅读(129)  评论(0编辑  收藏  举报