【问题标题】:Pythone :How to use dataframe output in email body as TextPython:如何将电子邮件正文中的数据框输出用作文本
【发布时间】:2019-01-18 20:17:03
【问题描述】:

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

【问题讨论】:

  • pandas 和 win32com.client 用于通过 Outlook 发送电子邮件

标签: python pandas email win32com


【解决方案1】:

检查下面的代码...

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()

【讨论】:

    【解决方案2】:

    考虑一下 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())
    

    【讨论】:

      【解决方案3】:

      如果您想要print(Df) 给出的相同输出,请将数据帧转换为字符串。

      mail.Body = str(Df)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-14
        • 1970-01-01
        • 2011-04-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多