Python How to use DataFrame output in email body as Text

Question:

I have a output of a dataframe Df , I am able to send it in mail as an attachment, but not able to print Df value in message body. Please advise to print my Df value in email body so I won’t have to add attachment.

import win32com.client as win32

outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = '[email protected]'
mail.Subject = 'Madsaage Subject'
mail.Body = 'print(Df)'
mail.HTMLBody = 'Please  Find Attached'  # This field is optional
# To attach a file to the email (optional):
mail.Attachments.Add('C:/XYZ/transport.csv')
mail.Send()
Asked By: Madhukar Singh

||

Answers:

If you want the same output print(Df) would give, cast the dataframe to a string.

mail.Body = str(Df)
Answered By: AKX

Consider pandas’s DataFrame.to_html() which renders data fame to HTML table to be used in email’s HTMLBody. If you do not specify a filename it will output table as a string.

...
mail.Subject = 'Madsaage Subject'

mail.HTMLBody = '''<h3>Please find data attached and below.</h3>
                   {}'''.format(Df.to_html())
...

Alternatively, use DataFrame.to_string() in the email’s Body.

mail.Body = '''Please find data attached and below.nn
               {}'''.format(Df.to_string())
Answered By: Parfait

Check below code…

import win32com.client as win32
import pandas as pd

df = pd.read_excel('fullpathtoxl.xlsx', index_col=False, nrows = 5,  usecols = "A:D")

html_table = df.to_html()

print(html_table)

outlook = win32.gencache.EnsureDispatch('Outlook.Application')
mail_item = outlook.CreateItem(0)
mail_item.To = '[email protected]'

#  modify the mail body as per need

mail_item.Attachments.Add(Source='C:folderfolderdownload.png')
body = "<h1>Dear ABC</h1>This is the Table <br><br>   "+html_table+"   <br><br> this is image <br><br><img src=ownload.png><br><br>Thanks"
mail_item.HTMLBody = (body)
mail_item.Send()
Answered By: Hietsh Kumar
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.