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 EmailMessageclass Mail:@staticmethoddef 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 importsfrom django.contrib.sites.shortcuts import get_current_sitefrom django.contrib.auth import get_user_modelfrom django.urls import reversefrom .utils import Mailfrom rest_framework_simplejwt.tokens import RefreshTokenUser = get_user_model()# Create your views here.class RegistrationView(generics.GenericAPIView):serializer_class = RegistrationSerializerdef post(self, request):user = request.dataserializer = self.serializer_class(data=user)serializer.is_valid(raise_exception=True)serializer.save()user_data = serializer.data#### Sending emailuser = User.objects.get(email=user_data['email'])token = RefreshToken.for_user(user).access_tokencurrent_site_domain = get_current_site(request).domainrelativeLink = 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_linkdata = {'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’saccess
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 calledverify-email
.