Search code examples
pythonpandasemailwin32com

Python How to use DataFrame output in email body as Text


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()

Solution

  • 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.\n\n
                   {}'''.format(Df.to_string())