Pandas将包含数据框的电子邮件作为可视表发送

时间:2018-05-28 10:35:04

标签: python-3.x pandas email

举个例子:

df_1 = ([1,2,3,5])
df_2 = ([10,20,30,50])
df_test =pd.concat([pd.DataFrame(df_1),pd.DataFrame(df_2)],axis=1)

如何通过gmail通过此数据框发送电子邮件看起来像桌子?

enter image description here

这就是我的尝试:

import smtplib

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr , ".......")

msg = df_test.to_html()
server.sendmail(fromaddr, toaddr, msg)
server.quit()

2 个答案:

答案 0 :(得分:3)

尝试:

  • 使用str.format将您的DF html附加到电子邮件正文html。

<强>实施例

from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from smtplib import SMTP
import smtplib
import sys


recipients = ['ToEmail@domain.com'] 
emaillist = [elem.strip().split(',') for elem in recipients]
msg = MIMEMultipart()
msg['Subject'] = "Your Subject"
msg['From'] = 'from@domain.com'


html = """\
<html>
  <head></head>
  <body>
    {0}
  </body>
</html>
""".format(df_test.to_html())

part1 = MIMEText(html, 'html')
msg.attach(part1)

server = smtplib.SMTP('smtp.gmail.com', 587)
server.sendmail(msg['From'], emaillist , msg.as_string())

答案 1 :(得分:0)

安装pretty-html-table

from pretty_html_table import build_table

body = """
<html>
<head>
</head>

<body>
        {0}
</body>

</html>
""".format(build_table(df, 'blue_light'))

您不必担心格式问题,而且如果您的 DataFrame 中有网站链接,那么输出将仅包含超链接。