User Account Activation Email

Learn how to verify user emails and activate their accounts using an email.

Sending email

When users get registered, the first thing we need to do is send them verification emails. For this, we create a function for sending emails. In the main directory, we add another file called utils.py. In this file, we add the code below.

Press + to interact
from django.core.mail import EmailMessage
class Mail:
@staticmethod
def send_email(data):
email = EmailMessage(
subject=data['email_subject'],body = data['email_body'], to=[data['to_email']])
email.send()

We have the send_email() method in lines 5–8 in the Mail class above. This method expects its parameter to be a dictionary that contains:

  • The email_subject for the subject of the email.
  • The email_body for the body of the email.
  • The to_email for the recipient of the email.

With that, it then uses the EmailMessage object to compose and finally send the email.

The next thing to do is to add the functionality of emailing users in the RegistrationView. To do that, we update RegistrationView in views.py, as shown below.

Press + to interact
# new imports
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth import get_user_model
from django.urls import reverse
from .utils import Mail
from rest_framework_simplejwt.tokens import RefreshToken
User = get_user_model()
# Create your views here.
class RegistrationView(generics.GenericAPIView):
serializer_class = RegistrationSerializer
def post(self, request):
user = request.data
serializer = self.serializer_class(data=user)
serializer.is_valid(raise_exception=True)
serializer.save()
user_data = serializer.data
#### Sending email
user = User.objects.get(email=user_data['email'])
token = RefreshToken.for_user(user).access_token
current_site_domain = get_current_site(request).domain
relativeLink = reverse('verify-email')
verification_link = 'https://' + current_site_domain + relativeLink + "?token=" + str(token)
message = ". Use the link below to verify your email.\n If you were not were not expecting any account verification email, please ignore this \n"
email_body = "Hi " + user.email+ message + verification_link
data = {'email_body': email_body,'to_email': user.email,
'email_subject':'Demo Email Verification'}
Mail.send_email(data)
return Response(user_data, status=status.HTTP_201_CREATED)

In the newly added code above:

  • The user variable in line 24 stores the newly created user object.
  • The token variable in line 26 stores the user’s access token.
  • The current_site_domain variable in line 28 stores the domain of our site.
  • The relative_link variable in line 29 stores the actual URL of the endpoint called verify-email.
...