Search code examples
pythonpython-3.xpandasjinja2html-email

HTML renders fine in browser but not in email (HTML is generated using pandas dataframe)


I am trying to send automated emails (containing tabled) in python using pandas dataframes. When I generate an HTML for the table and open it with browser, everything works great. When I try to render the same html in the email, some data is missing.

HTML rendered in browser HTML rendered in browser

HTML rendered in Email HTML rendered in Email

This is the code I'm using to create the HTML -

def csvToJinjaHTML(csvContent):

    print("Pandas: Set the max_colwidth to -1 for unlimited string length")
    pd.set_option("display.max_colwidth",-1)

    print("Pandas: Create a Pandas table from CSV content")
    pandasTable = pd.read_csv(StringIO(csvContent), index_col=False)

    # pandasTable is the dataframe that we want to beautify
    print(pandasTable)

    stylerObject = pandasTable.style

    styledHTML = (stylerObject
        .set_table_attributes('border="1" class="dataframe table table-hover table-bordered"')
        .set_properties(**{'font-size': '16pt', 'font-family': 'Calibri'})
        # .set_properties(subset=['6', '5'], **{'width': '300px'})
        .applymap(colour, subset=['ORGANIZATION'])
        .set_precision(3)
        .set_table_styles(
            [{'selector': 'tr:nth-of-type(odd)',
            'props': [('background', '#eee')]}, 
            {'selector': 'tr:nth-of-type(even)',
            'props': [('background', 'white')]},
            {'selector': 'th',
            'props': [('background', '#606060'), 
                        ('color', 'white'),
                        ('font-family', 'verdana')]},
            {'selector': 'td',
            'props': [('font-family', 'verdana')]},
            ]
        ).hide_index()
        .render()
    )

    with open('myJinjaTable.html', 'w') as f:
        print("Writing an HTML file to view the beautified Jinja table")
        f.write(styledHTML)

    return styledHTML


Solution

  • Figured it out. The lengths of the HREF links were too long apparently. I reduced the size of the links and it renders as expected.