• SMTP自动发送邮件功能代码


    SMTP自动发送邮件功能

    我也是跟着各种博客一步一步搜索出来的,可能在设置邮箱的时候会有各种问题,请参考我的其他博客进行设置

    https://blog.csdn.net/ly021499/article/details/82423019

    https://blog.csdn.net/ly021499/article/details/80943030

    以下代码集成了生成测试报告和自动发送邮件等功能,使用了新的测试报告模版,个人认为美观一点,另附下载链接

    链接:https://pan.baidu.com/s/1kwh7nAdc-vC0NbEK4PfODA 
    提取码:j77w 

    #-*- coding: utf-8 -*-
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    import BSTestRunner        # 注意此处我所使用的是BSTestRunner,博客附下载链接
    import unittest
    import time
    import os
    
    '''
                                  _(\_/) 
                                 ,((((^`
                                ((((  (6  
                              ,((((( ,    
          ,,,_              ,(((((  /"._  ,`,
         ((((\ ,...       ,((((   /    `-.-'
         )))  ;'    `"'"'""((((   (      
        (((  /            (((      
         )) |                      |
        ((  |        .       '     |
        ))       _ '      `t   ,.')
        (   |   y;- -,-""'"-.   /  
        )   / ./  ) /         `  
           |./   ( (           / /'
           ||     \          //'|
           ||      \       _//'||
           ||       ))     |_/  ||
           \_     |_/          ||
           `'"                  \_
                                `'"
    '''
    
    
    # ✎﹏₯㎕﹍﹍ 定义发送邮件 ζั͡ޓއއއ๓º
    def send_mail(new_file):
        # 发信邮箱
        sender = Sender
        # 收信邮箱
        receiver = Receiver
        # 打开邮件
        efile = open(new_file, 'rb')
        email_body = efile.read()
        efile.close()
        # 实例化一个带附件的示例
        message = MIMEMultipart()
        # 定义邮件正文内容
        message.attach(MIMEText(email_body, _subtype='html', _charset='utf-8'))
    
        # 定义抬头
        message['From'] = Sender
        message['To'] = Receiver
        # 定义邮件主题
        message['Subject'] = EmailTitle
        # 定义发送时间(不定义的可能有的邮件客户端会不显示发送时间)
        message['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z')
    
        att = MIMEText(email_body, _subtype='base64', _charset='utf-8')
        # 构造附件,传送当前目录下的 test.txt 文件
        att["Content-Type"] = 'application/octet-stream'
        # 这里的filename可以任意写,写什么名字,邮件中显示什么名字
        att["Content-Disposition"] = 'attachment; filename=%s' %AttName
        message.attach(att)
    
        # 连接SMTP服务器
        smtp = smtplib.SMTP()
        smtp.connect(SMTP)
    
        # 用户名密码
        smtp.login(Sender, EmailPassword)
        smtp.sendmail(sender, receiver, message.as_string())
        smtp.quit()
    
        print('✎biubiubiu ₯㎕~~~  导弹发射成功,颤抖吧!愚蠢的人类 ޓއއއ ')
    
    # ✎﹏₯㎕﹍﹍ 查找最新生成的测试报告文件 ζั͡ޓއއއ๓º
    def send_report(testreport):
        result_dir = testreport
        lists = os.listdir(result_dir)
        lists.sort(key=lambda fn: os.path.getmtime(result_dir + "\" + fn))
        print (u'最新的导弹已制成,即将进入发射程序: '+lists[-1])
    
        # 找到最新生成的文件
        new_file = os.path.join(result_dir, lists[-1])
        print(new_file)
    
        #调用发邮件模块
        send_mail(new_file)
    
    # ✎﹏₯㎕﹍﹍ 将用例添加到测试套件 ζั͡ޓއއއ๓º
    def creatsuite():
        testunit = unittest.TestSuite()
    
        # 定义测试文件查找的目录
        testcase_path = TestCasePath
    
        # 定义 discover 方法的参数
        discover = unittest.defaultTestLoader.discover(testcase_path, pattern='test*.py',top_level_dir=None)
        # discover 方法筛选出来的用例,循环添加到测试套件中
        for test_case in discover:
            print(test_case)
            testunit.addTests(test_case)
    
        return testunit
    
    def main():
        now = time.strftime("%Y-%m-%d %H_%M")
        # 报告存储的路径
        report_path = ReportPath
        # 构建文件完整路径
        filename = report_path + ReportName + now + '.html'
        # 打开报告文件
        file = open(filename, 'wb')
        # 设置报告头部信息
        runner = BSTestRunner.BSTestRunner(stream=file, title=Title,
                                           description=Description)
        # 拿到测试套件并运行
        all_test_case = creatsuite()
        runner.run(all_test_case)
        # 关闭生成的报告
        file.close()
        # 发送报告
        send_report(ReportPath)
    
    if __name__ == '__main__':
        # 设置发信邮箱
        Sender = 'xxx@yyy.com'       # 发信邮箱账号
        # 设置收信邮箱
        Receiver= 'xxxxxx@qq.com'    # 收信邮箱密码
        # 设置发信邮箱密码
        EmailPassword = 'xxxxxxx'    # 此处填写你在邮箱生成的客户端专用密码
        # 设置邮件标题
        EmailTitle = u"自动化测试报告"
        # 设置邮件正文内容
        BodyContent = '此邮件为执行自动化脚本后自动发送邮件,请勿回复!'
        # 设置邮件附件名称
        AttName = "TestReport.html"
        # 设置testCase存储路径
        TestCasePath = os.path.dirname(os.path.abspath('.')) + '\testcase'
        # 设置SMTP服务器-(现在用的QQ邮箱服务器)
        SMTP = "smtp.exmail.qq.com"
        # 设置报告的名字
        ReportName = 'TestReport '
        # 设置报告存储的路径
        ReportPath = os.path.dirname(os.path.abspath('.')) + '\reports\'
        # 设置报告主题
        Title = u'Big data platform'
        # 设置报告描述内容
        Description = u'This is the automation test report of the big data platform for reference only.'
        # 调用main()方法启动程序
        main()
    
    
    
    
  • 相关阅读:
    iOS开发技巧,细节
    一个PO审批的自动触发问题
    SAP Workflow(一)
    【S4 导数据】S/4HANA导数,只会LSMW远远不够(转)
    【MM】采购订单文本(二)
    【MM】 采购订单长文本(一)
    SAP Create Background Job定义后台作业
    No.595-Big Countries-(LeetCode之Database篇)
    设计模式之单例模式
    你一定能看懂的JDK动态代理
  • 原文地址:https://www.cnblogs.com/xianyulouie/p/11041804.html
Copyright © 2020-2023  润新知