Python自动化邮件添加HTML表格图像和Excel附件
2017-04-17 本文已影响112人
沈宥
本文源码请见:Github 源码
发送邮件的Python脚本网上有很多,就不做过多描述:
1、通过本地Excel获取原始数据:
wb = load_workbook(fileName,data_only=True)
ws = wb.get_sheet_by_name('Crash')
for rown in xrange(3,7):
for coln in xrange(2,8):
value = ws.cell(row=rown,column=coln).value
if coln == 2:
all_versions.append(value)
elif coln == 3:
personNums.append(int(value))
elif coln == 4:
hanppends.append(int(value))
elif coln == 5:
today_bugly.append(float(value))
elif coln == 6:
yes_bugly.append(float(value))
for x in xrange(0,4):
bugly_flu.append(crash_rate(today_bugly[x],yes_bugly[x]))
data_source.png
2、传入数据,形成HTML网页:
关于HTML的语法,可自行百度,这里给个简单的表格:
html = """\
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<title>iOS - Bugly崩溃日报</title>
</head>
<body>
<div id="container">
<div id="content">
<p>
版本崩溃信息:
<table width="800" border="2" bordercolor="black" cellspacing="2">
<tr>
<td><strong>版本号</strong></td>
<td><strong>影响人数</strong></td>
<td><strong>发生次数</strong></td>
<td><strong>日崩溃率-用户指标</strong></td>
<td><strong>波动</strong></td>
</tr>
<tr>
<td>""" + str(all_versions[0]) + """</td>
<td>""" + str(personNums[0]) + """</td>
<td>""" + str(hanppends[0]) + """</td>
<td>""" + daily_crash_bugly(today_bugly[0]) + """</td>
<td bgcolor="#FF8040">""" + str(bugly_flu[0]) + """</td>
</tr>
<tr>
<td>""" + str(all_versions[1]) + """</td>
<td>""" + str(personNums[1]) + """</td>
<td>""" + str(hanppends[1]) + """</td>
<td>""" + daily_crash_bugly(today_bugly[1]) + """</td>
<td bgcolor="#FF8040">""" + str(bugly_flu[1]) + """</td>
</tr>
<tr>
<td>""" + str(all_versions[2]) + """</td>
<td>""" + str(personNums[2]) + """</td>
<td>""" + str(hanppends[2]) + """</td>
<td>""" + daily_crash_bugly(today_bugly[2]) + """</td>
<td bgcolor="#FF8040">""" + str(bugly_flu[2]) + """</td>
</tr>
<tr>
<td>""" + str(all_versions[3]) + """</td>
<td>""" + str(personNums[3]) + """</td>
<td>""" + str(hanppends[3]) + """</td>
<td>""" + daily_crash_bugly(today_bugly[3]) + """</td>
<td bgcolor="#FF8040">""" + str(bugly_flu[3]) + """</td>
</tr>
</table>
</p>
<p>
详情请见附件
</p>
</div>
</div>
</body>
</html>
"""
3、添加Excel附件:
part = MIMEApplication(open(fileName,'rb').read())
part.add_header('Content-Disposition', 'attachment', filename=fileName)
message.attach(part)
4、发送邮件:
def send_mail_to_test(context):
send_mail({
'to': ["wangpingyang03@mail.cn"],
'cc': ['wangpingyang03@mail.cn'],
'server': 'smtp.exmail.qq.com',
'port': 25,
'subject': 'Just for Test',
'username': 'pingyang.wang@mail.cn',
'password': 'xxxxxx',
'text': context}
)
发送邮件成功结果:
result.png