我有一个生成并存储在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'] = "[email protected]"
msg['To'] = "[email protected]"
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()方法并将文件的绝对路径传递给上面的代码块。