zoukankan      html  css  js  c++  java
  • python selenium-7自动发送邮件

    https://jingyan.baidu.com/article/647f0115b78f8d7f2148a8e8.html

    1.发送HTML格式的邮件

    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    
    #发送邮箱服务器
    smtpserver = "smtp.126.com"
    #发送邮箱用户/密码
    user = "发送邮箱@126.com"
    password = "登陆密码"
    #发送邮箱
    sender = "发送邮箱@126.com"
    #接收邮箱
    receiver = "接收邮箱@qq.com"
    #发送邮箱主题
    subject = "python发送邮件"
    #编写HTML类型的邮箱正文
    msg=MIMEText('<html><h1>给QQ邮箱发送邮件</h1></html>','html','utf-8')
    msg['Subject']=Header(subject,'utf-8')
    msg['From']="张三"
    msg['To']=receiver
    
    smtp = smtplib.SMTP()
    smtp.connect(smtpserver)
    smtp.login(user,password)
    try:
        smtp.sendmail(sender, receiver, msg.as_string())
        print("发送成功")
    except smtplib.SMTPDataError as e:
        print("发送失败")
    finally:
        smtp.quit()
    

    2.发送文本内容的邮件

    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    
    msg_from = '发送邮箱@qq.com'
    passwd = '授权码'
    msg_to = '收件人邮箱@126.com'
    
    subject = "python邮件测试"
    content = "这是我使用python smtplib及email模块发送的邮件"
    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['From'] = "发送方"
    msg['To'] = "接收方"
    try:
        s = smtplib.SMTP_SSL("smtp.qq.com", 465)
        s.login(msg_from, passwd)
        s.sendmail(msg_from, msg_to, msg.as_string())
        print("发送成功")
    except s.SMTPDataError as e:
        print("发送失败")
    finally:
        s.quit()
    

    其中 s = smtplib.SMTP_SSL("smtp.qq.com", 465)#相当于以下2行
    s = smtplib.SMTP()
    s.connect("smtp.qq.com")

    3.发送带附件的邮件

    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    smtpserver = "smtp.126.com"
    sender = "发送邮箱@126.com"
    receiver = "接收邮箱@qq.com"
    user = "发送邮箱@126.com"
    password = "发送邮箱密码"
    subject = "测试附件3"
    sendfile = open("/Users/chenshanju/PycharmProjects/SeleniumOfJenkins/report/log.txt","rb").read()
    
    att = MIMEText(sendfile,"base64","utf-8")
    att["Content-Type"] = "application/octet-stream"
    att["Content-Disposition"] ="attachment;filename='log.txt'"
    msgRoot = MIMEMultipart("related")
    msgRoot["Subject"] = subject
    msgRoot["From"] = sender
    msgRoot["To"] = receiver
    msgRoot.attach(att)
    
    smtp = smtplib.SMTP()
    smtp.connect(smtpserver)
    smtp.login(user,password)
    smtp.sendmail(sender,receiver,msgRoot.as_string())
    smtp.quit()
    

    4.查找最新的测试报告

    import sys,os
    #获取当前脚本的目录
    script_path=sys.path[0].split("/")
    #获取工程的主目录
    end_index=script_path.index("SeleniumOfJenkins")+1
    #report所在的目录
    report_dir="/".join(script_path[:end_index])+"/report"
    #查看当前的文件生成列表
    list_file=os.listdir(report_dir)
    #对文件按照创建时间进行排序
    list_file.sort(key=lambda file:os.path.getmtime(report_dir+"/"+file))
    print(list_file[-1])
    

    5.自动发送测试报告

    import unittest,os,sys
    from time import strftime
    from HTMLTestRunner import HTMLTestRunner
    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    
    def get_new_report(report_dir):
        "get_new_report()方法传入一个参数(测试报告所在目录),得到最新的report文件"
        file_list = os.listdir(report_dir)
        file_list.sort(key=lambda file:os.path.getmtime(report_dir+"/"+file))
        return report_dir+"/"+file_list[-1]
    def send_email(new_report):
        "send_email()接收一个参数(new_report),发送邮件"
        f = open(new_report,"rb")
        mail_body=f.read()
        f.close()
        sender = "发送邮箱@126.com"
        receiver = "接收邮箱@qq.com"
        msg = MIMEText(mail_body,"html","utf-8")
        msg['Subject'] = Header("自动化测试报告","utf-8")
        msg['From'] = sender
        msg['To'] = receiver
        smtp = smtplib.SMTP()
        smtp.connect("smtp.126.com")
        smtp.login("发送邮箱@126.com","发送邮箱密码")
        try:
            smtp.sendmail(sender,receiver,msg.as_string())
            print("发送成功")
        except :
            print("发送失败")
        finally:
            smtp.quit()
    
    if __name__=="__main__":
        """1.执行测试 2.获取最新报告 3.发送邮件"""
        current_dir_list = sys.path[0].split("/")
        index = current_dir_list.index("SeleniumOfJenkins") + 1
        if index == len(current_dir_list):
            home_dir = "/".join(current_dir_list)
        else:
            home_dir = "/".join(current_dir_list[:index])
        report_dir = home_dir + "/" + "report"
        test_dir = home_dir + "/testcase/testsearch"
        discover = unittest.defaultTestLoader.discover(test_dir, pattern="test*.py")
        filename="report/"+strftime("%Y_%m_%d_%H_%M_%S")+"_result.html"
        fp = open(filename,"wb")
        runner=HTMLTestRunner(stream=fp,title="百度搜索报告",description="用例执行情况")
        runner.run(discover)
        fp.close()
        new_report = get_new_report(report_dir)
        send_email(new_report)
    

    FAQ:

    1.qq邮箱需要开启imap和smtp权限

    ## 2.从126邮箱发送qq邮箱抛出异常smtplib.SMTPDataError smtplib.SMTPDataError: (554, b'DT:SPM 126 smtp1,C8mowABHGtEduABcQk94BA--.46414S2 1543551006,please see http://mail.163.com/help/help_spam_16.htm?ip=125.122.53.172&hostid=smtp1&time=1543551006') 解决方法:需要对msg['From']和msg['To']赋值 ## 3.发送的附件不是指定的文件名,而是tcmime.*.bin类型的文件 原因:att["Content-Disposition"] ="attachment;filename='log.txt'"误写为Content-Dispostion ## 4.自动发送测试报告中,qq邮箱样式丢失,126邮箱正常 使用附件可以解决这个问题 ```#python import smtplib,os,sys from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText

    def get_home_dir():
    "获取最新的报告"
    current_path_list=sys.path[0].split("/")
    index = current_path_list.index("SeleniumOfJenkins")+1
    if index == len(current_path_list):
    home_path=sys.path[0]
    else:
    home_path="/".join(current_path_list[:index])
    return home_path
    def get_new_file():
    "获取最新的报告"
    file_list=os.listdir(report_path)
    file_list.sort(key=lambda file:os.path.getmtime(report_path+file))
    return file_list[-1]

    def send_email():
    "发送邮件"

    new_file_name = get_new_file()
    new_file = report_path + new_file_name
    server = "smtp.126.com"
    sender="发送邮箱@126.com"
    receiver="接收邮箱@qq.com"
    subject = "测试报告见附件3"
    sendfile= open(new_file,"rb").read()
    att = MIMEText(sendfile,"base64","utf-8")
    att['Content-Type'] = "application/octet-stream"
    att['Content-Disposition'] = "attachment;filename='%s'" % new_file_name
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = subject
    msgRoot['From'] = sender
    msgRoot['To'] = receiver
    msgRoot.attach(att)
    smtp = smtplib.SMTP()
    try:
        smtp.connect(server)
        smtp.login("发送邮箱@126.com","发送邮箱密码")
        smtp.sendmail(sender,receiver,msgRoot.as_string())
        print("发送成功")
    except:
        print("发送失败")
    finally:
        smtp.quit()
    

    if name=="main":
    home_path = get_home_dir()
    report_path = home_path + "/report/"
    send_email()

  • 相关阅读:
    NetCore+AutoMapper多个对象映射到一个Dto对象
    log4net快速上手
    WebService基于soapheader的身份验证
    Canvas入门笔记-实现极简画笔
    .Net修改网站项目调试时的虚拟目录
    Roslyn导致发布网站时报错:编译失败
    .NET通过字典给类赋值
    键盘测试工具
    索引器基类定义
    自定义队列任务执行器
  • 原文地址:https://www.cnblogs.com/csj2018/p/10048041.html
Copyright © 2011-2022 走看看