You most likely found this guide because you wish to use Python to send emails. It's possible that you want your code to send you email reminders to users when they create accounts, or to members of your organization to remind them to pay dues.
Manual email sending is time-consuming and prone to errors, but Python and its Django framework make it simple to automate. The Simple Mail Transfer Protocol (SMTP) can be used to send emails using Python's built-in `smtplib` module. For SMTP, `smtplib` uses the RFC 821 protocol.
The Gmail SMTP server will be used in this tutorial's example to send an email, but the same concepts apply to other email services as well. Although most email providers use the same connection ports described in this tutorial, you may quickly Google yours to make sure it's the right one.
Project Setup and Overview
In this section, we will set up a project to use for illustration purposes in this tutorial and briefly discuss SMTP as a backend protocol for sending emails.
Creating a Django Project
Setting up a Django project is straightforward. It is best practice, which is mostly the first thing to do, to always run new projects in their isolated environments. This helps you take control of the dependencies register. It is noteworthy that the commands in this guide are Unix- and Linux-based. To create a virtual environment for the project, run the following command in the terminal:
`python -m venv .venv`
With the .venv extension, the command above creates a virtual environment. You can use the following to turn on this virtual setting:
`source .venv/bin/activate`.
With the command below, we can install `django` and any other library or depending into our project:
`pip install django`
Time to set up the actual project folder. You use the command-line tool `django-admin` to start a Django project:
`django-admin startproject testmail .`
PS: Take note of the period symbol at the end of the command. It is useful for reducing our folder tree levels by one. You may call your Django project whatever you like; the script above just creates one with the name testmail.
Go ahead and launch the server after entering the project directory:
`cd testmail`
`python manage.py runserver`
Open your browser and go to http://localhost:8000 after starting the Django server. The most recent Django release notes will appear on an automatically produced page.

SMTP Email Backend
A set of guidelines called SMTP (or the Simple Mail Transfer Protocol) governs how emails are sent from senders to recipients. To transmit and relay outgoing emails, SMTP service employs this protocol. It should be noted that different protocols control how emails are received.
The most common port for SMTP servers to use when transmitting messages is 587. An SMTP server always has a unique address. We'll test the port's usefulness while using Django to send emails. We'll be working with the address smtp.gmail.com and essentially, the port 587 because we'll be using Gmail. Now, let us walk through sending an email using the django framework.
Modifying the Project Backend
Before sending emails, you must edit the settings file, therefore let's find that file in the project setup. You will find a file named `settings.py` in the project folder. Open the folder, we will be making modifications in it.
You can set custom variables in settings.py, which contains all the project configuration information you'll need. A settings file is merely a Python module with module-level variables, according to the Django documentation.
At the end of the file (or anywhere in the file), paste the following settings:
```xml
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = ’ '
EMAIL_PORT = ' '
EMAIL_HOST_USER = ' '
EMAIL_HOST_PASSWORD = ' '
EMAIL_USE_TLS = ‘ ‘
```
Let's dissect the aforementioned code by looking at each of these settings.
Email Backend
The backend that our Django project will use to connect to the SMTP server is specified by the EMAIL BACKEND parameter.
The smtp.EmailBackend class, which gets all the email-sending parameters, is pointed to via this variable. You should definitely look at the class constructor directly in the Django source code, in my opinion. This code is quite readable, as you'll discover.
Email Host
Your email provider will choose the SMTP server domain you will use, which is indicated by the EMAIL HOST parameter.
Email Port
The default port for the majority of SMTP servers is 587, so the EMAIL PORT parameter must be set to that value. For providers of personal email, this still holds true. In order to ensure the security of email sending, this port is utilized in conjunction with TLS encryption.
Email Host User
You can enter your own email address in the EMAIL HOST USER option. Usually the ESP will provide this credential for you, at the point of creating an account with them.
Email Host Password
The app password you receive from your email account will be entered in the EMAIL HOST PASSWORD option, which we'll be doing immediately after this step.
Email Use TLS
The connection between web apps (like Django) and servers is encrypted using the security protocol known as Transport Layer Security (TLS) on the Internet (SMTP server).
The setting EMAIL USE TLS was initially set to True. In order to connect to the SMTP server and send emails, Django will require Transport Layer Security. (It is required for providers of personal email.)
Sending Mail - SMTP
To build and send an email in Python, there is an in-built function that makes this easy and fast. It’s the Send Mail Function - send_mail()
This is Django's most fundamental email delivery feature. It has four required parameters that must be specified: `subject`, `message`, `from_email`, and `recipient_list`. Along with them, you can change the following:
`auth_user`: This username will be used to authenticate to the SMTP server if EMAIL HOST USER has not been defined or if you want to override it.
`auth password`: This password will be used to authenticate to the SMTP server if EMAIL HOST PASSWORD has not been supplied.
`connection`: You can use this optional email backend without changing EMAIL BACKEND.
`html_message`: You can send multipart emails using this parameter.
1fail_silently`: failure handling in the backend is determined by the boolean value fail silently. Exceptions will be silently disregarded if True. `Smtplib.SMTPException` will be triggered if the value is False.
```python
from django.core.mail import send_mail
from django.core import settings
send_mail(
subject = 'That’s your subject'
message = 'That’s your message body'
from_email = settings.EMAIL_HOST_USER,
recipient_list = [your-recipient-list]
auth_user = 'Login'
auth_password = 'Password'
fail_silently = False,
)
```
Let’s understand the code above:
- The Django send mail function is imported.
- The settings object, which contains both global and per-site options, is then imported (those inside the settings.py file).
- Finally, we call the send mail method with all the required inputs.
Sending Multiple Emails
You must establish a connection and then shut it in order to send a message using SMTP. When you need to send several transactional emails, this strategy is quite awkward. Making just one connection and using it for all messages is preferable. A trusted choice for delivering several messages with just one connection is `send_mass_mail`. Let us look at the snippet below:
```python
message1 = ('That’s your subject #1',
'That’s your message body #1',
'from@yourdjangoapp.com',
['to@yourbestuser1.com', 'to@yourbestuser2.com'])
message2 = ('That’s your subject #2',
'That’s your message body #2',
'from@yourdjangoapp.com',
['to@yourbestuser2.com'])
message3 = ('That’s your subject #3',
'That’s your message body #3',
'from@yourdjangoapp.com',
['to@yourbestuser3.com'])
send_mass_mail((message1, message2, message3), fail_silently=False)
```
`subject`, `message`, `from email`, and `recipient_list` are all parameters that are included in every email message. Additional arguments that are the same as for `send_mail` are optional.
Sending HTML Emails
Users of earlier versions will need to fiddle with EmailMessage and its subclass EmailMultiAlternatives. It allows you to use the attach alternative function to include various message body iterations.
```python
from django.core.mail import EmailMultiAlternatives
subject = 'That’s your subject'
from_email = 'from@yourdjangoapp.com>'
to = 'to@yourbestuser.com'
text_content = 'That’s your plain text.'
html_content = '<p>That’s <strong>the HTML part</strong></p>'
message = EmailMultiAlternatives(subject, text_content, from_email, [to])
message.attach_alternative(html_content, "text/html")
message.send()
```
Thankfully, starting with version 1.7, you may use send mail to send an email with HTML content like this:
```python
from django.core.mail import send_mail
subject = 'That’s your subject'
html_message = render_to_string('mail_template.html', {'context': 'values'})
plain_message = strip_tags(html_message)
from_email = 'from@yourdjangoapp.com>'
to = 'to@yourbestuser.com'
mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)
```
Sending Emails with Attachment
For use to send email in Django with attachment. We can use the `attach` or `attach_file` methods to do this. With the help of three arguments—filename, content, and mime type—the first one creates and inserts a file attachment.
```python
message.attach('Attachment.pdf', file_to_be_sent, 'file/pdf')
```
The second technique attaches a file from a filesystem. Each technique would appear like this in practice:
```python
message.attach_file('/documents/Attachment.pdf')
```
Sending Mails - Google Gmail SMTP
Configuring Google SMTP provider
You must edit and add a few more settings to your project with the information from your Google Gmail account in order to finish the process of sending emails via the Google Gmail SMTP service. Be aware that certain information, such as the account and password, should be kept private. Setting them as environment variables will accomplish this. Django-environ is a very effective third-party program for this task.
```xml
DEFAULT_FROM_EMAIL = '<Your gmail account goes here>'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '<Your gmail account goes here>'
EMAIL_HOST_PASSWORD = '<Your app password here>'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
```
Now, you have Google SMTP configuration set in your project. See the next subsection for how to set up an App Password.
Setting up an App Password
You must authorize access for less secure programs using this link in order to send emails from your Google Gmail account.

Take note that secure apps cannot be used with Google accounts that have 2-step Verification enabled. You utilize app passwords instead. Use this link to create an app password.
Sending emails with Gmail SMTP
To demonstrate an email sending procedure, we will use the `send_mail()` function and the Google SMTP configurations, which we described in their previous subsections respectively. Using the django shell, call the `send_mail` supplied with its respective arguments and test the email sending.
```python
send_mail(
'Message Subject',
'Message Body',
settings.EMAIL_HOST_USER, # This imports Google user credential
[<you recipient email here>]
# Other fields as described before are not compulsory
)
```
Now check the email address in the `recipient_list` field for the email. It should have dropped as you wrote it. That is essentially how to send emails, with Google Gmail SMTP configuration set in the backend.
Email Libraries in Django
Django offers a few simple wrappers over the mail sending interface that Python's `smtplib` module provides for usage and adaptation. These wrappers, also known as libraries, are offered to speed up email sending even further, to aid in test email sending while developing, and to support platforms that cannot use SMTP.
- django-mailer`: A reusable Django application for email queuing is called django-mailer. Email is saved in the database and sent at a later time. The database will be significantly more dependable and quick for many apps than existing email sending backends, which rely on 3rd party services like SMTP or an HTTP API. By saving and sending later, we may return success right away and then try sending actual emails in the background, with retries as necessary.
- django-templated-email`: The goal of django-templated-email is to send templated emails. The library allows for customizable template naming and location, template inheritance, and adding CC and BCC recipients. The `render to response` shortcut for email can be compared to the send templated email method.
- `django-anymail`: You can send and receive emails in Django using any of your preferred transactional email service providers (ESPs) with Anymail. It adds numerous common ESP-added functionalities to the standard django.core.mail, resulting in a consistent API that prevents your code from being locked to a single ESP (and making it easier to change ESPs later if needed). Anymail is thoroughly tested on all Python versions supported by Django and retains compatibility with all Django versions that are in mainstream or extended support, as well as (typically) a few earlier Django versions.
- `django-email`: A simple wrapper for Django's multialternative email sending, django-email. You must give both an HTML version and a plain text template (.txt) for this (.html). The boilerplate necessary for sending an email is reduced by Django email, which takes your template and context, renders it, and sends the email. Developers can always modify the library to suit their needs, although it makes an effort to use sensible defaults. The subject, email from, email to, and other settings are all customizable. Nothing else is presumptive, save that the templates must not have extensions.
To Wrap Up
You now know how to create a prototype email service and use Django in various ways to send emails. You were specifically shown how to send a test email using the Django Shell and the Gmail mail server setup.
Emails can be sent in a variety of ways using Django. In this instruction, you used your personal email address to complete the task. You can, interestingly, investigate different technologies and incorporate them into your work.
We have covered the following topics in this tutorial:
- instructions on how to configure Django to serve emails
- how to create the email backend for Gmail and set up the App Password for Gmail
- how to send emails in a small project using a personal email account