Django Automated Template Email After User Registration

Learn How to send Html Template mails after user registration. This tutorial will explain how to config “from mail” and how to use an HTML template. As mail content(body). You will also learn how to make user registration in Django.

Configuring the email in Settings.py Django

For Outlook(Microsoft Mail)
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.outlook.com' #outlook mail
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'your_email_password'
For Google(Gmail Mail)
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com' # gmail
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'your_email_password'

Creating User Registration in View.py

Imports
from django.shortcuts import redirect, render
from django.contrib import messages
from django.contrib.auth.models import auth, User
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
from django.conf import settings
Register View
def register(request):
    if request.method == 'POST':
        email = request.POST['email']
        username = request.POST['username']
        password = request.POST['password']

        if User.objects.filter(username=username).exists():
            messages.info(request, 'Huff ,Username already exist')
            return redirect("register")
        elif User.objects.filter(email=email).exists():
            messages.info(request, 'Come On, Email was already Taken !')
            return redirect("register")
        else:
            user = User.objects.create_user(
                username=username, password=password, email=email)
            mydict = {'username': username}
            user.save()
            html_template = 'register_email.html'
            html_message = render_to_string(html_template, context=mydict)
            subject = 'Welcome to Service-Verse'
            email_from = settings.EMAIL_HOST_USER
            recipient_list = [email]
            message = EmailMessage(subject, html_message,
                                   email_from, recipient_list)
            message.content_subtype = 'html'
            message.send()
            return redirect("success")
    else:
        return render(request, 'register.html')
Explanation:

This view will allow users to create a user account on the Django web application. When the user enters a mail or username that already exists in the database it will not save or create a user in such case it will raise some error message (validation). Hence user must give valid credentials to create an account. After successful account creation, the user will receive a welcome mail in HTML template style.

Html for User Registration Form

<form action="{% url 'register'  %}" method="POST">
        {% csrf_token %}
        <label for="">Email:</label>
        <br>
        <input type="email" name="email">
        <br>
        <label for="">Username:</label>
        <br>
        <input type="text" name="username">
        <br>
        <label for="">Password:</label>
        <br>
        <input type="password" name="password">
        <br>
        <br>
        <button type="submit">Submit</button>
    </form>
    <div class="">
        {% for message in messages %}
        <span> {{message}}</span>
        {% endfor %}
    </div>
Explanation :

The above html code will allow the users will fill the credentials to create an user account. And it will show the validation errors under the form.

register_email.html

Download Ready Made Templates from ClickHere . Edit the Html Templates with your personal choices.

Explanation :

The above template will be used as the body context into your mail for each user who registered successfully.

Note: The template should have dynamic data by using the jinja format code in the template html code.

Configuring the Urls.py

from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.register, name="register"),
    path('success', views.success, name="success")
]
Explanation :

This urls will let the user to access the register form html page as home page.

Note: The success HTML page is optional. It will be redirected when the user had created an account successfully after entering the valid credentials. I will display a successful message as a separate page.