How attach pandas dataframe as excel in email triggered from python

不想你离开。 提交于 2019-12-11 20:26:50

问题


I have a pandas dataframe which I want attach as xls in an automated email triggered from python. How can this be done

I am able to send the email without attachment successfully but not with the attachment.

My code

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())

回答1:


As pointed out in comment you are not attaching the file, so it would not be sent.

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)

Hope it helps



来源:https://stackoverflow.com/questions/55770471/how-attach-pandas-dataframe-as-excel-in-email-triggered-from-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!