- Published: January 9, 2019
Step by step guide to provide your Django app with Email capabilities.
Typically used for account activation and notifications.
This guide uses one of the most popular solutions, SendGrid, which provides a considerably free amount of emails for free each month (100 per month at the time of writing this article).
Using Sendgrid with Django
Email service can be added to Django following two strategies:
- Using SendGrid’s Web API
- Using SMTP as the transport mechanism or
In this tutorial we are going to use the first method, with a Web API. 1
To use the Web API we will rely on the the django-sendgrid-v5 package,
This package implements an email backend for Django that relies on *SendGrid*'s REST API for message delivery.
Log in to Sendgrid at https://app.sendgrid.com/login
Get API keys
And Create an API key for the app at https://app.sendgrid.com/settings/api_keys
We will create an API key just for sending emails, so in Name
Then choose Restricted Access, enable Mail Send and hit the Create button.
A new API Key will be generated, copy and set the
Using pip we install django-sendgrid-v5: pip install django-sendgrid-v5
And then tell Django to use it.
Configure Keys in Django
import os EMAIL_BACKEND = "sendgrid_backend.SendgridBackend" SENDGRID_API_KEY = os.environ.get("SENDGRID_API_KEY")
There are also optional settings to deliver emails in debug mode or to send them to standard output:
# Toggle sandbox mode (when running in DEBUG mode) SENDGRID_SANDBOX_MODE_IN_DEBUG=True # echo to stdout or any other file-like object that is passed to the backend via the stream kwarg. SENDGRID_ECHO_TO_STDOUT=True
Testing it works
To test that everything works fine we will send an email.
First turn off SendGrid’s sandbox at
Open Django shell python manage.py shell and send the
from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'firstname.lastname@example.org', ['email@example.com'], fail_silently=False, )
If everything goes fine reactivate sandbox mode and we are ready to focus in coding again.
Finally do Domain Authentication at https://app.sendgrid.com/settings/sender_auth to improve deliverability by proving to inbox providers that you own the domain you’re sending from.