Search code examples
pythondjangoemaildjango-rest-frameworkemail-attachments

How to attached documents (pdf/images) to Django emailer using the S3 URL to the document creating a file?


I have some Images and PDFs, which are available via their respective S3 URLs. I want to attach these documents to the emails I am sending using the native Django Emailer.

Is there any way I can do so without downloading the Documents on the servers and then attaching them, as it creates an overhead od deleting the documents post Email sent. Also, I don't want to give out the URLs in the Emails hence Images can't be embedded as a part of the HTML in the email.

Im using

Python 2.7
Django 1.9 
DRF 3.4

Solution

  • Assuming your file is stored as a normal file field with s3 path, then you can do the following:

    message = EmailMessage(subject, body, from_email, recipient_list)
    message.attach(FILENAME, xyzmodel.abcfilefield.read())
    

    OR

     from django.core.files.storage import default_storage
     try:
        yourfile = default_storage.open(files3_url, 'r')       
        email.attach(yourfile_name, yourfile.read())
    
    except:
        pass
    

    Hope it will solve your problem !!