使用email.mim时,无法在电子邮件正文中看到Pandas数据框

2024-06-02 06:46:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在熊猫中有以下数据帧(my\ u 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()

请帮忙


Tags: 数据代码dfserver电子邮件myhtmlcc
1条回答
网友
1楼 · 发布于 2024-06-02 06:46:31

您可以直接将dataframe 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()

相关问题 更多 >