在pywin32 Outlook电子邮件中发送表格 [英] Send table in pywin32 outlook email

查看:49
本文介绍了在pywin32 Outlook电子邮件中发送表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用类似下面的代码在 Python 中自动发送电子邮件.

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

如何使表格看起来像是从 excel 复制到电子邮件中(即表格格式)?目前它将 html 格式的表格视为电子邮件正文中的文本,这是非常无用的.

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> 

推荐答案

我想出了如何做到这一点.原代码中需要修改一行代码.而不是使用:

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

newMail.Body = body

改为这样做:

newMail.HTMLBody = body

这篇关于在pywin32 Outlook电子邮件中发送表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆