python 发送带附件邮件到钉钉邮箱+邮件内容带有表格

import smtplib

import pandas as pd

# smtplib这个模块是管发邮件

from email.mime.text import MIMEText

# 构造邮件内容

from email.mime.multipart import MIMEMultipart

import re

 

import os

from bs4 import BeautifulSoup as bs

#获取测试报告中的结果

def get_result(files):

listRes = []

for i in range(len(files)):

htmls = open(files[i],'r',encoding="utf-8")

htmlcontent = htmls.read()

htmlcontent1 = bs(htmlcontent,'html.parser')

ts = htmlcontent1.table

strs = str(ts)

h = re.findall(r'(.*?)

h1 = h[2]

 

h11 = h1.replace('(','').replace(')','').replace('/',' ').split(' ')

listRes.append(h11)

return listRes

#邮件内容中写入表格

def get_table(files):

content = get_result(files)

# 构建了一个能发附件的邮件对象

newdata = {'total': {'运营': content[0][0], 'M站': content[1][0], 'APP': content[2][0]},

'success': {'运营': content[0][1], 'M站': content[1][1], 'APP': content[2][1]},

'fail': {'运营': content[0][2], 'M站': content[1][2], 'APP': content[2][2]},

'error': {'运营': content[0][3], 'M站': content[1][3], 'APP': content[2][3]},

'skip': {'运营': content[0][4], 'M站': content[1][4], 'APP': content[2][4]}}

a = pd.DataFrame(newdata)

sub = "test"

d = '' # 表格内容

for i in range(len(a)):

d = d + """

       

          """ + str(a.index[i]) + """

          """ + str(a.iloc[i][0]) + """

          """ + str(a.iloc[i][1]) + """

          """ + str(a.iloc[i][2]) + """

          """ + str(a.iloc[i][3]) + """

""" + str(a.iloc[i][4]) + """

        """

html = """\

 

 

各位老师好,这是今日的测试报告,请各位注意查收 !如需了解详情,可自行下载附件 。注:此邮件为自动发送,请勿回复!:

 

 

 

 

 

 

""" + d + """

平台/结果 TOTAL SUCCESS FAIL ERROR SKIP

      """

 

context = MIMEText(html, _subtype='html', _charset='utf-8') # 解决乱码

return context

#给不同平台的测试报告重命名

def rename(report_dir,email_user,maillist):

datrTime = time.strftime('%Y-%m-%d %H:%M:%S')

subject = datrTime+' 接口测试报告'

message = MIMEMultipart()

message['Subject'] = Header(subject, 'utf-8') # 邮件主题

message['From'] = email_user # 发送者账号

message['To'] = (',').join(maillist) # 接收者账号列表

lists = os.listdir(report_dir)

lists.sort(key=lambda fn: os.path.getmtime(report_dir + '/' + fn))

filepath1 = os.path.join(report_dir, lists[-1])

filepath2 = os.path.join(report_dir, lists[-2])

filepath3 = os.path.join(report_dir, lists[-3])

files = [filepath1, filepath2, filepath3]

'''发送html文件'''

if filepath1 in files:

htmlApart1 = MIMEText(open(filepath1, 'rb').read(), 'base64', 'utf-8')

htmlApart1.add_header('Content-Disposition', 'attachment', filename=("gbk", "", "运营测试报告.html"))

message.attach(htmlApart1) # 发送邮件文本

if filepath2 in files:

htmlApart2 = MIMEText(open(filepath2, 'rb').read(), 'base64', 'utf-8')

htmlApart2.add_header('Content-Disposition', 'attachment', filename=("gbk", "", "M站测试报告.html"))

message.attach(htmlApart2) # 发送邮件文本

if filepath3 in files:

htmlApart3 = MIMEText(open(filepath3, 'rb').read(), 'base64', 'utf-8')

htmlApart3.add_header('Content-Disposition', 'attachment', filename=("gbk", "", "APP测试报告.html"))

message.attach(htmlApart3) # 发送邮件文本

context = get_table(files)

message.attach(context)

return message

# 发带附件的邮件用的

def send_email():

email_host = 'smtp.163.com' # 邮箱服务器地址

email_user = '**********@163.com' # 发送者账号

email_pwd = '*********'#邮箱的授权码

# 发送者密码是邮箱的授权码,不是登录的密码

maillist = ['***********@dingtalk.com','*******[email protected]','******@dingtalk.com']

 

report_dir = './reports'

message = rename(report_dir,email_user,maillist)

# 构建了一个能发附件的邮件对象

smtp = smtplib.SMTP(email_host, port=25) # 连接邮箱,传入邮箱地址,和端口号,smtp的端口号是25

smtp.login(email_user, email_pwd) # 发送者的邮箱账号,密码

# smtp.set_debuglevel(1)

smtp.sendmail(email_user, maillist, message.as_string())

# 参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串

smtp.quit() # 发送完毕后退出smtp

print('email send success.')

send_email()

 

你可能感兴趣的:(软件测试)