Python3 自动发邮件

版权声明: https://blog.csdn.net/shijianzhihu/article/details/86291650

背景:当UI Recorder录制的GUI自动化脚本回放失败时,自动发邮件通知,并打包测试报告作为附件发送。

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Created on 2018年12月28日
@author: Rethink
'''
import re
import os
from datetime import datetime
import zipfile
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders


def get_email_obj(email_subject, email_sender, email_receivers):
    '''
    构造邮件对象
    :param email_subject:邮件主题
    :param email_sender:发件人
    :param email_receivers:收件人列表
    :return 邮件对象
    '''
    email_obj = MIMEMultipart()
    email_obj["subject"] = Header(email_subject, "utf-8")
    email_obj["From"] = Header(email_sender, "utf-8")
    email_obj["To"] = Header(','.join(email_receivers), "utf-8")
    return email_obj


def attach_content(email_obj, email_content, content_type="plain", content_charset="utf-8"):
    '''
    创建邮件正文,并将其附加到根容器:正文格式支持plain/html
    :param email_obj:邮件对象
    :param email_content:邮件正文
    :param content_type:邮件正文格式
    :param content_charset:邮件正文编码
    '''
    content = MIMEText(email_content, content_type, content_charset)
    email_obj.attach(content)


def attach_part(email_obj, source_path, part_name):
    '''
    添加附件:附件可以为照片,也可以是文档
    :param email_obj:邮件对象
    :param source_path:资源路径
    :param part_name:附件名称
    '''
    part = MIMEBase('application', 'octet-stream')    # 创建附件对象
    part.set_payload(open(source_path, 'rb').read()
                     )                        # 将附件源文件加载到附件对象
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment',
                    filename=('gbk', '', '%s' % part_name))     # 给附件添加头文件
    email_obj.attach(part)


def send_email(email_obj, email_host, host_port, sender, sender_pwd, receivers):
    '''
    发送邮件
    :param email_obj:邮件对象
    :param email_host:SMTP服务器主机
    :param host_port:SMTP服务端口号
    :param sender:发件地址
    :param sender_pwd:发件地址授权码,而非密码
    :param receivers:收件地址列表,list
    :return 发送成功,返回 True;发送失败,返回 False
    '''
    try:
        smtp_obj = smtplib.SMTP_SSL(email_host, host_port)
        smtp_obj.set_debuglevel(1)   # 打印与邮件服务器的交互信息
        smtp_obj.login(sender, sender_pwd)
        smtp_obj.sendmail(sender, receivers, email_obj.as_string())
        smtp_obj.quit()
        print("邮件发送成功 ,发件人为:%s,收件人为: %s" % (sender, receivers))
        return True
    except smtplib.SMTPException as e:
        print("Error,无法发送邮件: %s" % e)
        return False


def createZip(file_path, save_path, note=""):
    '''
    打包测试报告目录
    :param file_path: 目标目录路径
    :param save_path: 保存路径
    :param note: 备份文件说明,会在压缩文件名中展示
    :return 压缩文件完整保存路径
    '''
    now = datetime.now().strftime("%Y%m%d%H%M%S")
    fileList = []
    if len(note) == 0:
        target = save_path + os.sep + now + ".zip"
    else:
        target = save_path + os.sep + now + "_" + str(note) + ".zip"
    newZip = zipfile.ZipFile(target, 'w')
    for dirpath, dirnames, filenames in os.walk(file_path):
        for filename in filenames:
            fileList.append(os.path.join(dirpath, filename))
    for tar in fileList:
        # tar为写入的文件,tar[len(filePath)]为保存的文件名
        newZip.write(tar, tar[len(file_path):])
    newZip.close()
    return target

if __name__ == "__main__":
    # QQ邮箱SMTP服务器
    mail_host = "smtp.exmail.qq.com"    # 发件服务器(企业邮箱)
    host_port = 465
    mail_user = "YOUR EMAIL"
    mail_pwd = "YOUR PASSWORD"  # 密码

    # mail_host = "smtp.qq.com"    # 发件服务器(个人邮箱,注意和企业邮箱是不同的服务器)
    # host_port = 465
    # mail_user = "YOUR EMAIL"
    # mail_pwd = "YOUR CODE"   # 授权码

    script_path = "E:/uirecorder"
    os.chdir(script_path)
    os.system("run.bat ./sample/park.spec.js")

    with open("./reports/index.json", mode="r", encoding="utf-8") as f:
        a = f. readlines()
        suites, tests, passes, pending, failures, start, end, duration, passPercent = a[
            3].strip(), a[4].strip(), a[5].strip(), a[6].strip(), a[7].strip(), a[8].strip(), a[9].strip(), a[10].strip(), a[12].strip()
        result = "\n".join(
            (suites, tests, passes, pending, failures, start, end, duration, passPercent))
        failNum = re.search("(\d+)", failures).group()

    if int(failNum) == 0:
        print("GUI Test Success! 用例运行成功,无须发邮件通知")
    if int(failNum) != 0:
        email_content = "Hi,all\n" + "GUI Test Fail! 运行结果摘要如下:\n" + \
            "\t" + result + "\n完整测试报告以及报错截图见附件"

        email_subject = "UI Recorder Script Running Failed"
        test_result_path = createZip("./reports",
                                     "./reports_zip", note="rethink")
        source_path1 = "./reports/index.json"
        source_path2 = test_result_path
        part_name1 = "index.json"
        part_name2 = "test_result.zip"
        receivers = ["ADDR1", "ADDR2"]  # 收件人列表

        email_obj = get_email_obj(email_subject, mail_user, receivers)
        attach_content(email_obj, email_content)
        attach_part(email_obj, source_path1, part_name1)
        attach_part(email_obj, source_path2, part_name2)
        send_email(email_obj, mail_host, host_port,
                   mail_user, mail_pwd, receivers)

猜你喜欢

转载自blog.csdn.net/shijianzhihu/article/details/86291650
今日推荐