Send pandas dataframe data as html e-mail

Nil*_*age 8 html python email pandas

I want to send a pandas dataframe data as an HTML e-mail. Based on this post I could create an html with the dataframe. Code

import pandas as pd
import numpy as np

HEADER = '''
<html>
    <head>

    </head>
    <body>
'''
FOOTER = '''
    </body>
</html>
'''

df = pd.DataFrame([[1.1, 1.1, 1.1, 2.6, 2.5, 3.4,2.6,2.6,3.4,3.4,2.6,1.1,1.1,3.3], list('AAABBBBABCBDDD')]).T
with open('test.html', 'w') as f:
    f.write(HEADER)
    f.write(df.to_html(classes='df'))
    f.write(FOOTER)
Run Code Online (Sandbox Code Playgroud)

Now I want to send this as a html e-mail. I tried this. Can not figure out how to attach the html file?

Joh*_*y V 9

熊猫具有以下功能:http : //pandas.pydata.org/pandas-docs/stable/generation/pandas.DataFrame.to_html.html

在您可以将表格嵌入到电子邮件中之后,将提供表格的html代码:

df = DataFrame(data)

email = " some html {df} lah lah"

email = email.format(df=df.to_html())
Run Code Online (Sandbox Code Playgroud)


Nil*_*age 4

终于找到了。这是应该做的。

filename = "test.html"
f = file(filename)
attachment = MIMEText(f.read(),'html')
msg.attach(attachment)
Run Code Online (Sandbox Code Playgroud)