loading...
Cover image for Convert a Dataframe into a pretty HTML table and send it over Email

Convert a Dataframe into a pretty HTML table and send it over Email

siddheshshankar profile image Siddhesh Shankar ・2 min read

Alt Text
My first post in dev.to.
I have learnt how to automate the creation of nice html tables using pretty-html-table package. This package is embedding very nicely with other packages used to send emails.
In this post I am going to cover:

  1. Sending Email using SMTP
  2. Convert pandas dataframe to pretty HTML table
  3. Sending the email with HTML content

Setup SMTP to send Email

Python comes with the built-in smtplib module for sending emails using the Simple Mail Transfer Protocol (SMTP). I have used Gmail SMTP server to send emails, but the same principles apply to other email services. Google’s Gmail SMTP server is a free SMTP service which anyone who has a Gmail account can use to send emails.

  • Gmail SMTP server address: smtp.gmail.com
  • Gmail SMTP username: Your Gmail address
  • Gmail SMTP password: Your Gmail password (Unique 12 letter password). Click here to set your password
  • Gmail SMTP port (TLS): 587
from smtplib import SMTP
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


def send_mail(body):

    message = MIMEMultipart()
    message['Subject'] = 'Top 5 Economies of the World!'
    message['From'] = '<sender>@gmail.com'
    message['To'] = '<receiver>@gmail.com'

    body_content = body
    message.attach(MIMEText(body_content, "html"))
    msg_body = message.as_string()

    server = SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(message['From'], 'Unique password')
    server.sendmail(message['From'], message['To'], msg_body)
    server.quit()

Create a Dataframe

import pandas as pd


def get_gdp_data():
    """
    GDP data
    :return:
    """
    gdp_dict = {'Country': ['United States', 'China', 'Japan', 'Germany', 'India'],
                'GDP': ['$21.44 trillion', '$14.14 trillion', '$5.15 trillion', '$3.86 trillion', '$2.94 trillion']}
    data = pd.DataFrame(gdp_dict)
    return data

Convert pandas dataframe to HTML table

Pretty HTML table package integrates very well with other python packages used to send emails. Just add the result of this package to the body of the email.

from send_email import send_mail
from get_data import get_gdp_data
from pretty_html_table import build_table


def send_country_list():
    gdp_data = get_gdp_data()
    output = build_table(gdp_data, 'blue_light')
    send_mail(output)
    return "Mail sent successfully."


send_country_list()

Done!
Octocat will take you to my GitHub repository...
Alt Text

Posted on by:

siddheshshankar profile

Siddhesh Shankar

@siddheshshankar

Analyst at BlackRock who loves working with R and Python💻

Discussion

pic
Editor guide