Django/Email notification/

How to send an Email notification with Gmail?

Published on

How to send an Email notification with Gmail?
Simple Mail Transfer Protocol (SMTP) is a quick and easy way to send emails from one server to another. Python has EmailMessage class which can be used to build email messages.  In this tutorial, how to send an email notification with Django. 

Introduction :

Django (Django rest Framework):

Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django. To know more about relative links click here

SMTP :

SMTP (or the Simple Mail Transfer Protocol) is a set of rules for determining how emails are transferred from senders to recipients. SMTP servers use this protocol to send and relay outgoing emails. (Note that other protocols govern how emails are received.)

An SMTP server always has a unique address, and a specific port for sending messages, which in most cases is 587. We’ll see how the port is relevant while sending emails with Django. To know more about relative links click here

Flow Diagram:


Flow diagram.

Prerequisites:

  • Python

  • Django

Steps:

Step 1: Set Up an App Password in Gmail



google accounts



Screenshot1

 

  • Once you’re in, click on the select app, where you’ll choose a custom name for that app password — such as “Django Send Email” — then click on GENERATE.

 

Screenshot2

 

Screenshot4

Step 2: Install Python

Python3.6 or above is needed in order to create a Django project, therefore please install python and proceed to the next step.

Step 3: Install Django:

Install the Django framework using the following command.

1pip install django

Step 4: Create a Django Project:

Create a Django project using the below command.

1django-admin startproject backend

Step 5: Create a Django App:

After creating the Django project, then create the Django app

1python manage.py startapp accounts

A sample screenshot of Django project files is shown below.


Screenshot6

Step 6: Configure the Django project to establish a connection with SMPT.

  • In backend/settings.py, add the following piece of code:

1EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' 2EMAIL_HOST = 'smtp.gmail.com' 3EMAIL_HOST_USER = 'gmail account email id' 4EMAIL_HOST_PASSWORD = '#############' # You two verification password 5EMAIL_USE_TLS = True 6EMAIL_PORT = 587

The sample code for the backend/settings.py file can be found in the following Github URL.

  • Update the accounts/views.py file with the following code.

1from django.core.mail.message import EmailMultiAlternatives 2from django.conf import settings 3from django.template.loader import render_to_string 4from django.shortcuts import redirect, render 5 6def send_email(request): 7 if request.method=="POST": 8 email_id = request.POST.get('email_id') 9 response_data = "email send to "+email_id 10 email_name = email_id.split('@') 11 12 email_template = render_to_string( 13 'email.html', {"username": email_name[0]}) 14 email_obj = EmailMultiAlternatives( 15 "Email Notification Example", 16 "Email Notification Example", 17 settings.EMAIL_HOST_USER, 18 [email_id], 19 ) 20 email_obj.attach_alternative(email_template, 'text/html') 21 email_obj.send() 22 context = {"data":response_data} 23 return render(request,"index.html",context) 24 else: 25 context = {"data":"response_data"} 26 return render(request,"index.html")

The sample code for the accounts/views.py file can be found in the following Github URL.

  • Add the accounts/urls.py file with the following content.

1from django.urls import path 2from .views import* 3 4urlpatterns = [ 5 path("send-email/",send_email) 6]

The sample code for the accounts/urls.py file can be found in the following Github URL.

 

Create the templates in your project directory.

  • In your project, go to your /templates directory and create a file called index.html



Screenshot7

  • In templates/index.html, add the following piece of code:

1<!DOCTYPE html> 2<html lang="en"> 3 4<head> 5 <meta charset="UTF-8"> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 7 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 <script src="https://cdn.tailwindcss.com"></script> 9 10 <title>Email Notification</title> 11</head> 12 13<body> 14 <div class="w-[1100px] mx-auto py-10"> 15 <form action="." method="post"> 16 {% csrf_token %} 17 {% if data %} 18 <h1 class="w-fit bg-green-300 py-1 px-7 rounded-xl text-center mx-auto mb-10 ">{{data}}</h1> 19 {% endif %} 20 <div class="w-80 mx-auto space-y-3"> 21 <label for="email" class="block text-sm font-medium text-gray-700 ml-1">Email Id</label> 22 <div class="mt-1"></div> 23 24 <input type="email" name="email_id" id="email" 25 class="block w-full rounded-md border text-center h-10 border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" 26 placeholder="you@example.com" aria-describedby="email-description" required> 27 <input type="submit" value="submit" 28 class="w-fit px-3 mx-auto border bg-blue-400 rounded-md border-gray-400"> 29 </div> 30 </form> 31 </div> 32 </div> 33</body> 34</html>

Sample code for the templates/index.html the file can be found in the following Github URL.

  • In your project, go to your /templates directory and create a file called email.html



Screenshot9

  • In templates/email.html, add the following piece of code:

    1<!DOCTYPE html> 2<html lang="en"> 3 4<head> 5 <meta charset="UTF-8"> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 7 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 <title>Email Notification</title> 9</head> 10<body> 11 <small>Hello, {{username}}</small> 12 13 <p>Email Notification</p> 14 15 <em>Thank you</em><br /> 16 <em>Team <b><a href="https://episyche.com/">Episyche Technologies</a></b></em> 17</body> 18</html>


The sample code for the templates/email.html file can be found in the following Github URL.

A Sample GitHub repo, with all the required configurations, is given below.

Result:

After finishing all the steps mentioned above, please go to the web browser, and try to access the next.js application (i.e http://127.0.0.1:8000/send-email). An example output screenshot is given below.


Results1


Results2

Comments