Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

python 3.x - Pandas send email containing dataframe as a visual table

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?

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try:

  • Using str.format to append your DF html to the email body 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())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...