1

I am relatively new to the coding world and trying to use the following python code to send automated email reports.. But i only get the dataframe in the automatic email and not the "Hi this is a test email" in the outlook email body.

Not really sure whats going wrong here.

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(10, 4)), columns=list('ABCD'))

outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'user@email.com'
mail.Subject = 'Insert Subject here'
mailerr1=df.to_html()
attachment  = 'shot.png'
mail.Attachments.Add(attachment)
mail.Body = "hi this is  a test email"
mail.HTMLBody = mailerr1

mail.Send()

Would really appreciate it if someone could give me a heads up on whats happening here.. Thank you.

0m3r
  • 12,286
  • 15
  • 35
  • 71
jack ryan
  • 61
  • 7

1 Answers1

0

You're overwriting your Body when you assign to HTMLBody your email client must be using the HTMLBody by default.

So you need to either combine the dataframe into the Body string, or add your Body as html to the other, here's an example:

email.HTMLBody = '<p>hi this is a test email</p><br>' + mailerr1

You also need to format it into actual html though, see this question: Sending HTML email using Python

tl:dr

email.HTMLBody = """
<html>
  <head></head>
  <body>
    <p>hi this is a test email</p><br>
""" + mailerr1 + """
  </body>
</html>
"""
iggy12345
  • 1,233
  • 12
  • 31
  • It works.Thanks for the answer... So Can I add multiple data frames, screenshots with different formatting for each of them into a single email body this way? That would be really helpful. – jack ryan Oct 04 '19 at 06:38
  • yes, just add more `+ my_dataframe_html` statements – iggy12345 Oct 04 '19 at 06:39
  • If this satisfies your question, please remember to accept the answer – iggy12345 Oct 04 '19 at 06:46
  • Just to follow up on this one, how do I consolidate my CSS code to the HTML here? – jack ryan Oct 04 '19 at 12:21
  • Here's a better in depth tutorial from Sprite Cloud that includes CSS support: https://www.spritecloud.com/creating-and-sending-html-e-mails-with-python/ – iggy12345 Oct 04 '19 at 15:21