首页 > 解决方案 > 如何在从 python 触发的电子邮件中将 pandas 数据框附加为 excel

问题描述

我有一个 pandas 数据框,我想在从 python 触发的自动电子邮件中附加为 xls。如何才能做到这一点

我可以成功发送没有附件的电子邮件,但不能发送附件。

我的代码

import os
import pandas as pd
#read  and prepare dataframe
data= pd.read_csv("C:/Users/Bike.csv")
data['Error'] = data['Act'] - data['Pred']
df = data.to_excel("Outpout.xls")
# import necessary packages
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
# create message object instance
msg = MIMEMultipart()
password = "password"
msg['From'] = "xyz@gmail.com"
msg['To'] = "abc@gmail.com"
msg['Subject'] = "Messgae"
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
# Login Credentials for sending the mail
server.login(msg['From'], password)
server.sendmail(msg['From'], msg['To'], msg.as_string())

标签: pythonpython-3.xpandassmtpmime

解决方案


正如评论中指出的那样,您没有附加文件,因此不会发送。

msg.attach(MIMEText(body, 'plain'))
filename = "Your file name.xlsx"
attachment = open("/path/to/file/Your file name.xlsx","rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename=%s" % filename)

msg.attach(part)
text = msg.as_string()
smtp0bj.sendmail(msg['From'], msg['To'], text)

希望能帮助到你


推荐阅读