Send User Verification and Welcome Email using Django Signals

In this tutorial, we will learn how to send user verification and welcome emails using Django signals. Signals in Django are a powerful mechanism for allowing decoupled applications to get notified when certain actions occur elsewhere in the codebase. We’ll leverage signals to send verification emails when a new user signs up and a welcome email to greet them upon successful email verification.

For this tutorial we are using our Tutorial on User Registration, Login, Logout API using Django

We have create “accounts” apps, this might be different in your project.

Step 1: Configure Email Settings

Ensure that you have configured your email settings properly in your project’s settings.py file. For example:

# settings.py

# ... other settings ...

# Email Configuration
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = '[email protected]'  # Replace with your email address
EMAIL_HOST_PASSWORD = 'your_email_password'  # Replace with your email password

Please watch bellow video, to send email using Gmail.

Gmail SMTP Email settings for Django Project

Step 2: Creating the Custom User Model

In “accounts/models.py”, define the custom user model:

# accounts/models.py

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

class CustomUser(AbstractUser):
    email = models.EmailField(unique=True)
    otp = models.CharField(max_length=6, null=True, blank=True)  # Add the otp
    email_verified = models.BooleanField(default=False)

    # Add custom fields here, if needed

    def __str__(self):
        return self.username

Update the AUTH_USER_MODEL in “myproject/settings.py”:

AUTH_USER_MODEL = 'accounts.CustomUser'

Step 3: Create Signals for Email Verification and Welcome Email

In the signals.py file inside the users app, create the signals for email verification and welcome email:

# accounts/signals.py

from django.dispatch import receiver
from django.db.models.signals import post_save
from django.core.mail import send_mail
from django.conf import settings
from .models import CustomUser

@receiver(post_save, sender=CustomUser)
def send_email_verification(sender, instance, created, **kwargs):
    if created and not instance.email_verified:
        verification_link = f"http://localhost:8000/verify_email/{instance.pk}/"
        subject = 'Email Verification for Your Account'
        message = f'Please click the link below to verify your email address:\n\n{verification_link}'
        from_email = settings.EMAIL_HOST_USER
        recipient_list = [instance.email]
        send_mail(subject, message, from_email, recipient_list)

@receiver(post_save, sender=CustomUser)
def send_welcome_email(sender, instance, created, **kwargs):
    if created and instance.email_verified:
        subject = 'Welcome to Our Website'
        message = f'Hello {instance.email},\n\nWelcome to our website! Thank you for joining us.'
        from_email = settings.EMAIL_HOST_USER
        recipient_list = [instance.email]
        send_mail(subject, message, from_email, recipient_list)

Step 4: Register the Signals

Import the Signals in “accounts/apps.py”: Open the “apps.py” file in the same app’s directory and add an import statement for the “signals.py” file:

# accounts/apps.py

from django.apps import AppConfig

class AccountsConfig(AppConfig):
    name = 'accounts'

    def ready(self):
        import accounts.signals  # Add this line to import the signals.py

Update the “apps” Setting in “settings.py”: Update the “INSTALLED_APPS” setting in your project’s “settings.py” file to include your app with the updated AppConfig:

# mydrfproject/settings.py

INSTALLED_APPS = [
    # ...
    'accounts.apps.AccountsConfig',  # Update the app's reference
    # ...
]

Step 5: Create the Verification View

Create a view to handle the verification URL in your app’s views.py:

# accounts/views.py

from django.shortcuts import redirect

def verify_email(request, pk):
    user = CustomUser.objects.get(pk=pk)
    if not user.email_verified:
        user.email_verified = True
        user.save()
    return redirect('http://localhost:8000/')  # Replace with your desired redirect URL

Step 6: Include the URLs

In your project’s urls.py, include the URL for email verification:

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

urlpatterns = [
    path('admin/', admin.site.urls),
    # ... other URL patterns ...
    path('verify_email/<int:pk>/', verify_email, name='verify_email'),
]

Conclusion

You’ve now implemented user verification and welcome email functionality using Django signals in your Django project. Whenever a new user signs up, they will receive an email verification link, and once they verify their email, they will receive a welcome email. Django signals help keep your code organized and modular, making it easy to maintain and xtend your project in the future. Happy coding!

Find this tutorial on Github.

Blogs You Might Like to Read!