首页 > 解决方案 > 通过电子邮件将 DF 作为附件发送

问题描述

我想通过电子邮件将 Pandas 数据框作为 excel .xlsx 附件发送。如果我通过 将 df 保存为 excel 文档df.to_excel(),则可以使用attachment = "C:\\Users\\ME\\Documents\\df.xlsx". 但是,我希望能够在不先保存的情况下将 df 作为 .xlsx 发送。谢谢!

import win32com.client as win32
df = pd.DataFrame([1,2])

mail = outlook.CreateItem(0)
mail.To = 'recipient@gmail.com'
mail.Subject = 'See Attachment'
mail.HTMLBody = 'See Attachment'
attachment  = df.to_excel()
mail.Attachments.Add(attachment)
mail.Send()

标签: pythonpandas

解决方案


我不认为这是可能的win32com。OutlookAttachments.Add方法需要一个文件或一个 Outlook 项目作为Source参数:

附件的来源。这可以是一个文件(由带有文件名的完整文件系统路径表示)或构成附件的 Outlook 项目。

并且pandas.ExcelWriter还需要path 虽然这个其他类似的问题(和答案)表明可以通过包装ExcelWriteraBytesIO来通过电子邮件发送,而不是通过 Outlook:

def export_excel(df):
  with io.BytesIO() as buffer:
    writer = pd.ExcelWriter(buffer)
    df.to_excel(writer)
    writer.save()
    return buffer.getvalue()

但这似乎不适用于 Outlook API(刚刚测试过):

>>> attachment  = export_excel(df)
>>> mail.Attachments.Add(attachment)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<COMObject <unknown>>", line 3, in Add
pywintypes.com_error: (-2147024809, 'The parameter is incorrect.', None, None)

推荐阅读