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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50564407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:36:51  来源:igfitidea点击:

Pandas send email containing dataframe as a visual table

python-3.xpandasemail

提问by Nick Dragosh

Take this example:

拿这个例子:

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)

How can I send an email, via gmail, with this dataframe to look like a table?

如何通过 gmail 发送带有此数据框的电子邮件,使其看起来像一张表格?

enter image description here

在此处输入图片说明

This is what I tried:

这是我尝试过的:

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()

回答by Rakesh

Try:

尝试:

  • Using str.formatto append your DF html to the email body html.
  • 使用str.format附加的DF HTML电子邮件主体的HTML。

Ex:

前任:

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 = ['[email protected]'] 
emaillist = [elem.strip().split(',') for elem in recipients]
msg = MIMEMultipart()
msg['Subject'] = "Your Subject"
msg['From'] = '[email protected]'


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())