How to create Email sender app in Django?

In this Python Django tutorial, we are going to learn how to create Email sender app in Django. Through this application, we would be able to send emails through a third-party app.

Email sender applications send messages usually over the internet and can be used for a variety of uses like customer service, businesses, and your general use also. There is a variety of email senders with unique features.

Create Email sender application in Django

So firstly we will set up all the requirements which are needed in every basic Python Django project. In this project, we are going to create a fully functional email sender Django application. Through this, we would be able to email and we will also test the functioning of this application.

Step 1: Creating a virtual environment for Django Project

The virtual environment is required to manage python packages for our Python Django project. In this project, we are going to name virtualenv as mail-env. To set up a virtual environment in your projects just follow the commands mentioned below.

> python -m venv mail-env

Now we have created our virtual environment and after this, we need to activate this virtualenv. Follow the commands mentioned below to activate the virtualenv.

> mail-env\Scripts\activate

After this command, virtualenv mail-env is been activated within our Python Django Project.

Step 2: Install Django in our virtual environment

To install Django in our virtual environment we will use pip command.

> pip install django

Step 3: Creating Django Project and App

To create a Python Django Project, follow the command mentioned below.

> django-admin startproject emailproject

Now you can see that we have created a created Django project emailproject. This will automatically generate files and directories in the Project.

In the below image, you can see the directories generated by default.

Django Email Sender in VS code
Directories in Django Email sender Project

In the next step, we need to move to the project directory using the following command.

> cd emailproject

Read: Python Django get admin password

Creating an App

Within our project directory, we will create a Python Django app named demoapp using the below command.

> python manage.py startapp demoapp

With this step, we have successfully created our Python Django application demoapp. Likewise our project our app will also contain some default directories and files.

READ:  AttributeError: 'numpy.ndarray' object has no attribute 'split' in Python [4 ways to handle]

Open the Django Project in the VS Code

Start Visual Studio Code > Under Get Started click on the Open Folder option > Select the emailproject directory. Make sure you are using the folder in which you have created the virtual environment mail-env.

Email Sender Django Application
Email Sender app folder

Read: Difference between app and project in Django

Registering App in Django

To configure our app go to settings.py under the emailproject then go to INSTALLED APPS list and register demoapp below that list.

INSTALLED_APPS = [
    .
    .
    .
    .
    'demoapp',
    
]

Our app is registered now. So, moving to the next step.

Step 4: Creating views

In views, we will render the templates which will create in the next step and we will also render the requests in this views.py file. Now, follow the code mentioned below.

from django.shortcuts import render

# Create your views here.
def sendanemail(request):
    return render(
        request,
        'email.html',
        {
        'title':'send an email'
        }
    )

Step 5: Creating templates

In this step, we are creating app level template. So, inside demoapp folder, we have to create another folder that is templates. Make an HTML file in that template named email.html. Now follow the below code.

<!DOCTYPE html>
<html lang="en">
<head>
    
    <title>{{title}}</title>
</head>
<body>
    <h1>
        SEND AN EMAIL
    </h1>
    <form action ="{% url 'email' %}" method="post">
        <table>
            <tr>
                <td>
                    TO
                </td>
                <td>
                    <input type="email" name="toemail">
                </td>
            </tr>
            <tr>
                <td colspan='2'>
                    <textarea name="content" cols="30" rows="10"></textarea>
                </td>
            </tr>
            <tr>
                <td>
                    <input type="submit" value="Send">
                </td>
                <td>
                    <input type="reset" value="Clear">
                </td>
            </tr>
        </table>
    </form>
    
</body>
</html>

In this HTML form, we have created all the fields which are required for the basic structure of email.

Now we need to add URLs path in our urls.py file. This will render the path which we will see in views.py through the user interface. So, we will add the below code in our urls.py file.

Read: Python Django vs Pyramid

Step 6: URL configuration

In previous steps, we created templates and views. Now we need to create URLs. For that, we need to go inside urls.py file in our project emailproject.

from django.contrib import admin
from django.urls import path
from demoapp.views import sendanemail

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',sendanemail,name="email")
]

We have imported the view function of sendanemail and registration path, In registration, it is going to invoke the function sendanemail.

After this go to email.html and write the below code in the form action.

> "{% url 'email' %}"
Email sender in Python
Email action in Django email sender app

Now with these changes, we are going to make migrations and to make migrations use of the below commands.

> python manage.py makemigrations
> python manage.py migrate

Read How to create a Music Player application using Django

Step 7: Run the development server

Now, we are ready to run this Email sender Python Django application, Now run the following command in the terminal or command prompt.

> python manage.py runserver

Once we run the above command, it will start the lightweight Python Django development server at port 8000 by default. To access the Django application, open this http://127.0.0.1:8000/ URL in the browser. Click the URL link in the terminal and it will redirect you to the server.

Django Mail Sender Project in Python
URL to redirect on Email Sender App server

We will see our Python Django app on the server after clicking on the URL.

Django Email application in Python
Python Django app on the server

Step 8: Creating variables in settings.py

In this step, we will email sending variables in our settings.py file. For these email variables, we need to view smtp settings of Gmail in our browser.

READ:  Write a Python Program to Check Whether a List Contains a Sublist

To create the variables follow the code mentioned below.

# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

#Email Sending Variables
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = "your email adress"
EMAIL_HOST_PASSWORD = "16 digit code generated by gmail"

SMTP settings in Python Django with a short brief:

  • EMAIL_HOST: It refers to the SMTP server. This server is basically a protocol that is required to send emails. For example, if you want to send an email through Gmail then smtp.gmail.com is going to be your SMTP server host.
  • EMAIL_HOST_USER: It is a login credential for the SMTP server. This setting requires your personal email address.
  • EMAIL_HOST_PASSWORD: − Password credential for the SMTP server. In this setting, we will enter a 16-digit code generated by Gmail. In further steps, you will come to know how to generate that code.
  • EMAIL_PORT: The EMAIL_PORT setting must be set  587 because it’s the default port for most SMTP servers. This remains true for personal email providers.
  • EMAIL_USE_TLS or_SSL:  It is a security protocol used across the Web to encrypt the communication between web apps of Django and servers (SMTP server). We will set it to True if the connection is secure.

We require these SMTP settings to send emails through google workspace. For this, we require 16 digit code generated by Gmail.

Make sure you have activated 2-factor authentication in your Gmail account.

Read Python Django import functions

Generate EMAIL_HOST_PASSWORD:

To generate this EMAIL_HOST_PASSWORD go to your google accounts and click manage google accounts after that a new window will open. It will open the settings page.

Go to the security option under the sidebar and then click on App password. A picture is shown below for a better understanding.

Python Django Email App
Password for Email sender Python application

In the App passwords we will see select app and select windows, for reference a picture is shown below.

Email sender app in Django template

When we will click generate it will generate a 16-digit code which we will use in EMAIL_HOST_PASSWORD field in settings.py file.

Email sender with Django shell
Generated code from Gmail in Email sender

Email Backend

The Email_backend  setting declares the backend in our Python Django project which use to connect with the SMTP server. For this, we will again go to settings.py file and add the code mentioned below.

#Email Sending Variables
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = "a.singh9980@gmail.com"
EMAIL_HOST_PASSWORD = "damjxgapxcskmhjz"

EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"

Step 9: Categorize request in Django

When a page is requested, Django creates an Httprequest object that contains metadata about the request. To categorize requests we will go to views.py and create post requests.

from django.shortcuts import render

def sendanemail(request):
    if request.method == "POST":
        to = request.POST.get('toemail')
        content = request.POST.get('content')

Whenever we make a POST request we need to add csrf token. So, we will add csrf token in our email.html file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{title}}</title>
</head>
<body>
    <h1>
        SEND AN EMAIL
    </h1>
    <form action ="{% url 'email' %}" method="post">
        {% csrf_token %}
        <table>
            <tr>
                <td>
                    TO
                </td>
                <td>
                    <input type="email" name="toemail">
                </td>
            </tr>
            <tr>
                <td colspan='2'>
                    <textarea name="content" cols="30" rows="10"></textarea>
                </td>
            </tr>
            <tr>
                <td>
                    <input type="submit" value="Send">
                </td>
                <td>
                    <input type="reset" value="Clear">
                </td>
            </tr>
        </table>
    </form>
    
</body>
</html>

To send an email we need to import send_email in views.py. Along with that, we will create a send_mail function in which we will show the subject, message, and from_email(EMAIL_HOST_USER). This from_email is mentioned in the settings.py file so, we will import it from there. Now, follow the code mentioned below in the view.py file.

from django.shortcuts import render
from django.core.mail import send_mail
from django.conf import settings

def sendanemail(request):
    if request.method == "POST":
        to = request.POST.get('toemail')
        content = request.POST.get('content')
        send_mail(
            #subject
            "testing",
            #message
            content,
            #from email
            settings.EMAIL_HOST_USER,
            #recipent list
            [to]
        )
        return render(
        request,
        'email.html',
        {
        'title':'send an email'
        }
    )
    else:
        return render(
        request,
        'email.html',
        {
        'title':'send an email'
        }
    )

Make Migrations

After making these changes we need to make migrations before running our server. To make migrations run the following commands in the command prompt or a terminal.

> python manage.py makemigrations
> python manage.py migrate

We have made the migrations and now we will run the server.

READ:  Matplotlib 3D scatter

Run the development server

Now, we are ready to run this Email sender Python Django application, Now run the following command in the terminal or command prompt.

> python manage.py runserver

Testing

Copy the mail address and paste it into the credentials of our email sender app and write the text in the text box.

Django Email Sender Application
Sending email via Django Email Sender

Now, Go and check the inbox of the email to which you send the mail.

Django Application Email Sender
Email sent by Python Django Email Sender

Till now we have completed the functioning of our Email sender application. It is ready to use and to make it more dynamic we are going to compile it with a rich text editor. So, in the next steps, we going to see the integration of our application through the rich text editor.

Step 10: Adding Summernote rich text editor in Django app.

To add more functionality to our Email sender app we are going to integrate it with Summernote rich text editor. Our app will get more functions like advanced styling options like heading levels, bold, italic, bullet points, font typefaces, and text size.

Django Application Email Sender with Summernote
Integrating Python Django app with Summernote rich text editor

Conclusion

In this Python Django tutorial, we have learned how to structure an Email sender application in the Django framework and tested its functionality also. We also learned about the SMTP (Simple mail transfer protocol) server and used it in the structure of our application.

In last, We added Summernote rich text editor to our Python Django application to make it more dynamic and to add more functionalities to it.

Also, check the following Python Django tutorials.