首页 > 解决方案 > Pythone:如何将电子邮件正文中的数据框输出用作文本

问题描述

我有一个数据框 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()

标签: pythonpandasemailwin32com

解决方案


考虑 pandas DataFrame.to_html(),它将数据成名呈现给 HTML 表格以用于电子邮件的 HTMLBody。如果您不指定文件名,它会将表输出为字符串。

...
mail.Subject = 'Madsaage Subject'

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

或者,DataFrame.to_string()在电子邮件的正文中使用。

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

推荐阅读