python - 如何在电子邮件中将数据框附加为 excel 并从 python 发送该附件?
问题描述
我有一个文件,它生成并存储在 AWS 的 S3 存储桶中。我想要将此 S3 文件作为 excel 发送到使用 python 发送的电子邮件中的附件,如何做到这一点。
我成功地能够发送没有附件的电子邮件。
我的代码
import os
import boto3
import pandas as pd
from sagemaker import get_execution_role
role = get_execution_role()
bucket='cotydata'
data_key = 'modeloutput'+'.csv'
data_location = 's3://{}/{}'.format(bucket, data_key)
output_key='UI_'+input_date
output_bucket='model-output-ui'
# Insert weather api key here
api_key= 'key'
#read modeloutput and prepare dataframe
modeloutput = pd.read_csv(data_location)
df = modeloutput.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'] = "riskradar@gmail.com"
msg['To'] = "abc@gmail.com"
msg['Subject'] = "Messgae"
filename = df
f = file(filename)
attachment = MIMEText(f.read(),'xls')
msg.attach(attachment)
# attach image to message body
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())
任何帮助表示赞赏
解决方案
无需从 xls 文件中生成 pandas 数据框。
msg = MIMEMultipart('mixed')
fp = open(data_location, 'rb')
record = MIMEBase('application', 'octet-stream')
record.set_payload(fp.read())
encode_base64(record)
record.add_header('Content-Disposition', 'attachment',
filename="what_ever_header_you_want.xls")
msg.attach(record)
其余的就像你写的那样。这应该可以解决问题。
如果您想将数据帧作为 excel 文件发送,则可以使用 to_excel() 方法并将文件的绝对路径传递给上面的代码块。
推荐阅读
- delphi - Delphi - Colordialog 选择黑色作为颜色
- c# - C# .Net 确定 OpenFileDialog 的哪个控件调用
- sql - 可以加入动态吗?取决于列的内容?
- generics - 强制转换为 Rust 中的推断函数类型
- git - git pull 并跳过我在本地已有的文件
- javascript - 滚动时将粘性导航栏的边框半径更改为零?
- html - Flexbox 在 ASP.NET MVC (FX) 应用程序中错位共享布局组件
- excel - 在列中查找字符串列表
- android - React Native - getDailyStepCountSamples 和 Google Fit App 之间的步骤不匹配
- android - 随着设备在android中移动,如何在ARCore中移动节点(位置标记)?