如何将pandas数据框作为excel从python触发的电子邮件中附加

问题描述 投票:0回答:1

我有一个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'] = "[email protected]"
msg['To'] = "[email protected]"
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())
python python-3.x pandas smtp mime
1个回答
0
投票

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

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)

希望能帮助到你

© www.soinside.com 2019 - 2024. All rights reserved.