Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send table in pywin32 outlook email

I use something like the following code to send emails automatically in Python.

How do I make the table look like it was copied from excel into the email (i.e. table formatting)? Currently it treats the html formatted table as text within the body of the email, which is pretty useless.

import win32com.client
import pandas as pd

#Parameters
data= [{'A' : 'data', 'B': 2, 'C':1.78},
      {'A' : 'data', 'B': 22, 'C':1.56},]
table = pd.DataFrame(data)

subject = 'email subject'
body = '<html><body>' + table.to_html() + '</body></html>'
recipient = '[email protected]'
attachments = []

#Create and send email
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = subject
newMail.Body = body
newMail.To = recipient

for location in attachments:
    newMail.Attachments.Add(Source=location)

newMail.display()
newMail.Send()

Sends an email that looks like this when I want it to be an actual table:

<html><body><table border="1" class="dataframe"> 
  <thead> 
    <tr style="text-align: left;"> 
      <th>A</th> 
      <th>B</th> 
      <th>C</th> 
    </tr> 
  </thead> 
  <tbody> 
    <tr> 
      <td> data</td> 
      <td> 2</td> 
      <td> 1.78</td> 
    </tr>
    <tr> 
      <td> data</td> 
      <td> 22</td> 
      <td> 1.56</td> 
    </tr> 
  </tbody> 
</table></body></html> 
like image 894
Nathan Clement Avatar asked Nov 17 '15 21:11

Nathan Clement


1 Answers

I figured out how to do this. One line of code needs to change in the original code. Instead of using:

newMail.Body = body

Do this instead:

newMail.HTMLBody = body
like image 135
Nathan Clement Avatar answered Oct 11 '22 07:10

Nathan Clement