python - 通过电子邮件将 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()
解决方案
我不认为这是可能的win32com
。OutlookAttachments.Add
方法需要一个文件或一个 Outlook 项目作为Source
参数:
附件的来源。这可以是一个文件(由带有文件名的完整文件系统路径表示)或构成附件的 Outlook 项目。
并且pandas.ExcelWriter
还需要path
虽然这个其他类似的问题(和答案)表明可以通过包装ExcelWriter
aBytesIO
来通过电子邮件发送,而不是通过 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)
推荐阅读
- php - 是否可以在 PHP 中声明空变量?
- javascript - filter() 和 some() 不返回预期值
- elasticsearch - 将数据直接从 Elasticsearch 索引导入到 h2o
- c# - 使用 JsonConverter 的 OnDeserialized 回调
- amazon-web-services - 带有 ALB 入口控制器的 Terraform AWS Kubernetes EKS 资源不会创建负载均衡器
- sql - 列第 2 行的值复制到下一列的第 1 行
- javascript - 在 JavaScript 中将对象属性转换为多个对象数组
- locust - 如何使用 Locust 实施尖峰测试?
- excel - 所有减法的总和,同时排除带有文本的单元格
- prolog - SICStus Prolog 垃圾收集跟踪消息