Send table in pywin32 outlook email

烈酒焚心 提交于 2020-12-08 07:04:25

问题


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@domain.com'
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> 

回答1:


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


来源:https://stackoverflow.com/questions/33767081/send-table-in-pywin32-outlook-email

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!