Send Email in Django App with SendGrid

Sandeep Chauhan
2 min readFeb 28, 2020

Many times we have to send an email for activation, invitation, and other purposes. Sendgrid is an email provider which have great support of Twillio Developers. sendgrid-python is a library backed by Twillio Sendgrid. In this article, we will learn how to send an email with the use of SendGrid in the Django application.

Create an account here and also create api-keys for your app in return you’ll get a key “SENDGRID_API_KEY”, copy and store it somewhere as an environment variable(I prefer to store it in .env file) and get it in settings.py like:

SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')

There are two approaches to send a mail by SendGrid, one is to use its API(sendgrid-python) and the second one is to use the SMTP server. So, In the SMTP approach, you have to provide some values/details in settings.py.

EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = SENDGRID_API_KEY
EMAIL_PORT = 587
EMAIL_USE_TLS = True

Then you are all set to send an email, now you have to add below code in your app’s views.py and it’ll send an email to “to@example.com”

from django.core.mail import send_mail
send_mail('Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False)

An API approach is much simpler than the previous one, no need to set any value/variable in settings.py except SENDGRID_API_KEY.

Install the sendgrid-python:

pip install sendgrid-python

Use the below code to send an email, in views.py

import os
from sendgrid import SendGridAPIClient
from django.conf import settings
from sendgrid.helpers.mail import Mail
message = Mail(
from_email='from@example.com',
to_emails='to@example.com',
subject='Sending with Twilio sendgrid-python library',
html_content='<strong>It is easy to send mail with Python and SendGrid</strong>')
try:
sg = SendGridAPIClient(settings.SENDGRID_API_KEY)
response = sg.send(message)
print(response.status_code)
except Exception as e:
print(e.message)

You may edit “from_mail or from@example.com” to your mail-id that you have used to create a SendGrid account and replace “to@example” with the desired email(where you have to send).

Great! now you have a good idea to send an email via SendGrid with Python. Thanks for the read. Follow me on twitter for updates about upcoming posts.

--

--