Yurii Shumak | 11 Apr, 2023

How To Send Emails In Django [Easy Tutorial]

You probably have some kind of subscription or newsletter on your website. Don’t you think it’s time to send a message in digital form to all of your site visitors? That’s right! An e-mail is the best and most convenient way to reach your users with the information they want to know. But, how can you implement this in your Django project? 

Using Django, you can accelerate email delivery and make it much easier. These Django code samples will show you how to send emails. In this blog post, we will show you a simple and effective way to do that. Let’s get started!

Setting Up

At the beginning of the file, import `send_mail` to send emails in Django. It is that simple.

```python

from django.core.mail import send_mail

```

Call the given code at the necessary location.

```python

send_mail(

'That’s your subject',

'That’s your message body',

'from@yurii.com',

['to@yourfriend.com'],

fail_silently=False,

)

```

The plain text email sending functionality is provided by the `django.core.mail` module, which is based on the Python SMTP library.

All the settings are set by default to deliver messages via the SMTP host:

```python

EMAIL_HOST: 'localhost'

EMAIL_PORT: 25

EMAIL_HOST_USER: (Empty string)

EMAIL_HOST_PASSWORD: (Empty string)

EMAIL_USE_TLS: False

EMAIL_USE_SSL: False

```

By default, emails are sent with `django.core.mail` using the values of your `DEFAULT_CHARSET` setting for the character set.

You can find out about the other default values [**here**](https://docs.djangoproject.com/en/dev/ref/settings/). You probably need to change them, so let's edit the *settings.py* file.

Setting up your email before sending is crucial. So, let's modify the *settings.py* file in your Django application.

```python

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_HOST = '[smtp.yourserver.com](http://smtp.yourserver.com/)'

EMAIL_PORT = '<your-server-port>'

EMAIL_HOST_USER = ''from@yurii.com'

EMAIL_HOST_PASSWORD = 'your-email account-password'

EMAIL_USE_TLS = True

EMAIL_USE_SSL = False

```

Each email provider requires a different `EMAIL_HOST` value. 

For example, if you have a Gmail account and use their SMTP server, `EMAIL_HOST = ‘smtp.gmail.com’`.

Furthermore, verify other important values that are related to your mail server. At some point, you must choose whether to encrypt the mail and protect your user account by setting the variable `EMAIL_USE_TLS` or `EMAIL_USE_SSL`.

It's simple to determine if your email provider specifies which option to use, otherwise you can experiment with different combinations using True and False operators. Only one of these options can be set to True.

Django is informed what custom or predefined email backend to use via the `EMAIL_BACKEND` setting.

`EMAIL_HOST`. It's also possible to configure this parameter.

What is SMTP and How Will We Use It?

An SMTP server uses the Simple Mail Transfer Protocol to relay and send electronic messages. This protocol specifies the rules for message delivery. (Other protocols govern message reception.)

Every SMTP server has a unique address and a specific port for sending messages, which is usually 587. We'll look at how ports are involved when sending emails with Django later on.

In this post, I will show you how to use Django to send emails.

Creating a Django Project

It's important to keep track of the project dependencies, so we don't mess them up. To make a virtual environment, run the following:

```python

python -m venv .venv

```

<aside>
 *Make sure to check this virtual environments guide for Python if you’re unfamiliar with virtual environments.*

</aside>

 

The above command creates a virtual environment named `.venv`. To activate it, use the following:

```python

source .venv/bin/activate

```

You have to install Django using pip, since it is a third-party package:

```python

pip install django

```

`pip freeze` will tell you what version of Django you have installed.

The [django-admin](https://docs.djangoproject.com/en/dev/ref/contrib/admin/) command line utility can be used to create a Django project:

```python

django-admin startproject EmailProject

```

You can create a Django project with any name you want by using the command above, but with the command, you are creating an `EmailProject` project.

Now, start the project's server:

```python

cd EmailProject

python manage.py runserver

```

Open up the [http://localhost:8000](http://localhost:8000/) address in your browser after running the Django server. You will see an automatically generated page with the latest Django release notes.

Changing Settings

Before sending emails, you must modify the settings file, so let's locate it with the command `tree`:

<aside>

*In order to keep things simple, we use UNIX system commands.*

</aside>

The `tree` command outputs the file structure of a directory. Since we’re not specifying a specific directory path, we’ll receive something like the following if we’re in the project’s root folder:

```python

├── EmailProject

│ ├── asgi.py

│ ├── __init__.py

│ ├── settings.py

│ ├── urls.py

│ └── wsgi.py

└── manage.py

1 directory, 6 files

```

Throughout this tutorial, we will be altering the settings.py file located in the `EmailProject` folder.

All of the project configurations are stored in `settings.py`, and you can set custom variables here. According to the Django documentation, "A settings file is simply a Python module with module-level variables.”

Here are the settings required to send an email using Django. Open the `EmailProject/settings.py` file and copy the following lines to the end of the file:

```python

# EmailProject/settings.py

# Bottom of the file

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_HOST = ''

EMAIL_PORT = 587

EMAIL_USE_TLS = True

EMAIL_HOST_USER = ''

EMAIL_HOST_PASSWORD = ''

```

Let's look at each of the settings in the code snippet above, to better understand how they work.

Email Backend

Django provides multiple backends for sending emails. This setting determines which one we will use.

Email host

You can use this setting to specify your email provider.

Here is a list of the SMTP server IP addresses for three popular mail services:

| Email provider | SMTP server host |

| --- | --- |

| Gmail | smtp.gmail.com |

| Outlook/Hotmail | smtp-mail.outlook.com |

| Yahoo | smtp.mail.yahoo.com |

Email Port

The `EMAIL_PORT` setting must be set to 587 because it is the default port for most SMTP servers.

Email Use TLS

Django will use Transport Layer Security to connect to the SMTP server and send emails if this setting is set to True.

Email Host User

Leave this field blank for now; we will use django-environ to set up all of these credentials later.

Email Host Password

After completing the procedure in this section, you will get the `EMAIL_HOST_PASSWORD` setting, which is the app password for your email account.

Sending Emails via SMTP

Once you've set up everything, you can use the `django.core.mail`. `send_mail` or `send_mass_mail` functions to send messages. 

These functions differ in their connection usage. Each message is associated with a separate connection using `send_mail`. A single connection is used to communicate with the mail server for mass emailing using `send_mass_mail`.

Send Mail Function

Django requires four mandatory parameters to be specified for email delivery: `subject`, `message`, `from_email`, and `recipient_list`.

The following may also be adjusted:

  •  `auth_user`: If `EMAIL_HOST_USER` has not been defined, or if you wish to replace it, this username will be used to authenticate to the SMTP server.
  •  `auth_password`:If `EMAIL_HOST_PASSWORD` is not specified, this password will be used to authenticate to the SMTP server.
  • -`connection`:You can use the email backend without tweaking `EMAIL_BACKEND` to send multipart emails.
  •  `fail_silently`: The `smtplib.SMTPException` class will be raised if this flag is set to `False`, or exceptions will be silently ignored if it is set to True.

It might look like this:

```python

send_mail(

subject = 'That’s your subject'

message = 'That’s your message body'

from_email = ‘from@yurii.com’

recipient_list = ['to@yourfriend.com',]

auth_user = 'Login'

auth_password = 'Password'

fail_silently = False,

)

```

It is also possible to send emails to the recipients specified in `ADMINS` and `MANAGERS` settings using `mail_admins` and `mail_managers`, respectively.

You can specify the `subject`, `message`, `fail_silently`, `connection`, and `html_message` as arguments for them.

The `SERVER_EMAIL` setting defines the `from_email` argument.

Sending Multiple Emails

Creating and closing connections to deliver messages via SMTP is a bit awkward if you need to send multiple transactions. It is better to establish one connection and reuse it for all messages.

You can accomplish this with the `send_messages` method available through the email backend API. Here is an example:

```python

from django.core import mail

connection = mail.get_connection()

connection.open()

email1 = mail.EmailMessage(

'That’s your subject',

'That’s your message body',

'from@yurii.com',

['to@yourfriend1.com'],

connection=connection,

)

email1.send()

email2 = mail.EmailMessage(

'That’s your subject #2',

'That’s your message body #2',

'from@yurii.com',

['to@yourfriend2.com'],

)

email3 = mail.EmailMessage(

'That’s your subject #3',

'That’s your message body #3',

'from@yurii.com',

['to@yourfriend3.com'],

)

```

Here, you can see that emails 2 and 3 were sent using the open connection for email 1. You then closed the connection manually.

Sending HTML Emails

There is also no difficulty sending HTML emails with Django. Here's how to send HTML emails using Django

```python

from django.core.mail import send_mail

from django.http import HttpResponse

res = send_mail("hello yurii", "How are you doing?", "yurii@yurii.com", 

["yurii@gmail.com"], html_message=")

```

An e-mail with multiple parts will be produced by this.

Prior to Django version 1.7, you sent HTML emails using the `django.core.mail.EmailMessage` class by calling `send` on the object.

Let's create a `sendHTMLEmail` view to send an HTML e-mail.

```python

from django.core.mail import EmailMessage

from django.http import HttpResponse

def sendHTMLEmail(request , emailto):

html_content = "<strong>How are you doing?</strong>"

email = EmailMessage("my subject", html_content, "yurii@yurii.com", [emailto])

email.content_subtype = "html"

res = email.send()

return HttpResponse('%s'%res)

```

The parameters are given below: 

- `Subject` − E-mail subject.

- `message` − E-mail body in HTML.

- `from_email` − E-mail from.

- `to` − List of receivers’ e-mail address.

- `bcc` − List of “Bcc” receivers’ e-mail addresses.

- `connection` − E-mail backend.

Sending Emails with Attachment

An `EmailMessage` can be attached using the `attach` method.

There is a button to send an e-mail with an attachment in the view.

A view to send an e-mail with an attachment will be:

```python

from django.core.mail import EmailMessage

from django.http import HttpResponse

def sendEmailWithAttach(request, emailto):

html_content = "How are you doing?"

email = EmailMessage("my subject", html_content, "yurii@yurii.com", emailto])

email.content_subtype = "html"




fd = open('manage.py', 'r')

email.attach('manage.py', fd.read(), 'text/plain')




res = email.send()

return HttpResponse('%s'%res)

```

Details are arguments to be attached:

  • `filename` − The file name to attach.
  • `content` − The file to attach contains the desired content.
  •  `mimetype` − The file's mime type is indicated by the attachment's mime type.

Using Google Gmail SMTP

Setting up Gmail's SMTP server is not as difficult as setting up others, and it's free.

Configuring Google SMTP provider

You require less secure application access to send emails using your Google Gmail account.

Setting up an App Password

While using a secure app with a Google account that has 2-step Verification turned on, you cannot use a secure app. Instead, you must generate an app password using this link.

Sending Emails with Gmail SMTP

In order to finish sending emails using the Google Gmail SMTP provider, you must update and add some additional settings to your project with your Google Gmail account information.

```python

DEFAULT_FROM_EMAIL = '<paste your gmail account here>'

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_HOST = 'smtp.gmail.com'

EMAIL_HOST_USER = '<paste your gmail account here>'

EMAIL_HOST_PASSWORD = '<paste Google password or app password here>'

EMAIL_PORT = 587

EMAIL_USE_TLS = True

```

It's important to keep certain information confidential, so environment variables should be used. A great `django-environ` alternative is a good choice for this.

Now we are ready to send the emails. Go ahead and send some emails using the app.

Email Sending in Django

Prior to sending email messages, you must first test your mail server. With Python, you may accomplish this with a single command:

`python -m smtpd -n -c DebuggingServer localhost:1025`

In order to send emails to your local SMTP server, you can use the `DebuggingServer` feature. You can see the content of your message in the shell window, but the feature won’t actually send the email. That’s an option you can use offhand.

Testing Django Email Sending

With Django’s `core.mail.outbox`, TestCase checks several aspects of email delivery. As you recollect, outbox stores messages in the local memory cache — `django.core.mail.outbox`. Therefore, this test runner doesn’t actually send emails. Once you’ve selected this email backend, you can proceed.

`EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend’`

The following unit test sample can be used to test your email-sending capability.

```python

from django.core import mail

from django.test import TestCase

class EmailTest(TestCase):

def test_send_email(self):

mail.send_mail(

'That’s your subject', 'That’s your message body',

'from@yurii.com', ['to@yourfriend.com'],

fail_silently=False,

)

self.assertEqual(len(mail.outbox), 1)

self.assertEqual(mail.outbox[0].subject, 'That’s your subject')

self.assertEqual(mail.outbox[0].body, 'That’s your message body')

```

This test will verify the adequacy of both the subject and message of your email in addition to the successful sending of the email.

Testing with Mailtrap Services

Mailtrap is an excellent choice for testing. Firstly, it allows you to perform a wide variety of checks on the email content and SMTP server, among other things. It is also very easy to use.

All you have to do is copy the SMTP credentials from your demo inbox and modify your settings.py. Alternatively, you may just copy/paste these four lines from the Integrations section by selecting Django in the pop-up menu.

```python

EMAIL_HOST = 'smtp.mailtrap.io'

EMAIL_HOST_USER = '********'

EMAIL_HOST_PASSWORD = '*******'

EMAIL_PORT = '2525'

```

Send me your email with an attachment after that, and I'll see how it goes.

```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@yurii.com>'

to = 'to@yourfriend.com'

mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)

message.attach('Attachment.pdf', file_to_be_sent, 'file/pdf')

```

Conclusion

Django is a powerful Python web framework that allows you to build applications faster and reach your goals in a short amount of time. With the help of Django, you can implement an email-building feature in the simplest and most efficient way possible. 

I showed you how to configure your Django project to send emails and how to send emails through the Django development server. In particular, we learned:

  • How to set up sending emails in Django with the help of proper and practical examples.
  • How to send mails from a local system and how to configure an SMTP.
  • How to configure Google Gmail SMTP provider and send emails with Google Gmail SMTP provider.
  • And most importantly, we learned how to check and test the sending of an e-mail.

But I encourage you to examine other tools and implement them in your initiatives.

Good luck!

Bonus Django Related Course

Python Django - The Practical Guide

 

By Yurii Shumak

I'm a technical content writer and Mailtrap contributor passionate about helping companies and products bridge the gap between people, processes, and technology. In other words: the trenches are where I spend most of my time.

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

I accept the Terms and Conditions.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

Learn More

Please login to leave comments