Pythone:如何在电子邮件正文中使用数据框输出作为文本

时间:2018-08-11 12:25:10

标签: python pandas email-integration win32com

我有一个数据帧Df的输出,我可以将其作为附件发送到邮件中,但不能在邮件正文中打印Df值。建议在电子邮件正文中打印我的Df值,这样我就不必添加附件。

import win32com.client as win32

outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'abc@xyg.com'
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()

3 个答案:

答案 0 :(得分:0)

如果您希望提供相同的输出print(Df),请将数据帧转换为字符串。

mail.Body = str(Df)

答案 1 :(得分:0)

请考虑熊猫的DataFrame.to_html(),它将DataFrame.to_string()的数据声名呈现给HTML表,以用于电子邮件的HTMLBody。如果不指定文件名,它将以字符串形式输出表。

...
mail.Subject = 'Madsaage Subject'

mail.HTMLBody = '''<h3>Please find data attached and below.</h3>
                   {}'''.format(Df.to_html())
...

或者,在电子邮件的正文中使用^[-+]?(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)(?:,\s*[-+]?(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)){2}$

mail.Body = '''Please find data attached and below.\n\n
               {}'''.format(Df.to_string())

答案 2 :(得分:0)

检查以下代码...

import win32com.client as win32
import pandas as pd

df = pd.read_excel('fullpathtoxl.xlsx', index_col=False, nrows = 5,  usecols = "A:D")

html_table = df.to_html()

print(html_table)

outlook = win32.gencache.EnsureDispatch('Outlook.Application')
mail_item = outlook.CreateItem(0)
mail_item.To = 'abc@gmail.com'

#  modify the mail body as per need

mail_item.Attachments.Add(Source='C:\folder\folder\download.png')
body = "<h1>Dear ABC</h1>This is the Table <br><br>   "+html_table+"   <br><br> this is image <br><br><img src=ownload.png><br><br>Thanks"
mail_item.HTMLBody = (body)
mail_item.Send()