zoukankan      html  css  js  c++  java
  • 实现自动发邮件功能

    在实际的项目中,当脚本执行完毕,生成测试报告,我们需要把报告通过邮件发送到对应的测试人员和开发人员,下面学习下在Python中如何实现邮件发送功能,在Python中提供了smtplib模块来发送邮件,导入smtplib,通过help函数可以查看smtp提供的方法。

    在学习发邮件的过程中,只需要掌握两个模块的用法即可,smtplib和email,smtplib模块负责发送邮件(连接邮箱服务器,登录邮箱,发送邮件),email负责构造邮件(发件人,收件人,主题,正文,附件等)。

    smtplib模块:

     1 connect(host,port):
     2 host:指定连接的邮箱服务器
     3 port:指定连接服务器的端口号,默认为25
     4 login(user,password):
     5 usr:指定邮箱用户名
     6 password:指定邮箱登录密码
     7 sendmail(from_addr, to_addrs, msg):
     8 from_addr:指定邮件发送者地址
     9 to_addrs:指定邮箱接受者地址
    10 msg:发送消息:邮件内容,一般是msg.as_string()将msg(MIMEText对象或者MIMEMultipart对象)变为str。
    11 quit():
    用来结束SMTP回话。

    email模块:

    email模块下有mime包,该包下常用的三个模块是:text,image,multipart。

    构造一个MIMEText对象,就表示一个文本邮件对象,构造一个MIMEImage对象,就表示一个作为附件的图片,如果要把多个对象组合到一起,则需要使用MIMEMultipart对象。

    发送普通的文本:text_plain=MIMEText(text,"plain","utf-8")

    发送HTML格式的文本:text_html=MIMEText(text,"html","utf-8")

    在进行发送邮件时,我们需要把subject,from,to等添加到MIMEText或者MIMEMultipart对象中,因为只有这样,邮件才会显示主题,发件人,收件人等。

        msg = MIMEMultipart()
        msg["subject"] = "这是发送邮件的主题"
        msg["from"] = sender
        msg["to"] = recever

    说明:如果只有一个html网页或者plain普通文本的话,msg可以是MIMEText,但是如果是多个的话(附件,文本,图片等),则msg类型要为MIMEMultipart。

    1.发送HTML格式的邮件

    # -*-coding:utf-8 -*-
    import smtplib
    from email.mime.text import MIMEText
    
    # ------1、设置发送邮件相关的参数------
    smtpserver ="smtp.126.com"  # 发送邮件服务器
    sender ="xxxxxx"  # 发送邮件的账号
    pwd = "xxxxxx"  # 发送邮件账号的密码
    receiver = "xxxxxx"  # 接收邮件的账号
    # ------2、编辑邮件的内容-----
    subject = "发送邮件的主题"  # 发送邮件的主题
    body = "这是发送的邮件的内容"  # 发送邮件的内容,邮件的正文为html格式
    msg = MIMEText(body, "html", "utf-8")  # 发送纯文本格式的邮件
    msg["Subject"] = subject
    msg['from'] = "xxxxxx"
    msg['to'] = "xxxxxx"
    # ------3、发送邮件------
    smtp = smtplib.SMTP()
    smtp.connect(smtpserver)  # 连接邮件服务器
    smtp.login(sender, pwd)  # 登录邮件服务器
    
    smtp.sendmail(sender, receiver, msg.as_string())  # 发送邮件
    smtp.quit()  # 关闭连接

    2.发送带附件的邮件

    上面的MIMEText只能发送正文格式的邮件,无法发送附件,如果想要发送带附件的邮件,需要另外一个类MIMEMultipart。

    # -*-coding:utf-8 -*-
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    
    # ------1、设置发送邮件相关的参数------
    smtpserver ="smtp.126.com"  # 发送邮件服务器
    sender ="xxxxxx"  # 发送邮件的账号
    pwd = "xxxxxx"  # 发送邮件账号的密码
    receiver = "xxxxxx"  # 接收邮件的账号
    # ------2、编辑邮件的内容-----
    # 读文件
    file_path = "./testpro/testresult/2019-03-10 09-35-54result.html"
    with open(file_path, "rb") as fp:
        mail_body = fp.read()
    
    msg = MIMEMultipart()
    msg['from'] = sender
    msg['to'] = receiver
    msg["subject"] = "这是发送邮件的主题"
    
    # 正文
    body = MIMEText(mail_body, "html", "utf-8")
    msg.attach(body)
    # 附件
    attach = MIMEText(mail_body, "base64", "utf-8")
    attach["Content-Type"] = "application/octet-stream"
    attach["Content-Disposition"] = 'attachment; filename="testReport.html"'
    msg.attach(attach)
    # ------3、发送邮件------
    smtp = smtplib.SMTP()
    smtp.connect(smtpserver)  # 连接邮件服务器
    smtp.login(sender, pwd)  # 登录邮件服务器
    
    smtp.sendmail(sender, receiver, msg.as_string())  # 发送邮件
    smtp.quit()  # 关闭连接

     3.邮件发送最新的测试报告

    # -*-coding:utf-8 -*-
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    import os
    from email.header import Header
    
    # ------1、设置发送邮件相关的参数------
    smtpserver ="smtp.126.com"  # 发送邮件服务器
    sender ="xxxxxx"  # 发送邮件的账号
    pwd = "xxxxxx"  # 发送邮件账号的密码
    receiver = "xxxxxx"  # 接收邮件的账号
    # ------2、编辑邮件的内容-----
    result_dir = "./testpro/testresult/"
    file_list = os.listdir(result_dir)
    file_list.sort(key=lambda fn: os.path.getmtime(result_dir + "/" + fn))
    file = os.path.join(result_dir+file_list[-1])
    # 读文件
    with open(file, "rb") as fp:
        mail_body = fp.read()
    
    msg = MIMEMultipart()
    msg["subject"] = "这是发送邮件的主题"
    msg["from"] = sender
    msg["to"] =  receiver
    
    # 正文
    body = MIMEText(mail_body, "html", "utf-8")
    msg.attach(body)
    # 附件
    attach = MIMEText(mail_body, "base64", "utf-8")
    attach["Content-Type"] = "application/octet-stream"
    attach["Content-Disposition"] = 'attachment; filename="testReport.html"'
    msg.attach(attach)
    # ------3、发送邮件------
    smtp = smtplib.SMTP()
    smtp.connect(smtpserver)  # 连接邮件服务器
    smtp.login(sender, pwd)  # 登录邮件服务器
    
    smtp.sendmail(sender, receiver, msg.as_string())  # 发送邮件
    smtp.quit()  # 关闭连接

     4.整合自动发送邮件功能

    下面根据上节的测试百度搜索和搜狗搜索的案例整合自动发送邮件功能。

    # coding:utf-8
    import unittest
    from HTMLTestRunner import HTMLTestRunner
    import time
    from smtplib import SMTP
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart
    import os
    
    def send_mail(report):
        # 设置发送邮件需要的参数
        smtp_server = "smtp.126.com"
        sender = "xxxxxx"
        pwd = "xxxxxx"
        recever = "xxxxxx"
        # 设置发送邮件的内容
        # 读文件
        with open(report, "rb") as fp:
            mail_body = fp.read()
    
        msg = MIMEMultipart()
        msg["subject"] = "这是发送邮件的主题"
        msg["from"] = sender
        msg["to"] = recever
        # 内容
        body = MIMEText(mail_body,"html","utf-8")
        msg.attach(body)
        # 附件
        attach = MIMEText(mail_body, "base64", "utf-8")
        attach["Content-Type"] = "application/octet-stream"
        attach["Content-Disposition"] = 'attachment; filename="testReport.html"'
        msg.attach(attach)
        # 发送邮件
        smtp = SMTP()
        smtp.connect(smtp_server)
        smtp.login(sender, pwd)
        smtp.sendmail(sender, recever, msg.as_string())
        smtp.quit()
    
    
    def find_report(file_path):
        list_file = os.listdir(file_path)  # 列出该目录下的所有文件
        list_file.sort(key=lambda fn: os.path.getmtime(file_path + "/" + fn))
        report = os.path.join(file_path + list_file[-1])
        return report
    
    
    if __name__ == '__main__':
        discover = unittest.defaultTestLoader.discover("./testpro/testcase/", "test*.py")
        now_time = time.strftime("%Y-%m-%d %H-%M-%S")
        file_name = "./testpro/testresult/"+now_time+"result.html"
        file = open(file_name, "wb")
        runner = HTMLTestRunner(stream=file, title="测试报告", description="测试用例执行情况")
        runner.run(discover)
        file.close()
        new_report = find_report("./testpro/testresult/")
        send_mail(new_report)
        print("The end!")
  • 相关阅读:
    jfreechart简单介绍---曲线图
    Java监听器
    在java里actionPerformed是做什么用的
    sqlserver,oracle,mysql等的driver驱动,url怎么写
    ibatis入门实例(完整)
    java连接access数据库的三种方式以及远程连接
    elementui入门以及nodeJS环境搭建
    vue路由
    vue模板语法下
    vue模板语法上
  • 原文地址:https://www.cnblogs.com/zhuzhaoli/p/10510223.html
Copyright © 2011-2022 走看看