我在pandas中有以下数据框(my_df):
Date Value1 Value2 Value3
01/05/2018 407 8 304
02/05/2018 879 3 82
03/05/2018 998 407 435
04/05/2018 399 479 349
05/05/2018 394 299 705
06/05/2018 840 524 710
我使用以下代码将数据帧转换为html格式:
my_df.to_html('df1.html')
当尝试在我的电子邮件中使用它作为正文时,它会发送包含所有文本的电子邮件,但不会发送数据帧。知道我可能做错了吗?
我使用以下代码发送电子邮件:
strFrom = 'xyz'
strTo = ['xyz']
cc = ['abc']
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test'
msgRoot['From'] = strFrom
msgRoot['To'] = ",".join(strTo)
msgRoot['Cc'] = ",".join(cc)
msgRoot.preamble = 'This is a multi-part message in MIME format.'
text1 = "\nABC:\n\nTable 1(xyz)"
part1 = MIMEText(text1, 'plain')
part2 = MIMEText('df1.html', 'html')
msgRoot.attach(part1)
msgRoot.attach(part2)
server = smtplib.SMTP(email_host)
server.set_debuglevel(1)
server.sendmail(strFrom, strTo, msgRoot.as_string())
server.quit()
请帮忙。
答案 0 :(得分:1)
您可以直接将数据框html呈现给电子邮件正文。
<强>实施例强>
strFrom = 'xyz'
strTo = ['xyz']
cc = ['abc']
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test'
msgRoot['From'] = strFrom
msgRoot['To'] = ",".join(strTo)
msgRoot['Cc'] = ",".join(cc)
msgRoot.preamble = 'This is a multi-part message in MIME format.'
text1 = """<html>
<head></head>
<body>
<h4>ABC: Table 1(xyz)</h4>
{0}
</body>
</html>
""".format(df_test.to_html())
part1 = MIMEText(text1, 'html')
msgRoot.attach(part1)
server = smtplib.SMTP(email_host)
server.set_debuglevel(1)
server.sendmail(strFrom, strTo, msgRoot.as_string())
server.quit()