Unittest接口和UI自动化测试框架中的发送邮件服务如何使用?

在写Unittest接口和UI自动化测试的时候,需要封装邮件模块来进行发送邮件。如何做呢?简单做一下整理。

1、在框架工具集中封装send_mail.py

如图,我的在common中封装了send_mail.py
在这里插入图片描述
代码如下:

#coding=utf-8
from email.mime.text import MIMEText
import time
import smtplib
import getpass
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import email
import os

def sendmain(file_path,mail_to = 'xxxx@sdsdsd.com'):
    mail_from = 'xxx@126.com' # 发送邮件账号
    f = open(file_path,'rb')
    mail_body=f.read()
    f.close()
    
    #msg = email.MIMEMultipart.MIMEMultipart()
    msg = MIMEMultipart()

    # 构造MIMEBase对象做为文件附件内容并附加到根容器  
    contype = 'application/octet-stream'  
    maintype, subtype = contype.split('/', 1)  
    
    ## 读入文件内容并格式化  
    data = open(file_path, 'rb')
    file_msg = MIMEBase(maintype, subtype)
    file_msg.set_payload(data.read( ))  
    data.close( )  
    encoders.encode_base64(file_msg)
    
    ## 设置附件头  
    basename = os.path.basename(file_path)  
    file_msg.add_header('Content-Disposition',  
                        'attachment', filename = basename)  
    msg.attach(file_msg)  
    print(u'msg 附件添加成功')
    
    msg1 = MIMEText(mail_body,_subtype='html',_charset='utf-8')
    msg.attach(msg1)
    
    if isinstance(mail_to,str):
        msg['To'] = mail_to
    else: 
        msg['To'] = ','.join(mail_to)
    msg['From'] = mail_from
    msg['Subject'] = u'zzzz项目接口自动化测试'
    msg['date']=time.strftime('%Y-%m-%d-%H_%M_%S')
    print(msg['date'])

    smtp = smtplib.SMTP()
    smtp.connect('smtp.126.com')
    smtp.login('xxx@126.com','123456') # 发送邮件账号密码
    smtp.sendmail(mail_from, mail_to, msg.as_string())
    smtp.quit()
    print('email has send out !')

if __name__=='__main__':
    sendmain('../report/2017-08-18-10_18_57_result.html')

2、 在主框架入口调用邮件模块

在这里插入图片描述

    # HTML报告
    now = datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S')
    htmlreport = reportpath + "/" + now + r"result.html"
    print("测试报告生成地址:%s"% htmlreport)
    fp = open(htmlreport, "wb")
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp, verbosity=2, title="xxxx项目接口自动化测试报告", description="用例执行情况")
    # 调用add_case函数返回值
    runner.run(all_case)
    fp.close()
    time.sleep(2)
    sendmain(htmlreport, mail_to=['yyyyy@qq.com']) # 填写需要发送给对方邮件账号,用逗号隔开,可写多个
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虫无涯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值