首页 > 解决方案 > 如何在电子邮件中将数据框附加为 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())

任何帮助表示赞赏

标签: pythonpython-3.xpandasemailsmtp

解决方案


无需从 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() 方法并将文件的绝对路径传递给上面的代码块。


推荐阅读