Have you ever ever struggled with organising electronic mail integration in your Django tasks? Whether or not it’s configuring SMTP settings, dealing with safety considerations, or automating contact types, electronic mail performance is essential for consumer engagement and belief.
On this tutorial, we’ll stroll via the best way to ship emails utilizing Django with sensible, step-by-step directions. We’ll cowl the best way to configure Django SMTP connections, the best way to arrange an password in your electronic mail supplier, and the best way to ship emails via the Django shell. We’ll additionally take a look at the best way to arrange a contact type in your Django app, which can enable your prospects to contact you.
Key Takeaways
- Configure SMTP Settings: Arrange Django electronic mail ship by configuring the settings.py file with the suitable electronic mail backend, host, port, and safety settings (e.g., TLS).
- Safe Credentials with Django Environ: Use Django Environ to handle delicate credentials like EMAIL_HOST_USER and EMAIL_HOST_PASSWORD securely through atmosphere variables, stopping hardcoding of credentials within the supply code.
- Generate App-Particular Passwords: When utilizing Gmail, allow 2-Step Verification and create an App Password to securely authenticate Django mail sending as an alternative of relying in your main password.
- Ship Emails with send_mail: Use Django’s built-in send_mail operate to ship emails with Django from the Django shell, views, or reusable helper features, using settings for streamlined configuration.
- Implement Automated Contact Types: Construct an automatic contact type utilizing Django Types and combine email-sending performance for seamless dealing with of consumer inquiries.
- Check E mail Performance: Confirm email-sending logic with unit exams and use instruments like MailHog or Console E mail Backend for protected growth testing.
- Comply with Greatest Practices: Guarantee safe and environment friendly electronic mail supply through the use of TLS encryption, correct authentication, and modular electronic mail features for reusability.
Most net functions use electronic mail to handle essential operations, resembling resetting passwords, account activation, receiving buyer suggestions, sending newsletters, and advertising campaigns. Whereas Gmail works for testing or small tasks, manufacturing web sites ought to use devoted electronic mail providers resembling AWS SES, SendGrid, or Mailgun.
Nevertheless, in the event you examine the price and the hassle of utilizing a devoted electronic mail service, sending emails together with your private electronic mail may be extra affordable for small or testing tasks. So we’ll take that method right here to maintain issues easy.
Notice: It’s not a good suggestion to make use of your private electronic mail service in your manufacturing web site. You may be taught extra about Gmail sending restrictions, or seek advice from the restrictions of your electronic mail supplier.
Notice: the total code for this tutorial is obtainable on GitHub.
Understanding the SMTP Server and Easy Mail Switch Protocol
SMTP (or the Easy Mail Switch Protocol) is a algorithm for figuring out how emails are transferred from senders to recipients. SMTP servers use this protocol to ship and relay outgoing emails. (Notice that different protocols govern how emails are acquired.)
An SMTP server all the time has a novel handle and a particular port for sending messages, which normally is 587. We’ll see how the port is related in Django electronic mail ship.
For this instance, we’ll use Gmail’s SMTP server, the place:
Now, let’s see how we are able to ship electronic mail with Django.
Making a Django Undertaking
Each Django venture ought to have a digital atmosphere, as we don’t wish to mess up the venture dependencies. To create one, run the next:
Notice: in the event you’re unfamiliar with digital environments, be certain that to examine our Python digital environments information.
The command above creates a digital atmosphere with the identify .venv. To activate this digital atmosphere, you should utilize the next:
.venvScriptsactivate
.venvScriptsActivate.ps1
supply .venv/bin/activate
Since Django is a third-party bundle, it’s a must to set up it with pip:
This may set up the most recent model of Django, which you’ll be able to examine with pip freeze.
To create a Django venture, you name the command line utility django-admin:
django-admin startproject EmailProject
With the command above, you’re making a Django venture with the identify EmailProject, however you’ll be able to create the venture with no matter identify you need. Now, enter to the venture listing and run the server:
cd EmailProject
python handle.py runserver

After working the Django server, go to http://localhost:8000 in your browser. You’ll see an auto-generated web page with the most recent Django launch notes.

Configuring Django E mail Backend for SMTP
The e-mail backend is the mechanism to ship emails with Django. By default, Django makes use of django.core.mail.backends.smtp.EmailBackend, which permits it to connect with an SMTP server and ship emails. Relying on the atmosphere (growth or manufacturing), you’ll be able to select a distinct electronic mail backend to fit your wants.
You’ll want to change the settings file earlier than sending emails, so let’s find that file with the under command:
Notice: for simplicity’s sake, we’ll be utilizing solely UNIX (macOS or Linux) system instructions.
The tree command outputs the file construction of a listing. On this case, since we’re not giving it a particular listing path, we’ll get one thing just like the next if we’re within the root folder of the venture:
├── EmailProject
│ ├── asgi.py
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── handle.py
1 listing, 6 information
The file we’ll be consistently modifying via this tutorial is the settings.py contained in the EmailProject folder. It holds all of the venture configuration you’ll want, and means that you can set customized variables. Because the Django docs say, “A settings file is only a Python module with module-level variables”.
Let’s take a look at the settings required for sending an electronic mail with Django. Open the EmailProject/settings.py file and paste the next settings on the backside 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 break down the code above by analyzing every considered one of these settings.
E mail Backend
The EMAIL_BACKEND setting declares the backend our Django venture will use to attach with the SMTP server.
This variable is pointing to the smtp.EmailBackend class that receives all of the parameters wanted to ship an electronic mail. I strongly counsel you check out the category constructor straight on the Django supply code. You’ll be shocked by how readable this code is.
Notice: though this class is the default EMAIL_BACKEND, it’s thought of a very good apply to be specific within the Django settings.
All the opposite electronic mail settings will likely be based mostly on the constructor of this EmailBackend class.
E mail host
The EMAIL_HOST setting refers back to the SMTP server area you’ll be utilizing. This is dependent upon your electronic mail supplier. Under is a desk with the SMTP server host corresponding to a few widespread suppliers:
| E mail supplier | SMTP server host |
|---|---|
| Gmail | smtp.gmail.com |
| Outlook/Hotmail | smtp-mail.outlook.com |
| Yahoo | smtp.mail.yahoo.com |
We’re leaving this setting clean for now since we’ll use a .env file later to keep away from hard-coded delicate keys or per-site configurations. You must by no means set credentials straight into the code. We’ll be utilizing Django Environ to resolve this downside.
E mail Port
The EMAIL_PORT setting should be set to 587 as a result of it’s the default port for many SMTP servers. This stays true for private electronic mail suppliers. This port is used together with TLS encryption to make sure the safety of electronic mail sending.
E mail Use TLS
Transport Layer Safety (TLS) is a safety protocol used throughout the Internet to encrypt the communication between net apps (Django) and servers (SMTP server).
Initially, we set the EMAIL_USE_TLS variable to True. This implies Django will use Transport Layer Safety to connect with the SMTP server and ship emails. (It’s necessary for private electronic mail suppliers.)
E mail Host Person
The EMAIL_HOST_USER setting is your private electronic mail handle. Go away it clean for now, since we’ll use django-environ to arrange all of those credentials.
E mail Host Password
The EMAIL_HOST_PASSWORD setting is the app password you’ll get out of your electronic mail account — the method we’ll be doing proper after this part. Identical story: depart this setting clean, as we’ll use environmental variables later.
For different suppliers, you’ll be able to modify the settings accordingly. For instance:
Outlook Configuration:
EMAIL_HOST = 'smtp-mail.outlook.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'your-email@outlook.com'
EMAIL_HOST_PASSWORD = 'your-app-password'
Yahoo Configuration:
EMAIL_HOST = 'smtp.mail.yahoo.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'your-email@yahoo.com'
EMAIL_HOST_PASSWORD = 'your-app-password'
Setting Up Gmail SMTP Server with App Password
Since “Much less Safe Apps” is deprecated by Google, the right and safe approach to connect with Gmail account for sending emails is to make use of App Passwords. App Passwords can be found provided that you allow 2-Step Verification in your Google account.
Why Use App Passwords?
- Safe Various: As an alternative of sharing your main password, App Passwords present restricted entry for particular functions.
- Works with SMTP: App Passwords adjust to Gmail’s safety necessities for SMTP entry.
- Obligatory for 2-Step Verification: As soon as 2-Step Verification is enabled, App Passwords are the one strategy to enable exterior apps to attach.
Step 1: Allow 2-Step Verification
- Go to your Google Account: https://myaccount.google.com/.
- Navigate to Safety within the left-hand menu.
- Scroll to the “The way you sign up to Google” part.
- Click on on “2-Step Verification” and observe the on-screen directions:
- Use your telephone quantity or an authenticator app to arrange 2-Step Verification.
- Confirm your setup with the code despatched to your system.

Step 2: Generate an App Password
- As soon as 2-Step Verification is enabled, search “App Passwords” within the search bar.
- There, enter the identify for the App password and click on Create.

- Then, it’ll give an pop up modal with a 16-character App Password. Be certain to reserve it someplace since it’ll solely be proven as soon as.

If you happen to’re utilizing different electronic mail suppliers, be certain that to learn the next guides:
Utilizing Django Environ to Safe E mail Backend Credentials
Even in the event you’re simply sending emails in growth, you shouldn’t write passwords straight into the supply code. This turns into much more essential when utilizing a model management system together with GitHub to host your venture. You don’t need folks to entry your information.
Let’s see how we are able to forestall this through the use of Django-environ.
Create a .env file contained in the EmailProject listing (the place the settings.py file is situated) with the command under:
cd EmailProject/
ls
settings.py
contact .env
Now, open that .env file and enter the next key–worth pairs:
EMAIL_HOST=smtp.gmail.com
EMAIL_HOST_USER=YourEmail@handle
EMAIL_HOST_PASSWORD=YourAppPassword
RECIPIENT_ADDRESS=TheRecieverOfTheMails
Breaking down the contents of this file:
- EMAIL_HOST: Your electronic mail supplier’s SMTP server handle. See the e-mail host desk above for fast steerage. On this case, I’m utilizing smtp.gmail.com, the Gmail SMTP handle.
- EMAIL_HOST_USER: Your electronic mail handle.
- EMAIL_HOST_PASSWORD: The app password you simply generated. Keep in mind it doesn’t embody any areas.
- RECIPIENT_ADDRESS: The e-mail handle by which you’ll obtain the messages. This can be a customized setting that we’ll create later to ship all of the emails to the identical recipient.
To make use of those environmental variables, we’ll want to put in Django-environ:
pip set up django-environ
Notice: be certain that your digital atmosphere is activated.
Now, open the settings.py situated within the EmailProject listing and use the code under:
import environ
env = environ.Env()
environ.Env.read_env()
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = env('EMAIL_HOST')
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = env('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD')
RECIPIENT_ADDRESS = env('RECIPIENT_ADDRESS')
First, we’re importing the environ bundle on the high of the settings file. Keep in mind that all imports must be at first. Then we create an env variable which can comprise all the important thing–worth pairs out there on the .env.
The env(‘KEY’) assertion means we’re wanting up the worth of that key. Earlier than continuing, ensure you have arrange your .env file. In any other case, if some environmental variable isn’t set, you’ll get a Django ImproperlyConfigured error.
Notice: RECIPIENT_ADDRESS is a customized setting that we’ll use to ship emails to an handle we are able to entry.
Don’t neglect to incorporate the .env file in your .gitignore in the event you’re utilizing Git and GitHub. You are able to do this simply by opening it and including the next line:
1. Sending Emails with the Django Shell
Lastly, we get to the juicy a part of the article! It’s time to ship your first electronic mail to Django.
Open up a terminal, activate the digital atmosphere, and run:
This may create a shell with all of the Django settings already configured for us. Inside that brand-new shell, paste the next code:
>>> from django.core.mail import send_mail
>>> from django.conf import settings
>>> send_mail(
... topic='A cool topic',
... message='A surprising message',
... from_email=settings.EMAIL_HOST_USER,
... recipient_list=[settings.RECIPIENT_ADDRESS])
1
We will additionally make a one-liner with out specifying the arguments:
>>> send_mail('A cool topic', 'A surprising message', settings.EMAIL_HOST_USER, [settings.RECIPIENT_ADDRESS])
1
Let’s break down the code above:
- We import the Django send_mail operate.
- Then we import the settings object, which accommodates all of the world settings and the per-site settings (these contained in the settings.py file).
- Lastly, we move all of the wanted arguments to the send_mail operate. This operate returns the variety of emails despatched, on this case, 1.
Notice how we use the settings object to get the from_email (the e-mail you’re sending emails with) and the recipient_list (the RECIPIENT_ADDRESS customized setting we outlined within the .env).
Now, if I examine my inbox — as I set the RECIPIENT_ADDRESS environmental variable to my electronic mail handle — I’ll get the e-mail message despatched by Django.

Asynchronous E mail Sending
In Django 4.x, asynchronous electronic mail sending is supported to enhance efficiency. That is helpful for high-traffic web sites or when sending bulk emails.
Right here’s how one can ship an electronic mail asynchronously:
import asyncio
from django.core.mail import send_mail
from django.conf import settings
async def send_async_email():
await send_mail(
topic="Async E mail Check",
message="This electronic mail is shipped asynchronously with Django 4.x.",
from_email=settings.EMAIL_HOST_USER,
recipient_list=[settings.RECIPIENT_ADDRESS],
)
asyncio.run(send_async_email())
Asynchronous electronic mail sending is helpful in eventualities like:
- Non-blocking operations the place sending an electronic mail shouldn’t delay consumer requests.
- Sending bulk emails (use a job queue like Celery for production-scale duties).
Notice: Whereas Django helps asynchronous electronic mail, for production-scale bulk emails, use a background job queue like Celery or Django-Q for true non-blocking operations.
On this part, we’ll construct an automatic contact type with Django types and the built-in send_mail operate. We’ll additionally create a customized operate, ship(), contained in the contact type so it’s simpler to implement it within the views.
Let’s begin by creating the contact app. Enter the venture root listing — the place handle.py is situated — and run:
python handle.py startapp contact
Then, set up it in your INSTALLED_APPS variable contained in the EmailProject/settings.py file:
INSTALLED_APPS = [
'django.contrib.admin',
...
'contact',
]
Earlier than advancing with the contact app, let’s configure the urlpatterns inside the EmailProject/urls.py file. To do that, import the django.urls.embody operate and embody the contact URLs within the general venture. Don’t fear; we’ll configure the contact URLs later:
from django.contrib import admin
from django.urls import path, embody
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('contact.urls'))
]
Contact Kind
Enter the contact app folder and create a types.py file. It’s a very good apply to outline all your types inside a types.py file, but it surely isn’t necessary. That’s why Django doesn’t embody this file by default. You may create the types file with the next instructions:
cd ../contact/
contact types.py
Open the file you simply created and make the next imports:
from django import types
from django.conf import settings
from django.core.mail import send_mail
The Django type module provides us all of the wanted courses and fields to create our contact type. As soon as once more we’re importing the settings object and the send_mail operate to ship the emails.
Our contact type will comprise a number of fields and use two customized strategies: get_info(), which codecs the user-provided data, and ship(), which can ship the e-mail message. Let’s see this applied in code:
from django import types
from .providers import send_contact_email
class ContactForm(types.Kind):
identify = types.CharField(max_length=120)
electronic mail = types.EmailField()
inquiry = types.CharField(max_length=70)
message = types.CharField(widget=types.Textarea)
def get_info(self):
"""
Methodology that returns formatted data
:return: topic, msg
"""
cl_data = tremendous().clear()
identify = cl_data.get('identify').strip()
from_email = cl_data.get('electronic mail')
topic = cl_data.get('inquiry')
msg = f'{identify} with electronic mail {from_email} mentioned:'
msg += f'n"{topic}"nn'
msg += cl_data.get('message')
return topic, msg
def ship(self):
topic, msg = self.get_info()
send_mail(
topic=topic,
message=msg,
from_email=settings.EMAIL_HOST_USER,
recipient_list=[settings.RECIPIENT_ADDRESS]
)
This class is big, so let’s break down what we do in every half. Firstly, we outline 4 fields that will likely be required to ship the e-mail message:
- Title and inquiry are CharFields, which characterize the identify and purpose of the contact message.
- E mail is an EmailField that represents the e-mail handle of the particular person making an attempt to contact you. Notice that the e-mail is not going to be despatched by the consumer’s electronic mail handle however by the e-mail handle you set to ship emails within the Django venture.
- The message is one other CharField, besides we’re utilizing the Textarea widget. Because of this, when displaying the shape, it’ll render a <textarea> tag as an alternative of a easy <enter>.
Heading into the customized strategies, we’re solely utilizing the get_info methodology to format the consumer’s data and return two variables: topic, which is nothing however the inquiry area, and message, which would be the precise electronic mail message despatched by Django.
Alternatively, the ship() methodology solely will get the formatted information from get_info and sends the message with the send_mail operate. Though this part was fairly giant, you’ll see how we simplified the contact views by implementing all of the sending logic to the ContactForm itself.
Contact Views
Open the contact/views.py file and add the next imports:
from django.views.generic import FormView, TemplateView
from .types import ContactForm
from django.urls import reverse_lazy
As you’ll be able to see, we’re going to make use of Django generic views, which saves us a ton of time when making easy duties — for instance, when organising a type with FormView or making a view that solely renders a template with TemplateView.
Additionally, we’re importing the ContactForm that we constructed within the earlier part and the reverse_lazy operate used when working with class-based views. Persevering with with the views, let’s write the ContactView:
class ContactView(FormView):
template_name = 'contact/contact.html'
form_class = ContactForm
success_url = reverse_lazy('contact:success')
def form_valid(self, type):
type.ship()
return tremendous().form_valid(type)
As you’ll be able to see, we’re constructing a easy FormView utilizing the ContactForm we created. We’re additionally organising the template_name and the success_url. We’ll write the HTML template and arrange the URLs later.
The type legitimate methodology allow us to ship the e-mail utilizing the ContactForm.ship() methodology provided that all of the fields of the shape are legitimate. This means that if the consumer enters invalid enter — resembling an unformatted electronic mail handle — the message gained’t be despatched.
The above form_valid methodology implementation could be equal to the next in a function-based view:
if request.methodology == 'POST':
type = ContactForm(request.POST)
if type.is_valid():
type.ship()
return redirect('contact:success')
else:
type = ContactForm())
Ending this part, we’re going to write down a ContactSucessView, which can present a hit message to the consumer. Since we’ve already imported the TemplateView class, we solely must inherit from it and outline the template_name attribute:
class ContactSuccessView(TemplateView):
template_name = 'contact/success.html'
You may take a look at the views.py file on the GitHub repository when you’ve got any considerations.
Contact URLs
It’s time to create the URL patterns of the contact app. Since Django doesn’t give us the urls.py file by default, we’ll must create it with the next command (be certain that to be contained in the contact app folder):
Open that file and arrange the app_name and urlpatterns variables:
from django.urls import path
from .views import ContactView, ContactSuccessView
app_name = 'contact'
urlpatterns = [
path('', ContactView.as_view(), name="contact"),
path('success/', ContactSuccessView.as_view(), name="success"),
]
We use path to incorporate the route and its correspondent view to the URL configuration of the app. After we set the app_name variable to ‘contact’, it means the URL namespacing of the app will appear to be this:
contact:name_of_path
contact:contact
contact:success
Notice: a namespace is what we name URLs dynamically in Django templates and Views.
You may be taught extra concerning the Django URL dispatcher within the official documentation.
Writing templates
Django templates are the popular strategy to show information dynamically, utilizing HTML and particular tags offered by the Django Template Language.
For this particular app, we’ll be utilizing three templates:
- base.html: All the opposite templates will inherit from it. It’ll comprise the HTML skeleton that each one templates should have, in addition to hyperlinks to Bootstrap.
- contact.html: Shows the contact type.
- success.html: Shows a hit message.
Let’s begin by creating the contact’s app template construction (ensure you’re contained in the contact app folder):
mkdir -p templates/contact/
cd templates/contact
contact base.html contact.html success.html
The instructions above create the everyday template construction of a reusable Django app — appname/templates/appname — and the tree template information I discussed earlier than. Right here’s what the app file construction ought to now appear to be:
.
├── admin.py
├── apps.py
├── types.py
├── __init__.py
├── migrations
│ └── __init__.py
├── fashions.py
├── templates
│ └── contact
│ ├── base.html
│ ├── contact.html
│ └── success.html
├── exams.py
├── urls.py
└── views.py
Let’s bounce into the content material of the bottom.html template:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Suitable" content material="IE=edge" />
<meta identify="viewport" content material="width=device-width, initial-scale=1.0" />
<title>Django E mail Ship</title>
<hyperlink href="https://cdn.jsdelivr.internet/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="nameless" />
</head>
<physique>
{% block physique %}
{% endblock %}
<script src="https://cdn.jsdelivr.internet/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="nameless">
</script>
</physique>
</html>
As you’ll be able to see, it’s the straightforward skeleton of an HTML file that features hyperlinks to Bootstrap 5. This enables us to stylize our contact app with out utilizing CSS information. The {% block name-of-block %} tag permits us to arrange a placeholder that “youngster templates” will make the most of. The usage of this tag makes template inheritance a simple job.
Earlier than heading into the types, you’ll want to put in the Django crispy types bundle, which permits us to stylize them simply:
pip set up django-crispy-forms
As soon as once more, crispy_forms is a Django app, and we have to embody it on the INSTALLED_APPS record:
INSTALLED_APPS = [
...
'crispy_forms',
'contact',
]
CRISPY_TEMPLATE_PACK = 'bootstrap4'
We use the template pack of Bootstrap 4, as a result of the Bootstrap type courses are appropriate between the 4th and fifth model (on the time of writing).
Now, let’s work on the contact.html template:
{% extends 'contact/base.html' %}
{% load crispy_forms_tags %}
{% block physique %}
<div class="mx-auto my-4 text-center">
<h1>Contact Us</h1>
</div>
<div class="container">
<type motion="" methodology="publish">
{% csrf_token %}
{ crispy }
<button class="btn btn-success my-3" kind="submit">Ship message</button>
</type>
</div>
{% endblock %}
Notice how we prolonged the bottom template and make use of the block placeholder. That is what makes Django Template Language so environment friendly, because it lets us save a whole lot of HTML copying and pasting.
Speaking concerning the type, we’re utilizing the strategy “publish”, which signifies that our ContactView will course of the information given by the consumer and ship the e-mail if the shape is legitimate. The {% csrf_token %} is necessary in each type due to safety causes. Django’s documentation has a devoted web page on CSRF tokens and the explanations to make use of them when working with types.
We’ll be rendering the shape with the crispy template tag, which is why we loaded the crispy tags with {% load crispy_forms_tags %}.
Lastly, let’s write the success.html template:
{% extends 'contact/base.html' %}
{% block physique %}
<div class="mx-auto my-4 text-center">
<h1 class="fw-bolder text-success">We despatched your message</h1>
<p class="my-5">You may ship one other within the <a href="{% url 'contact:contact' %}">contact web page</a></p>
</div>
{% endblock %}
As you’ll be able to see, it’s a easy success announcement with a hyperlink to the contact type in case the consumer needs to ship one other message.
Let’s run the server once more and go to http://localhost:8000 (ensure you have the .venv activated and also you’re contained in the venture root folder):
python handle.py runserver
The picture under reveals what the ultimate contact type seems like.

And that is a picture of the success message.

And right here’s a picture of the e-mail within the inbox.

Greatest Practices to Comply with
1. Reusable E mail Sending Operate
To make your email-sending logic modular and reusable, you’ll be able to transfer the e-mail sending operate to a helper operate:
from django.core.mail import send_mail
from django.conf import settings
def send_contact_email(topic, message, recipient):
send_mail(
topic=topic,
message=message,
from_email=settings.EMAIL_HOST_USER,
recipient_list=[recipient],
fail_silently=False,
)
Now you can name this operate wherever you must ship emails, together with your contact type.
2. Unit Testing
You need to use django.take a look at to check ship electronic mail Django functionalities.
from django.take a look at import TestCase
from django.core.mail import send_mail
class EmailTest(TestCase):
def test_email_sending(self):
response = send_mail(
topic='Check Topic',
message='Check Message',
from_email='from@instance.com',
recipient_list=['to@example.com'],
)
self.assertEqual(response, 1)
3. Sending Wealthy HTML Emails
HTML emails present higher design and presentation. Use Django’s template engine to create wealthy electronic mail content material:
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.conf import settings
def send_html_email():
topic = 'HTML E mail Instance'
from_email = settings.EMAIL_HOST_USER
recipient = ['recipient@example.com']
html_content = render_to_string('email_template.html', {'key': 'worth'})
msg = EmailMultiAlternatives(topic, physique='', from_email=from_email, to=recipient)
msg.attach_alternative(html_content, "textual content/html")
msg.ship()
4. Integrating Third-Occasion E mail Companies
For production-ready functions, think about using third-party providers resembling SendGrid, Mailgun, or AWS SES. These providers provide superior options like electronic mail analytics, supply monitoring, and spam filtering.
EMAIL_BACKEND = 'sendgrid_backend.SendgridBackend'
SENDGRID_API_KEY = 'your-api-key'
SENDGRID_SANDBOX_MODE_IN_DEBUG = False
5. E mail Verification in Person Registration
Ship electronic mail verification hyperlinks throughout consumer registration to forestall spam accounts.
from django.core.mail import send_mail
from django.utils.http import urlsafe_base64_encode
from django.utils.encoding import force_bytes
from django.template.loader import render_to_string
def send_verification_email(consumer, request):
token = account_activation_token.make_token(consumer)
uid = urlsafe_base64_encode(force_bytes(consumer.pk))
hyperlink = request.build_absolute_uri(f'/activate/{uid}/{token}/')
message = render_to_string('activation_email.html', {'hyperlink': hyperlink})
send_mail('Confirm your electronic mail', message, 'from@instance.com', [user.email])
Wrapping up
Congrats! You’ve discovered the best way to ship emails with Django and the best way to construct a Django contact type as nicely.
There are lots of methods to ship emails with Django. On this tutorial, you’ve made it together with your private electronic mail handle, however I’d such as you to discover different instruments and combine them into your tasks.
On this tutorial, we’ve coated the next:
- Learn how to arrange Django settings to serve emails
- Learn how to use a private electronic mail account to ship emails in a small venture
- Learn how to use .env information to make use of delicate information in a Django venture
- Learn how to construct an automatic contact type
For extra on Django, take a look at “Construct a Photograph-sharing App with Django”.
FAQs on Django Ship E mail with SMTP Server
Can I Ship an E mail from Django?
Sure, Django gives a built-in email-sending framework that makes it easy to ship emails. By configuring the SMTP settings in your settings.py file, you’ll be able to ship emails utilizing the send_mail operate or EmailMessage class.
Learn how to Ship E mail in Django?
To configure Django for sending emails:
- Set the SMTP particulars in your settings.py file:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'your_email@instance.com' EMAIL_HOST_PASSWORD = 'your_app_password' - Use a safe Password as an alternative of your fundamental electronic mail password in the event you’re utilizing Gmail or comparable suppliers.
- For manufacturing, think about using third-party providers like SendGrid, Mailgun, or Amazon SES for higher scalability.
Learn how to Ship Outlook Mail in Django?
To ship Outlook mail in Django, you should utilize Django’s electronic mail sending performance with the SMTP settings for Outlook. In your Django venture’s settings.py file, configure the SMTP settings for Outlook. These settings will allow Django to connect with the Outlook SMTP server to ship emails.
Learn how to Obtain Emails in Django?
In your Django venture’s settings.py, configure your incoming electronic mail server settings. You sometimes want the IMAP (Web Message Entry Protocol) server particulars in your electronic mail supplier, together with authentication credentials. Subsequent, use the imaplib library to connect with your electronic mail server and retrieve emails. You are able to do this in your Django views or customized administration instructions. Upon getting fetched an electronic mail, you’ll be able to course of it, extract data, and carry out any essential actions inside your Django utility. This might contain parsing the e-mail content material, storing related information in your database, or triggering particular actions based mostly on the e-mail’s content material or sender.
How Do I Check E mail Sending in Django With out Sending Actual Emails?
Throughout growth, you should utilize an elective electronic mail backend to check emails with out connecting to an actual SMTP server. For instance: Console E mail Backend: Prints electronic mail messages to the terminal as an alternative of sending them.
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
For extra superior testing, use instruments like MailHog or Mailtrap, which act as faux SMTP servers for capturing and displaying take a look at emails.
How Do I Handle Delicate E mail Credentials Securely?
Use Django Environ to load delicate credentials (like electronic mail host, username, and password) from a .env file:
- Set up Django Environ:
pip set up django-environ - Create a .env file:
EMAIL_HOST=smtp.gmail.com EMAIL_HOST_USER=your_email@instance.com EMAIL_HOST_PASSWORD=your_app_password - Load the .env file in settings.py:
import environ env = environ.Env() environ.Env.read_env() EMAIL_HOST = env('EMAIL_HOST') EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD')


