pandas 发送带有熊猫数据框作为附件的电子邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39999964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:11:31  来源:igfitidea点击:

send email with a pandas dataframe as attachment

pythonemailpandas

提问by Andrei Cozma

I have a pandas dataframe that I am looking to convert into an xlsx and attach to an email. I can send emails based on outlook(this is the only way I can do it). I am able to convert the dataframe into an xlsx and save it on my drive and afterwards send it as attachment but I am looking to attach it directly without having to save it on my drive. see bellow my function to send emails:

我有一个 Pandas 数据框,我希望将其转换为 xlsx 并附加到电子邮件中。我可以根据 Outlook 发送电子邮件(这是我能做到的唯一方法)。我能够将数据帧转换为 xlsx 并将其保存在我的驱动器上,然后将其作为附件发送,但我希望直接附加它,而不必将其保存在我的驱动器上。请参阅下面我发送电子邮件的功能:

def email():
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject ="FRANCE SO"
newMail.Body =' '
newMail.To = "email adress"
newMail.Attachments.Add(attachment)
newMail.Send()
return

attachment is the dataframe that has been transformed into xlsx

附件是转换成xlsx的数据框

回答by snooze92

Have you tried to play with the iomodule in Python 3? It allows you to use streams as file-like objects, so that APIs that expect a file can read from or save their content to the stream instead.

您是否尝试过使用ioPython 3 中的模块?它允许您将流用作类似文件的对象,以便期望文件的 API 可以从流中读取或将其内容保存到流中。

That works nicely, using a StringIOalong with pandas.DataFrame.to_csv:

这很好用,使用StringIOwith pandas.DataFrame.to_csv

import io

def export_csv(df):
  with io.StringIO() as buffer:
    df.to_csv(buffer)
    return buffer.getvalue()

That works, because to_csvexpects a string (interpreted as a path) or a file handle, and StringIOcan be used like a file handle. Unfortunately, pandas.DataFrame.to_excelworks with either a string (interpreted as a path) or an ExcelWriter. In that case, we need to create the ExcelWriterourselves, and wrap a BytesIOwith it.

这是有效的,因为to_csv需要一个字符串(解释为路径)或文件句柄,并且StringIO可以像文件句柄一样使用。不幸的是,pandas.DataFrame.to_excel使用字符串(解释为路径)ExcelWriter. 在这种情况下,我们需要创建ExcelWriter自己,并BytesIO用它包装 a 。

import io
import pandas as pd

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

I am not familiar with the Outlook Python tools for sending emails, I use SMTP:

我不熟悉用于发送电子邮件的 Outlook Python 工具,我使用 SMTP:

from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib

SEND_FROM = '[email protected]'
EXPORTERS = {'dataframe.csv': export_csv, 'dataframe.xlsx': export_excel}

def send_dataframe(send_to, subject, body, df):
  multipart = MIMEMultipart()
  multipart['From'] = SEND_FROM
  multipart['To'] = send_to
  multipart['Subject'] = subject
  for filename in EXPORTERS:    
    attachment = MIMEApplication(EXPORTERS[filename](df))
    attachment['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
    multipart.attach(attachment)
  multipart.attach(MIMEText(body, 'html'))
  s = smtplib.SMTP('localhost')
  s.sendmail(SEND_FROM, send_to, multipart.as_string())
  s.quit()

I hope this helps, good luck!

我希望这会有所帮助,祝你好运!