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

Solution 1:

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

Solution 2:

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.