zoukankan      html  css  js  c++  java
  • selenium2学习:单元测试框架(6):自动发送邮件

    1.1     自动发送邮件

    1.1.1      自动发送(无附件)

    Python的smtplib模块提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。使用SMTP对象的sendmail方法发送邮件。

    内容如下编写:

    '''发送邮件:正文'''
    # coding=utf-8  
    import smtplib  
    from email.mime.text import MIMEText  
    from email.header import Header
    
    #发送邮箱服务器
    smtpserver="smtp.126.com"
    #发送邮箱用户名和密码
    username="tianshixia111@126.com"  
    password="1121228" 
    
    #发送邮箱
    sender="tianshi1212@126.com"
    #接收邮箱
    receiver="tianshi1111@126.com"
    #邮件主题
    subject="邮件主题信息:标题,是的,就酱~~~"
    
    #html类型的邮件正文 
    msg=MIMEText('<html><h1>同学你好~!这是自动发给你的邮件,请问怎么文字换行显示呢?</h1></html>','html','utf-8')  
    msg['subject']=Header(subject,'utf-8')
     
    #连接发送邮件
    smtp=smtplib.SMTP()  
    smtp.connect(smtpserver)  
    smtp.login(username,password)  
    smtp.sendmail(sender,receiver,msg.as_string())  
    smtp.quit() 

    邮件内容:

     

    1.1.2      自动发送含附件

    # 发送邮件:附件
    # coding=utf-8  
    import smtplib  
    from email.mime.text import MIMEText   #MIMRText()定义邮件正文  
    from email.header import Header
    from email.mime.multipart import MIMEMultipart   #MIMEMulipart模块构造带附件
    
    #发送邮箱服务器
    smtpserver="smtp.126.com"
    #发送邮箱用户名和密码
    username="tianshixiao8@126.com"  
    password="jxba0128" 
    
    #发送邮箱
    sender="tianshixiao8@126.com"
    #接收邮箱
    receiver="tianshixiao8@126.com"
    #邮件主题
    subject="邮件主题信息:标题,有附件,是的~就酱~~~"
    #发送附件
    sendfile = open('D:Report_180519-120941.html','rb').read()
    att = MIMEText(sendfile,'base64','utf-8')
    att["Content-Type"] = "application/octet-stream"  
    att["Content-Disposition"] = 'attachment;filename = "Report_180519-120941.html"'
    
    msgroot = MIMEMultipart('related')
    msgroot['Subject'] = subject
    msgroot.attach(att)
    
    
    #连接发送邮件
    smtp=smtplib.SMTP()  
    smtp.connect(smtpserver)  
    smtp.login(username,password)  
    smtp.sendmail(sender,receiver,msgroot.as_string())  
    smtp.quit()  

    邮件内容:

     

    注:原来本句为如下编写:

    att["Content-Disposition"] = "attachment;filename = 'Report_180519-120941.html'"

    导致邮件的附件含’’,如下图

     

    后改为:
    att["Content-Disposition"] = 'attachment;filename = "Report_180519-120941.html"' 正常。

    1.1.3      查找最新报告(筛选文件)

    # 查找最新的html文件
    #coding=utf-8  
    import os
    
    #定义文件目录
    result_dir=".\"  
    lists=os.listdir(result_dir) #将文件放在列表中
    reports = []
    for file in lists:         
        if file.startswith("Report") and file.endswith(".html"):  #筛选以Report开头的html格式的文件
            reports.append(file)
            
    # 排序html格式的文件        
    reports.sort(key=lambda fn: os.path.getmtime(result_dir+"\"+fn))
    #打印出最新的文件
    print (reports[-1]) 
    file=os.path.join(result_dir,reports[-1])  
    print (file) 

    1.1.4      整合自动发送邮件

    步骤:

    1、  通过unittest框架的discover()找到匹配的测试用例,由HTMLTestRunner的run()方法执行测试用例并生成测试报告;

    2、  调用第一种写法的findnew()的findfile()或第二种写法findfile()找到最新的测试报告,返回测试报告的路径;

    3、  将该报告传给send_mail()函数,将报告以正文的形式发送。

    粗糙暴力写法:

    # 因为原目录下不仅仅有report文件,所以对report文件进行了筛选
    # =====查找最新的html文件(在筛选后的文件列表中排序寻找最新的)
    #coding=utf-8  
    import os
    class findnew():
        def __init__(self,result_dir,lists):
            self.result_dir = result_dir
            self.lists = lists
        def findfile(self):
            #定义文件目录
            self.lists.sort(key=lambda fn: os.path.getmtime(self.result_dir+"\"+fn))   # 排序html格式的文件
            file1=os.path.join(self.result_dir,reports[-1])                   #返回最新的文件
            return file1
    
    
    
    
    # =====发送邮件:附件
    # coding=utf-8  
    import smtplib  
    from email.mime.text import MIMEText                   #MIMRText()定义邮件正文  
    from email.header import Header
    from email.mime.multipart import MIMEMultipart         #MIMEMulipart模块构造带附件
    
    def send_mail(reportfile):
        f = open(reportfile,'rb')                              #将报告的内容赋给变量mail_body
        mail_body = f.read()
        f.close()
        #发送邮箱服务器
        smtpserver="smtp.126.com"
        #发送邮箱用户名和密码
        username="tianshixiao8@126.com"
        password="jxba0128"
    
        #发送邮箱
        sender="tianshixiao8@126.com"
        #接收邮箱
        receiver="tianshixiao8@126.com"
        #邮件主题
        subject="邮件主题信息:标题,有附件,是的~就酱~~~"
        
        msg = MIMEText(mail_body,'html','utf-8')              #正文为报告的内容
        msg['subject']=Header(subject,'utf-8')
    
        #连接发送邮件
        smtp=smtplib.SMTP()
        smtp.connect(smtpserver)
        smtp.login(username,password)
        smtp.sendmail(sender,receiver,msg.as_string())
        smtp.quit()
    
    
    # ======生成报告
    import unittest
    from HTMLTestRunner import HTMLTestRunner
    import time
    
    if __name__ == '__main__':
        #定义测试用例的目录为当前目录
        test_dir = '.\'
        discover = unittest.defaultTestLoader.discover(test_dir, pattern='test*.py')
        now = time.strftime("%y%m%d-%H%M%S")
        filename = test_dir + '/' + 'Report_' + now + '.html'
        fp = open(filename,'wb')
        runner = HTMLTestRunner(stream=fp,  #stream指定测试报告文件
                                title='计算器测试报告',   #测试报告标题
                                description='用例执行情况如下:')  #副标题
    
        runner.run(discover)
        fp.close()
    
        lists1=os.listdir(test_dir) #将文件放在列表中
        reports = []
        for file in lists1:
            if file.startswith("Report") and file.endswith(".html"):  #筛选以Report开头的html格式的文件
                reports.append(file)
                
        newreport = findnew(test_dir,reports).findfile()
        print(newreport)
        send_mail(newreport)

     另一种精致写法:

    import os
    import smtplib  
    from email.mime.text import MIMEText                   #MIMRText()定义邮件正文  
    from email.header import Header
    from email.mime.multipart import MIMEMultipart         #MIMEMulipart模块构造带附件
    import unittest
    from HTMLTestRunner import HTMLTestRunner
    import time
    
    #coding=utf-8 
    # 因为原目录下不仅仅有report文件,所以对report文件进行了筛选
    # =====查找最新的html文件(先对文件进行筛选,然后再在筛选后的文件列表中排序寻找最新的)
    def findfile(result_dir):
        lists1=os.listdir(result_dir) #将文件放在列表中
        reports = []
        for file in lists1:
            if file.startswith("Report") and file.endswith(".html"):  #筛选以Report开头的html格式的文件
                reports.append(file)
        reports.sort(key=lambda fn: os.path.getmtime(result_dir+"\"+fn))   # 排序html格式的文件
        file1=os.path.join(result_dir,reports[-1])                   #返回最新的文件
        return file1   
    
    
    # =====发送邮件:附件 
    def send_mail(reportfile):
        f = open(reportfile,'rb')                              #将报告的内容赋给变量mail_body
        mail_body = f.read()
        f.close()
        #发送邮箱服务器
        smtpserver="smtp.126.com"
        #发送邮箱用户名和密码
        username="tianshixiao8@126.com"
        password="jxba0128"
    
        #发送邮箱
        sender="tianshixiao8@126.com"
        #接收邮箱
        receiver="tianshixiao8@126.com"
        #邮件主题
        subject="邮件主题信息:标题,有附件,是的~就酱~~~"
        
        msg = MIMEText(mail_body,'html','utf-8')              #正文为报告的内容
        msg['subject']=Header(subject,'utf-8')
    
        #连接发送邮件
        smtp=smtplib.SMTP()
        smtp.connect(smtpserver)
        smtp.login(username,password)
        smtp.sendmail(sender,receiver,msg.as_string())
        smtp.quit()
    
    
    # ======生成报告,并发送
    if __name__ == '__main__':
        #定义测试用例的目录为当前目录
        test_dir = '.\'
        discover = unittest.defaultTestLoader.discover(test_dir, pattern='test*.py')
        now = time.strftime("%y%m%d-%H%M%S")
        filename = test_dir + '/' + 'Report_' + now + '.html'
        fp = open(filename,'wb')
        runner = HTMLTestRunner(stream=fp,  #stream指定测试报告文件
                                title='计算器测试报告',   #测试报告标题
                                description='用例执行情况如下:')  #副标题
        runner.run(discover)
        fp.close()
    
        newreport = findfile(test_dir)
        send_mail(newreport)

    执行结果:

     
     
     
     
     
  • 相关阅读:
    【数据库学习笔记】什么是DBO?
    【计算机网络学习笔记】端口号
    【计算机网络学习笔记】什么是cookie以及cookie劫持的基本概念
    【python学习笔记】pthon3.x中的文件读写操作
    【Java学习笔记】JFrame类的pack()与validate()方法的区别(待补充)
    【python学习笔记】python中的模块,类,函数,对象,实例(与JAVA的比较)
    virtual hust 2013.6.23 数学杂题基础题目 M
    virtual hust 2013.6.23 数学杂题基础题目 F
    virtual hust 2013.6.23 数学杂题基础题目 E
    virtual hust 2013.6.23 数学杂题基础题目 D
  • 原文地址:https://www.cnblogs.com/jxba/p/9060160.html
Copyright © 2011-2022 走看看