我有一個django應用程序,它希望使用smtplib和email.mime庫將文件從S3存儲桶附加到電子郵件。使用MIMEApplication將s3文件附加到smtplib lib電子郵件
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。 – georgeofallages