How can I embed a pandas dataframe into a SparkPost email with HTML formatting?

115 Views Asked by At

I would like to send automated emails through SparkPost that include a pandas dataframe in the body of the email. The code below shows what I've been working through thus far. The main issue is the html section of the transmissions block. I cannot get the email to send if I have the html section formatted as is, but if I remove all the current text in the html variable and set html = table I can get the email to run, but there is no html formatting included.

My question is how I can I embed the dataframe into the html?

from sparkpost import SparkPost
from sparkpost.exceptions import SparkPostAPIException
import pandas as pd
from tabulate import tabulate

d = {'col1': [1, 2], 'col2': [3, 4]}

df = pd.DataFrame(data=d)

table = tabulate(df, headers=list(df.columns.values), tablefmt="html")

sp = SparkPost('API Key here')

try:
    response = sp.transmissions.send(
        recipients=['[email protected]'],
        html="""
          <html>
          <head>
          <style> 
            table, th, td {{ border: 1px solid black; border-collapse: collapse; }}
            th, td {{ padding: 5px; }}
          </style>
          </head>
          <body>
          <p>Hello, <br><br>Please find the data below.</p>
          <p>Here is your data:</p>
          {table}
          <p>Thanks,</p>
          <p>Signature</p>
          </body>
          </html>
        """,
        from_email='[email protected]',
        subject='SparkPost Test Email'
    )
except SparkPostAPIException as err:
    # http response status code
    print(err.status)
    # python requests library response object
    # http://docs.python-requests.org/en/master/api/#requests.Response
    print(err.response.json())
    # list of formatted errors
    print(err.errors)
1

There are 1 best solutions below

0
Yepher On

This worked for me

response = sp.transmissions.send(
      
        recipients=['[email protected]'],
        html="""
          <html>
          <head>
          </head>
          <body>
          <p>Hello, <br><br>Please find the data below.</p>
          <p>Here is your data:</p>""" +
          table +
          """<p>Thanks,</p>
          <p>Signature</p>
          </body>
          </html>
        """,
        from_email='[email protected]',
        subject='SparkPost Test Email'
    )