Emails with Django

Learn via video courses
Topics Covered

Overview

Django is an open-source, Python-based framework with a ready-to-use, lightweight email engine. Most web applications utilize email to handle important tasks, including password resets, account activations, customer feedback gathering, newsletter distribution, and marketing campaigns. For sending the email through the Django framework, we have to import the django.core.mail module in our Django project.

Pre-requisites

  • You should know the basics of Django views.
  • You should know the basic email-sending process.

Introduction

Django uses the django.core.mail module, which is based on smtplib to deliver the email service. The email delivery is carried out via the SMTP host. The send_mail() and send_mass_mail() methods in Django are basically thin wrappers that use the EmailMessage class. EmailMessage is in charge of constructing the actual email message. The email backend is then responsible for transmitting the message.send_mail is the most fundamental email delivery function in Django. EMAIL_BACKEND is specified as django.core.mail.backends.smtp.EmailBackend. It is the default configuration that uses SMTP server for email delivery.

Email Backend

The EMAIL_BACKEND parameter specifies the Django backend that will be used by our Django project to connect to the SMTP server. The email backend handles the actual sending of an email. The EMAIL BACKEND parameter specifies the backend that our Django app will use to connect to the SMTP server. EMAIL_BACKEND refers to the smtp.EmailBackend is class that gets all the parameters required to send an email.

The EmailBackend class has the following methods:

  • open() creates a long-lived email-sending connection.
  • close() This method is used in terminating the connection of the current email sender.
  • send messages(email messages) This method is used to send a list of EmailMessage objects which we had declared in the email variable. If the connection is not open, this function call will open it implicitly and then shut it. If the connection is already open, it will be kept open after the message has been transmitted.

Email host

The EMAIL_HOST setting specifies the SMTP server domain that you will use to send the email. This is determined by your email provider. The following table shows the SMTP server host for three common providers:

Email providerSMTP server host
Yahoosmtp.mail.yahoo.com
Gmailsmtp.gmail.com
Hotmail/Outlooksmtp-mail.outlook.com

Email Port

The EMAIL_PORT must be set to 587 because it is the default port for most SMTP servers. This is still true for personal email providers. In order to ensure the security of email sending, this port is utilized in conjunction with TLS encryption.

Sending a Simple Email

For sending an email via Django, we have to follow the following steps: Step-1: Set up a basic Django app. For the creation of a simple Django app, run the following commands. Before running the commands, make sure that Django is already installed in your system:

The above command will create a Django project named "djemail". After creating a Django project, we have to create a Django app with the following command.

The above command will create an app named "mail".

Step-2: Configuring the setting.py file of the project open the setting.py file of the Django project and paste the following code:

Step-3: Creating the view function to send the mail open the view.py file of the app and paste the following code:

In the above function the main function is send_mail is the most fundamental email delivery function in Django. It requires four mandatory parameters: subject, message, from email, and recipient list.

Syntax:

  • subject: It is a string-type value.
  • message: It is a string-type value.
  • from_email: It is a string type value. If the value is None, Django will use the value of the DEFAULT_FROM_EMAIL setting.
  • recipient_list: It is a list of strings that contains an email address. Each recipient_list member will see the other recipients in the email message's "To:" field.
  • fail_silently: It is a boolean expression. If it is False, send mail() will throw a smtplib. 
  • auth_user: The optional username for logging in to the SMTP server. If this is not specified, Django will utilize the EMAIL_HOST_USER option.
  • auth password: The optional password used to log in to the SMTP server. If this is not specified, Django will use the value of the EMAIL HOST PASSWORD property.
  • connection: This is an optional email backend to use to send the mail. If not given, the default backend will be utilized.
  • html_message: If an HTML message is specified, the resultant email will be a multipart/alternative email with the text/plain content-type message and the text/html content-type Html message.

For better understanding, check the example mentioned below:

Step-4 Connect the view to the URL. Create a file named urls.py in the <project>/<app>/url.py file, and write this code in it:

The above code connects any blank URL with the sendSimpleEmail view we had already mentioned in the view.py file. Now we have connected the URL to views in our app. But we have to connect this app URL with the project URL. To connect app URLs, we have to go to project urls.py and write this code.

In the above code, we connected the blank route to the email.urls which means all the requests with blank will redirect to app urls.py Now we can start the Django server to see the output. To run the server, we have to go to the project directory and write the following command in the terminal in windows.

Now in the browser, if we go to 8000 port, the email will be sent to the recipient email.

Sending Multiple Mails with send_mass_mail

Django uses send_mass_mail to delivering multiple messages with just one connection. django.core.mail.send_mass_mail() is intended to handle mass emailing.

Syntax

Datatuple is a tuple in which each element is in this format:

The primary distinction between send_mass_mail() and send_mail() is that send_mail() creates a new connection to the mail server for each message, whereas send_mass_mail() utilizes a single connection for all messages. This makes send_mass_mail() somewhat faster.

For sending the bulk emails, we can use the following code in the view function

Sending HTML E-mail

We can send the email through an HTML template in Django. In this method, the message body will be written in the Django template, and we can pass any value to the Django template using the context in the view.

Sending Email with Attachment

In the above sections of blog, we saw how to send emails in Django. We can also send the email with the attachment by using attach or attach_file methods. The attach method creates and adds a file attachment through three arguments – filename, content, and mime type.

The attach_file method uses a file from a filesystem as an attachment.

Build an Automated Contact Form with Django

In this section, we will create an automated contact form in which, if any user fills the form, the entry of that form will be sent to the respective admin. We had already set up the Django project in the above blog section, so we will continue after that. Firstly we will create a forms.py file inside the Django app(app name is mail).

forms.py file

After creating the form we will connect this form to view and template.

View.py file

Html template for the sending the email.

contactform.html file

Html Template for the taking input to the form.

index.html file

Now last we will connect the view to the urls.

app urls.py file

The entire directory tree will be look like the as below:

SMTP with Django

SMTP (Simple Mail Transfer Protocol) is an application layer TCP/IP protocol used to send and receive email. Django uses django.core.mail.backends.smtp.EmailBackend module to send the email. It is the default configuration that uses an SMTP server for email delivery. Defined email settings will be passed as matching arguments to EmailBackend. Django mails are sent by using the SMTP host and port mentioned in the EMAIL_HOST and EMAIL_PORT settings. We can set the EMAIL_HOST_USER and EMAIL_HOST_PASSWORD options to authenticate to the SMTP server, while the EMAIL_USE_TLS and EMAIL_USE_SSL parameters determine whether a secure connection is utilized.

Conclusion

  • Django uses django.core.mail module to send the email.
  • The EMAIL_BACKEND parameter specifies the Django backend that will be used by our Django project to connect to the SMTP server.
  • The EMAIL_HOST setting specifies the SMTP server domain that you will use to send the email. This is determined by your email provider.
  • The EMAIL_PORT must be set to 587 because it is the default port for most SMTP servers. This is still true for personal email providers.
  • send_mail function is used to send a single email in Django, while send_mass_mail is used to send mass emails.
  • The primary distinction between send_mass_mail() and send_mail() is that send_mail() creates a new connection whereas send_mass_mail() utilizes a single connection for all messages.
  • We can also send the email with the attachment by using the attach or attach_file methods.