如何将 Python 数据帧存储在内存中并将其作为 excel 附件发送到特定的电子邮件地址?
Posted
技术标签:
【中文标题】如何将 Python 数据帧存储在内存中并将其作为 excel 附件发送到特定的电子邮件地址?【英文标题】:How do I store Python dataframe in-memory and send it as excel attachment to specific email addresses? 【发布时间】:2021-01-20 19:18:27 【问题描述】:我从 mongo dB 读取数据并创建报告。我曾经将报告保存为本地计算机上的 .xlsx 文件,然后使用电子邮件手动发送。我想自动化这个过程。
我在 Python 3 中找到了一种使用 Python 的 io.BytesIO() 功能将文件保存在内存中的方法。我尝试了一些在堆栈溢出时发现的东西,但它对我不起作用。我想就如何自动化我的工作获得一些建议。
以下是我尝试过的,
df = pd.dataframe(df) # has my reports dataframe
def export_excel(df):
with io.BytesIO() as buffer:
writer = pd.ExcelWriter(buffer)
df.to_excel(writer)
writer.save()
return buffer.getvalue()
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
SEND_FROM = 'myemail@company.com'
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'] = 'myemail@company.com'
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()
我没有收到错误消息,但也没有收到带有 Excel 附件的电子邮件。
【问题讨论】:
嗨,Amogh 你有解决这个问题的办法吗,即使我也面临着类似的问题。 【参考方案1】:我需要解决同样的问题,所以这是我的代码:
import io
import pandas as pd
from pandas import util
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
df = util.testing.makeDataFrame()
# df.head()
output = io.BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
output.seek(0)
send_from = 'my_gmail@gmail.com'
gmail_pwd = 'my_gmail_password'
send_to = 'my_gmail@gmail.com'
subject = 'Daily report'
body = "<p>Please find attached report,<br/>by me</p>"
report_name = "report.xlsx"
msg = MIMEMultipart()
msg['Subject'] = subject # add in the subject
msg['From'] = send_from
msg['To'] = send_to
msg.attach(MIMEText(body, 'html')) # add text contents
file = MIMEApplication(output.read(), name=report_name)
file['Content-Disposition'] = f'attachment; filename="report_name"'
msg.attach(file)
smtp = smtplib.SMTP('smtp.gmail.com:587')
smtp.ehlo()
smtp.starttls()
smtp.login(send_from, gmail_pwd)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.quit()
【讨论】:
以上是关于如何将 Python 数据帧存储在内存中并将其作为 excel 附件发送到特定的电子邮件地址?的主要内容,如果未能解决你的问题,请参考以下文章
发送我想要制作的文件并将其作为IHttpActionResult存储在内存中
Python 3:如何在不保存在磁盘上的情况下将 pandas 数据帧作为 csv 流上传?