How attach pandas dataframe as excel in email trig

2019-08-21 10: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条回答
太酷不给撩
2楼-- · 2019-08-21 11:45

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

查看更多
登录 后发表回答