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?
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()
Exporting the DataFrame into a CSV filePandas DataFrame to_csv() function exports the DataFrame to CSV format. If a file argument is provided, the output will be the CSV file. Otherwise, the return value is a CSV format like string. sep: Specify a custom delimiter for the CSV output, the default is a comma.
Try:
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())
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With