2020年自己为了美化邮件格式写的脚本,有需要的可以取用,直接上脚本:
一、要发送的原始文件格式
cat /tmp/dzg-test
a1|b1|c1
a2|b2|c2
a3|b3|c3
二、Python脚本
#!/bin/python3
# -*- coding:utf-8 -*-
import smtplib,csv,numpy
import pandas as pd
from email.mime.text import MIMEText
from email.header import Header
from datetime import datetime, date, timedelta
yesterday= (date.today() + timedelta(days = -1)).strftime("%Y-%m-%d") # 昨天日期
file = r"/tmp/dzg-test" #可以更改为每天生成的日志
#file = r"/tmp/file"+str(yesterday)+".log"
###这里对应多列
a = numpy.loadtxt(file , delimiter = "|" , usecols=(0), dtype=str)
b = numpy.loadtxt(file , delimiter = "|" , usecols=(1), dtype=str)
c = numpy.loadtxt(file , delimiter = "|" , usecols=(2), dtype=str)
################################################################
def convertToHtml(result,title):
#将数据转换为html的table
#result是list[list1,list2]这样的结构
#title是list结构;和result一一对应。titleList[0]对应resultList[0]这样的一条数据对应html表格中的一列
d = {}
index = 0
for t in title:
d[t]=result[index]
index = index+1
pd.set_option('max_colwidth',200)
#df = pd.DataFrame(d)
df = pd.DataFrame.from_dict(d,orient='index').T
df = df[title]
h = df.to_html(index=False)
return h
result = [a,b,c]
#print(result)
title = ['A','B','C'] ###对应多个标头
df_html=(convertToHtml(result,title))
head = \
"""
"""
body = \
"""
{df_html}
""".format(df_html=df_html)
html_msg = "" + head + body + ""
html_msg = html_msg.replace('\n','').encode("utf-8")
################################################################
SUBJECT = "测试邮件:"+yesterday ###邮件标题
HOST = "smtp.exmail.qq.com" ###代理邮箱Server地址,我用的是企业微信邮箱
FROM = "xxxcc@ss.com" ###代理邮箱
TO = ['2424160528@qq.com'] ###收件人
#TO = ['xxxx@qq.com','cccc@qq.com'] ###可以指定多个收件人
text = MIMEText(html_msg, 'html', 'utf-8')
text['From'] = Header(FROM,'utf-8')
text['TO'] = Header(str(TO), 'utf-8')
text['Subject'] = Header(SUBJECT, 'utf-8')
server = smtplib.SMTP()
server.connect(HOST,"25")
server.login(FROM,"passwordkkk") ###账户密码
server.sendmail(FROM, TO, text.as_string())
server.quit()
效果如下:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)