How to Send an Email with an Attachment in Django



Python


In this article, we show how to send an email with an attachment in Django.

So we've previously showed how to send email in Django without any attachment.

Now we go more advanced and show how to send an email with an attachment.

So the way we sent an email without an attachment was through the Django send_mail() function.

We cannot use this function to send an email with an attachment, however.

In order to send an email with an attachment, we need to use the EmailMessage class.

As per Django's site, "Django’s send_mail() and send_mass_mail() functions are actually thin wrappers that make use of the EmailMessage class. Not all features of the EmailMessage class are available through the send_mail() and related wrapper functions. If you wish to use advanced features, such as BCC’ed recipients, file attachments, or multi-part email, you’ll need to create EmailMessage instances directly."

So this is what we will do now.

We will create a direct instance (or object) of the EmailMessage class and store this in the variable, msg. Once we add the necessary information to this msg variable, we can then send the email through the send() function.

This is shown in the code below.



So let's go over this code.

So we create an instance (object) of the EmailMessage class.

This takes in the subject of the email, the body, the from email, and the to email(s).

We then make the content HTML. So this email will accept HTML tags.

We then attach a document to this email using the attach_file() function. The document that we attach is called Instructions.pdf in the pdfs folder in the root directory of our project.

We then send the email with the send() function.

So this is really all that is needed to send an email with an attachment in Django.

Sending emails with attachments may be common or uncommon depending on the type of website you are running. Common social media sites such as youtube, facebook, linkedin generally don't send emails with pdfs. However, certain websites do, such as turbotax, if they are sending maybe tax year-end documents to your email. Sending emails with attachments may also be common with ecommerce sites, where they send you a pdf of a recent order you made.

So depending on your website and its use, sending emails with attachments may be a relatively common task.

And this is how to send an email with an attachment in Django.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...