Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 820
Nick Dragosh Avatar asked May 28 '18 10:05

Nick Dragosh


People also ask

How do you send a Dataframe to a csv file?

Exporting the DataFrame into a CSV filePandas DataFrame to_csv() function exports the DataFrame to CSV format. If a file argument is provided, the output will be the CSV file. Otherwise, the return value is a CSV format like string. sep: Specify a custom delimiter for the CSV output, the default is a comma.


2 Answers

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())
like image 58
Rakesh Avatar answered Sep 20 '22 22:09

Rakesh


Install pretty-html-table

from pretty_html_table import build_table

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

<body>
        {0}
</body>

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

You need not have to worry about the formatting and also if there are website links in your DataFrame then the output will be with hyperlinks only.

like image 40
Nisrin Dhoondia Avatar answered Sep 19 '22 22:09

Nisrin Dhoondia