【发布时间】:2016-08-25 18:22:11
【问题描述】:
我有一个 django 应用程序,它想使用 smtplib 和 email.mime 库将文件从 S3 存储桶附加到电子邮件。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# This takes the files and attaches each one within the bucket to the email. The server keeps erroring on the "with open(path,'rb') as fil" .
def attach_files(path_to_aws_bucket,msg,files=[]):
for f in files or []:
path = path_to_aws_bucket + f
with open(path,'rb') as fil:
msg.attach(MIMEApplication(
fil.read(),
Content_Disposition='attachment; filename="{}"' .format(os.path.basename(f)),
Name=os.path.basename(f)
))
return msg
def build_message(toaddress,fromaddress,subject,body):
msg = MIMEMultipart('alternative')
msg['To'] = toaddress
msg['From'] = fromaddress
msg['Subject'] = subject
b = u"{}" .format(body)
content = MIMEText(b.encode('utf-8') ,'html','UTF-8')
msg.attach(content)
return msg
def send_gmail(msg,username,password,fromaddress,toaddress):
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(fromaddress, toaddress , msg.as_string())
server.quit()
Python 无法打开该文件,因为它声称我给它的任何 s3 url 都不是有效目录。我所有的权限都是正确的。我尝试使用 urllib.opener 打开文件并附加它,但它也引发了错误。
不知道从哪里开始,想知道以前是否有人这样做过。谢谢!
【问题讨论】:
-
您是如何在 django/python 环境中连接到 s3 的?您是否将本地目录映射到 s3 存储桶? python open 函数期望读取本地文件系统,而不是 s3。
标签: python django amazon-s3 mime