自动化发送邮件smtp以附件形式发送邮件用法

2021-05-23  本文已影响0人  心本逍遥

smtp发送邮件用法

1发送邮件def:

python登录qq账号, 属于第三方登录, 密码需写SMTP服务 验证码,不输入真实qq密码

2.最新报告def:

3.运行:

4.具体代码:

# coding:utf-8

import unittest

import os

import HTMLTestRunner

import time

import smtplib

from email.mime.multipartimport MIMEMultipart

from email.mime.textimport MIMEText

from email.headerimport  Header

import datetime

now = time.strftime("%Y-%m-%d %H_%M_%S")

# 用例路径

case_path = os.path.join(os.getcwd(), "testcase")

#报告存放文件夹路径

test_report ="D:\\pythonproject\\Autotest\\report"

# 报告存放路径

report_path = os.path.join(os.getcwd(), "D:\\pythonproject\\Autotest\\report\\"+now+"report.html")

##用例集

def all_case():

discover = unittest.defaultTestLoader.discover(case_path,

                                                    pattern="test*.py",

                                                    top_level_dir=None)

print(discover)

return discover

##发送邮件

def send_mail(file_new):

f=open(file_new,'rb')

mail_body =f.read()

f.close()

msg = MIMEMultipart()

#msg = MIMEText(mail_body,_subtype='html',_charset='utf8')

    msg['From'] ='1020474486@qq.com'

    msg['To'] ='1459581689@qq.com'

    msg['subject'] = Header('测试结果(' +str(datetime.date.today()) +')','utf-8')

att = MIMEText(open(report_path, 'rb').read(), 'base64', 'gb2312')

att["Content-Type"] ='application/octet-stream'

    att["Content-Disposition"] ='attachment; filename="testTemplate.html"'

    msg.attach(att)

body ="Python test mail"

    msg.attach(MIMEText(body, 'plain'))

smtp= smtplib.SMTP()

smtp.connect('smtp.qq.com')

smtp.login('1020474486','XXXXXXXXXXX')

smtp.sendmail('1020474486@qq.com','1459581689@qq.com',msg.as_string())

smtp.quit()

print('email has send out!')

#####查找测试报告目录, 找到最新生成的测试报告文件+======

def new_report(testreport):

lists = os.listdir(testreport)

lists.sort(key=lambda  fn:os.path.getmtime(testreport+"\\"+fn))

print(('最新文件为:'+ lists[-1]))

file = os.path.join(testreport,lists[-1])

print(file)

return (file)

if __name__ =='__main__':

##生成报告

    fp =open(report_path,"wb")

runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='这是我的自动化测试报告', description='用例执行情况:')

##执行所有用例

    runner.run(all_case())

fp.close()

new_report =new_report(test_report)

print("hehe"+ new_report)

send_mail(new_report)

上一篇 下一篇

猜你喜欢

热点阅读