Email confirmation process using Django and Sendgrid

GSoC’20 | Coding Phase | Week 3

Bismita Guha
AnitaB.org Open Source
2 min readJun 22, 2020

--

Email confirmation is a necessary part of proper authentication. It’s like a complete process for confirming user details. I have implemented this in my GSoC project which was my major work in the 3rd week of my Coding Phase.

I have used the Sendgrid email service for easy implementation with Django REST Framework. Sendgrid is a cloud-based email service that provides reliable transactional email delivery, scalability, and real-time analytics along with easy integration. The first step would be sending the email and the second step would be generating encoded tokens for email activation for specific users.

Sending emails

A few changes to the settings.py and the views will easily send emails. First, we need to generate an API key for the app from this URL. We need to add this API key to the .env file and then import this in settings.py for further use.

We need to install python-dotenv for loading the environment variable. Next, make the following changes to settings.py:

Next, we need to add a few lines to the views on the execution of which we want to send the email. Go to the specific function on the execution of which you want to send the email.

For testing, we can manipulate the settings.py to receive the output to the terminal instead of sending the email.

SENDGRID_SANDBOX_MODE_IN_DEBUG = False
SENDGRID_ECHO_TO_STDOUT = True

Next, we need to generate the token for email activation.

Token Generation

We need to generate a unique token for every user registering, to frame the URL for email activation. Write a token.py file for generating a unique token. You can obviously use other methods.

In the URL generation part, these tokens need to be added:

token1 = urlsafe_base64_encode(force_bytes(user.pk))
token2 = account_activation_token.make_token(user)
# URL with token
http://your_domain_here/token1/token2

You need to send this URL in the email being sent, with any other customized message you are willing to add. This token needs to be appended to the URL for activation. In the activate function we need to activate the user and return a response according to the validation of the URL, so that when the user clicks the URL in the email they received, they are redirected to a page that confirms their action and allows further login in the application.

views.py

So, finally, this process isn’t as complicated as it looks. You can customize your email and also the email confirmation page, as per your design and creativity.

Have fun!

Well done, you successfully integrated email confirmation in your application.

References

--

--