本文介绍了如何将python触发的电子邮件中的 pandas 数据框附加为Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个熊猫数据框,我想将其作为xls附加在从python触发的自动电子邮件中.该怎么办
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.
我的代码
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())
推荐答案
正如注释中指出的那样,您没有附加文件,因此不会发送该文件.
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)
希望有帮助
这篇关于如何将python触发的电子邮件中的 pandas 数据框附加为Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!