python - 如何在从 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())
解决方案
正如评论中指出的那样,您没有附加文件,因此不会发送。
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)
希望能帮助到你
推荐阅读
- android-studio - android studios/gradle 同步启动时多个重复的 Openjdk 二进制文件失败,96% RAM
- django - django-allauth Google 登录无法在 iOS 上运行
- python - 如何更改标签的文本 - Tkinter
- python-3.x - 如何在 Python3 中将日志记录与多处理一起使用
- windows - 损坏的包管理器?找不到模块提供程序 (PowerShellGet)
- azure - 获取 Azure Log Analytics 免费层
- html - 使Div中的图像不调整大小
- r - 在 UI 出现后延迟加载 Shiny 中的库,但在实际需要之前
- python - 如何查找文件中有多少个相同的单词?
- c++ - 在 C++ 中格式化文本文件