Integrate Email Service in your Django Application using SendGrid Email API

Saad Ali
4 min readSep 10, 2022

--

In this article, we are going to learn how to integrate email service into our Django application using SendGrid in a few easy steps.

Let's first create a simple Django application that performs basic user authentication. Our task is to send an email to a user after he clears the registration process.

Step 1

Create a new Django project:

django-admin startproject mysite

Recommended Approach: Always create your Django application in a separate virtual environment. Let's say you have two application that uses the same package but of different version. So, If you are using virtual environments it's easy to manage packages with different versions

Step 2

Create a users app:

python manage.py startapp users

Add user model (users/models.py)

from django.contrib.auth.models import AbstractUser
from django.db import models


class User(AbstractUser):

def __str__(self):
return f'{self.first_name} {self.last_name}'

We are using an AbstractUser class from Django auth, that already contains basic user information fields like first_name, last_name, email, or username. If you want any other field you can override this class.

Add user registration serializer in users/serializers.py (create serializers.py file)

class RegisterSerializer(serializers.ModelSerializer):

email = serializers.EmailField(
required=True,
validators=[UniqueValidator(queryset=User.objects.all())]
)
password = serializers.CharField(
write_only=True, required=True, validators=[validate_password]
)
password2 = serializers.CharField(write_only=True, required=True)

class Meta:
model = User
fields = ('username', 'password', 'password2',
'email', 'first_name', 'last_name')
extra_kwargs = {
'first_name': {'required': True},
'last_name': {'required': True}
}

def validate(self, attrs):
if attrs['password'] != attrs['password2']:
raise serializers.ValidationError(
{"password": "Password fields didn't match."})
return attrs

def create(self, validated_data):
user = User.objects.create(
username=validated_data.get('username'),
email=validated_data.get('email'),
first_name=validated_data.get('first_name'),
last_name=validated_data.get('last_name')
)
user.set_password(validated_data.get('password'))
user.save()
return user

Add user views (users/views.py)

from rest_framework import generics
from .serializers import RegisterSerializer

class RegisterUserAPIView(generics.CreateAPIView):
serializer_class = RegisterSerializer

Add user URLs (users.urls.py)

from django.urls import path

from users.views import RegisterUserAPIView

urlpatterns = [
path('signup/', RegisterUserAPIView.as_view(), name="signup"),
]

Step 3

Update mysite/settings.py

AUTH_USER_MODEL = 'users.User'

# Application definition

INSTALLED_APPS = [
"users",
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

Update mysite/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('/', include('users.urls')),
]

Step 4

Make migrations

python manage.py makemigrations 
python manage.py migrate

After running migrations, our registration API is ready. To test an API, start your app first then use Postman

python manage.py runserver
Testing API in Postman

Integrating SenGrid

To use SendGrid, you first need to create your account on SenGrid

Do the following steps to use SenGrid:

1) Single sender verification

SenGrid Dashboard

2) Create an API key for your application by clicking here

3) Install django-sendgrid-v5 package using pip

pip install django-sendgrid-v5

4) Add the following lines in your mysite/settings.py

EMAIL_BACKEND = "sendgrid_backend.SendgridBackend"
SENDGRID_API_KEY = "Add your API key, created in step 2"
SENDGRID_SANDBOX_MODE_IN_DEBUG = False
SENDGRID_ECHO_TO_STDOUT = True

5) Add utils.py file in your users app

from django.core.mail import EmailMessage


def send_email(to, reply_to, template_id, data):
msg = EmailMessage(
to=to,
from_email="your sender email",
reply_to=reply_to,
)
msg.template_id = template_id
msg.dynamic_template_data = data
msg.send()

6) Create your email template in SenGrid and save it’s ID

]

Open your template in Code Editor

Add the following HTML code in your template:

<html>
<head>
<title></title>
</head>
<p>Hi {{ first_name }} {{ last_name }},</p>
<p>Congratulations!! you have completed the registration process</p>
<p>Kind regards,</p>

</body>
</html>

7) Last step, update your users/view.py

from rest_framework import generics, status
from rest_framework.response import Response

from .serializers import RegisterSerializer
from .utils import send_email


class RegisterUserAPIView(generics.CreateAPIView):
serializer_class = RegisterSerializer

def create(self, request, *args, **kwargs):
data = request.data

serializer = self.get_serializer(data=data)
serializer.is_valid(raise_exception=True)
serializer.save()

send_email(
to=[data["email"]],
reply_to=[],
template_id="Your Template ID",
data={
"first_name": data["first_name"],
"last_name": data["last_name"],
},
)

return Response(serializer.data, status=status.HTTP_201_CREATED)

Thats it! now call your API in Postman again, you will get an email like this

Hope you like this article, if you have any confusion in any step feel free to message in the comment box :)

--

--

Saad Ali

Software Engineer. Love to work in Python, Django and Rails