使用MIMEApplication将{s}文件附加到smtplib lib电子邮件

时间:2016-04-30 17:13:23

标签: python django amazon-s3 mime

我有一个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打开文件并附加它,但它也引发了一个错误。

不知道从哪里开始,并且想知道是否有人之前已经这样做了。谢谢!

2 个答案:

答案 0 :(得分:1)

您是否考虑过使用S3 get_object而不是smtplib?

function(x: array of string)

答案 1 :(得分:0)

使用urllib对我有用,请看下面的内容,我有这个Lambda函数来发送带有smtplib的电子邮件:

import smtplib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
import urllib
# ['subject','from', 'from_name','to','cc','body','smtp_server','smtp_user','smtp_password']

def lambda_handler(event, context):
    msg = MIMEMultipart('alternative')
    msg['Subject'] = event['subject']
    msg['From'] = formataddr((str(Header(event['from_name'], 'utf-8')), event['from']))
    msg['To'] = event['to']
    msg['Cc'] = event['cc'] # this is comma separated field 

    # Create the body of the message (a plain-text and an HTML version).
    text = "Look in a browser or on a mobile device this HTML msg"
    html = event['body']

    # Record the MIME types of both parts - text/plain and text/html.
    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')

    # Attach parts into message container.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    msg.attach(part1)
    msg.attach(part2)

    # Attach files from S3
    opener = urllib.URLopener()
    myurl = "https://s3.amazonaws.com/bucket_name/file_name.pdf"
    fp = opener.open(myurl)

    filename = 'file_name.pdf'
    att = MIMEApplication(fp.read(),_subtype="pdf")
    fp.close()
    att.add_header('Content-Disposition','attachment',filename=filename)
    msg.attach(att)

    # Create de SMTP Object to Send
    s = smtplib.SMTP(event['smtp_server'], 587)
    s.login(event['smtp_user'], event['smtp_password'])
    s.sendmail(msg['From'], [msg['To']], msg.as_string())

    return True