python3发送测试报告截图(正文中显示截图)和html附件

#! /usr/bin/env python3
'''
i'm  pot

'''

# import pysnooper
import smtplib
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
import os,sys
import time
import glob
from PIL import Image
from selenium import webdriver
from email.mime.image import MIMEImage 
# sys.path.append('..')
from Configer.config import GetConfig,log





Conf =GetConfig()
nowpath = os.path.dirname(os.path.realpath(__file__))
mailfile_path = os.path.abspath(os.path.join(nowpath, '..') +'/Report/report.html')
mailshot_path = os.path.abspath(os.path.join(nowpath, '..') +'/Report/report.png')

if not os.path.exists(mailfile_path):
    log.info('没有找到生成的report 文件')
    raise FileNotFoundError('没有找到生成的report 文件')

class SendMail(object):
    def __init__(self,file=None, ssl=True, email_host='smtp.qq.com', port=25, ssl_port=465):
        '''
        :param username: 用户名
        :param passwd: 密码
        :param recv: 收件人,多个要传list ['a@qq.com','b@qq.com]
        :param title: 邮件标题
        :param content: 邮件正文
        :param file: 附件路径,如果不在当前目录下,要写绝对路径,默认没有附件
        :param ssl: 是否安全链接,默认为普通
        :param email_host: smtp服务器地址
        :param port: 非安全链接端口,默认为25
        :param ssl_port: 安全链接端口,默认为465
        '''
        self.username = Conf.get_param('email', 'mail_user')  # 用户名
        self.passwd = Conf.get_param('email', 'mail_pwd')  # 密码
        self.recv = Conf.get_param('email', 'touser')  # 收件人,多个要传list ['a@qq.com','b@qq.com]
        # self.title = 'title'  # 邮件标题
        # self.content = 'content'  # 邮件正文
        self.file = mailfile_path  # 附件路径,如果不在当前目录下,要写绝对路径
        self.email_host = Conf.get_param('email', 'mail_host')  # smtp服务器地址
        self.port = 25  # 普通端口
        self.ssl = ssl  # 是否安全链接
        self.ssl_port = Conf.get_param('email', 'mail_port')  # 安全链接端口



    def shot(self):
        # open in webpage
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument('--headless')
        chrome_options.add_argument('--disable-gpu')
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument('--disable-dev-shm-usage')
        driver = webdriver.Chrome('/usr/local/bin/chromedriver',chrome_options=chrome_options)
        #上面的driver是linux服务器上的地址
  		#下面的driver是windows本地的地址
        # driver = webdriver.Chrome('D:\\Python37\\chromedriver.exe',chrome_options=chrome_options)

		#打开HTML,需要url地址,或者file://格式,我这里用的是本地的html文件,所以用file://格式
		
        new_path = 'file://'+mailfile_path
        
        driver.get(new_path)
        driver.save_screenshot(mailshot_path)
        driver.quit()




    # @pysnooper.snoop()
    def send_mail(self):
        msg = MIMEMultipart('related')
        # 发送内容的对象
        if self.file:  # 处理附件的
            file_name = os.path.split(self.file)[-1]  # 只取文件名,不取路径
            try:
                f = open(self.file, 'rb').read()
            except Exception as e:
                raise Exception('附件打不开!!!!')
            else:
                att = MIMEText(f, "base64", "utf-8")
                att["Content-Type"] = 'application/octet-stream'
                # base64.b64encode(file_name.encode()).decode()
                new_file_name = '=?utf-8?b?' + base64.b64encode(file_name.encode()).decode() + '?='
                # 这里是处理文件名为中文名的,必须这么写
                att["Content-Disposition"] = 'attachment; filename="%s"' % (new_file_name)
                msg.attach(att)
        
        
        # msg.attach(MIMEText('Hi,all\n本次接口自动化测试报告见附件:'))  # 邮件正文的内容


               
        content1 = 'Hi,all'
        content2 = '本次接口自动化详情见附件,截图如下:'

        html = """ 
        <html>  
            <head></head>  
            <body>  
                <p> 
                    %s
                <br>%s</br>     
                <br><img src="cid:image1"></br> 
                </p> 
            </body>  
        </html>  
        """ % (content1,content2)
        htm = MIMEText(html, 'html', 'utf-8')
        
        msg.attach(htm)

        file = open(mailshot_path, "rb")
        img_data = file.read()
        file.close()
        img = MIMEImage(img_data)
        img.add_header('Content-ID', 'image1') # todo: 注意这里的 dns_config 是和 html中对应的
        msg.attach(img) 






        tm = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        msg['Subject'] = Header("接口自动化测试报告"+"_"+tm, 'utf-8')  # 邮件主题
        msg['From'] = self.username  # 发送者账号
        self.touser= self.recv.split(',')
        # msg['To'] = ','.join(self.touser)  # 接收者账号列表
        msg['To'] = self.recv  # 接收者账号列表

        if self.ssl:
            self.smtp = smtplib.SMTP_SSL(self.email_host, port=self.ssl_port)
        else:
            self.smtp = smtplib.SMTP(self.email_host, port=self.port)
        # 发送邮件服务器的对象
        self.smtp.login(self.username, self.passwd)
        try:
            self.smtp.sendmail(self.username, self.touser, msg.as_string())
            pass
        except Exception as e:
            log.info('邮件发送失败', e)
        else:
            log.info('邮件发送成功!')
        self.smtp.quit()


sendmail=SendMail()

if __name__ == '__main__':
    m = SendMail()
    m.shot()
    m.send_mail()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值