How To Use Gmail as an Email Client for your Django Web App

Introduction

The project looks into how you can use Gmail as an Email Client for your website, this can be done when one needs a reliable and safe email client service. Also compounded by the fact that a lot of organizations host their email accounts on Google’s Gsuite due to its reliability.

Intended audience: Who the article is for

This article targets python/Django developers who would want to build a web app, without the hustle of building and maintaining an email client service. It provides the user with an option of using google email client API.

Case Study: What the article is going to cover

The project will display two use cases, the first being – sending an email to another user and the second being – requesting for a password reset, where the reset link will be emailed to the user.

The application is built using python programming language in Django Framework.

Requirements:

  1. Some knowledge of Python and Django
  2. Google Account
  3. Google Generated App Password

Getting started with Google

Creating a Gmail Account

To create a Gmail account, open your browser and type Gmail sign up, it should take you to the page below, for you to enter your details:

Follow the remaining steps provided for you to sign up

After a successful sign up you will be directed to your profile/admin page, similar to the one below:

Once your google account is created you get access to Google services like Gmail, YouTube, Photos etc.

Accessing your Google Account

If you already have a Gmail/Gsuite, go to the link https://myaccount.google.com/ and log in using your google/gmail username and password, to get to the above page (my account’s page)

Click on the “Security” Menu Option on the left navigation bar

It will take you to the Security page, where you will scroll down to the “Signing in to Google” section, displayed below:

Click on the 2-Step Verification’s “Off” to switch it “On”, it will take you to the p age below:

Click on “GET STARTED”, where it will ask for your password so as to verify it’s you

Entering the correct password and submitting will take you to the form below:

Enter your phone number and select Text message, you can select Phone call if you want

Click on “Next” button and google will send a code to your phone for you to enter on the next page

Enter the code on click on “Next”

A final page will show up with the option to “Turn On” 2 Step Verification, similar to the one below:

Click on “TURN ON” and it will then send you to the page below:

Click on the “Back” arrow to take you back to the “Security” page of your account and navigate down to the “Signing in to Google” section

Click on the “None” option next to App passwords, this page will take you to a verification page for you to enter/confirm your username and password

After confirming, the page below will be displayed:

Select the app dropdown and select other and enter the name of the app to be associated with, give it any name. e.g. DjangoGmailEmailClient

Click on “Generate” and a pop up with the secret password to be used when using the Gmail Email client will be displayed, similar to the one below:

Copy this password to some safe place and where you won’t forget

Storing the Generated Credentials

Option 1: Inside a JSON file

  1. We will now create a JSON file inside the “users” app folder to store these credentials, this file will be called “config.json”
  2. Inside this file paste the code below:

This JSON code contains two variables:

  • EMAIL_HOST: This is the google account we created above or we intend to use for sending/managing emails
  • EMAIL_PASSWORD: This is the password we generated above for the google account in order to use the Gmail email service
  1. Enter your google account username and the generated app password retrieved above

We will access this file from our Django web app and retrieve the credentials The reason I have placed the credentials in this file, is so that I can place the file where I want in a server/computer where I feel it’s safe and retrieve the credentials from it by passing the path to the file inside my Django App (This is displayed later on in the article).

Option 2: Inside your Environment Variable

If you are using/hosting in a windows environment you have an option of storing these credentials inside the computer’s environment variable and then access the name of the environment variable parameter from the Django app. This protects your credentials from getting out, in case you get to push your code to a repository.

Below are the steps on how to do so:

Type environment variable on the search bar on the bottom left side of your screen

Select the first option from the control panel that pops up

A system properties window will pop up, click on the environment variable button

An environment variable window will pop up, click on the highlighted “New” button under the “User variables for …”

A “New User Variable” window will pop up, enter the “Variable Name” as EMAIL_HOST and enter the Google account you created above under the “Variable Value” and then click “Ok”

Click on the highlighted “New” button under the “User variables for …” in the environment variable window again to create and save the password associated with the google account that we created above.

A “New User Variable” window will pop up, enter the “Variable Name” as EMAIL_PASSWORD and enter the password for the google account you created above under the “Variable Value” and then click “Ok”

Getting started with the Web App

Creating a Django Project

  1. From your terminal navigate to the folder/location your project is to reside
  2. We will create a Django project called “djangogmailemailclient”, type the command: django-admin startproject djangogmailemailclient
  3. From the terminal navigate into the created project folder, where you will create and activate your project’s virtual environment by typing in the terminal the command “python –m venv venv”
  4. In windows, type “venv\Scripts\activate” in the terminal
  5. In Mac/Linux, type ”source venv/bin/activate” in the terminal
  6. After your virtual environment has been activated, run the code below in the terminal to install the following python packages
    1. “pip install requests” : python package used in managing HTTP requests
    1. “pip install django” : python package to be used in building the web app
    1. “pip install django-crispy-forms”  : to be used rendering bootstrap styles in HTML templates
  7. Create your first Django app by typing in the terminal the command: “python manage.py startapp users”
  8. Create a SQLite database that will used by the project by typing in the terminal the command: “python manage.py makemigrations”
  9. Apply database changes by typing in the terminal the command: “python manage.py migrate”
  10. Start your server by typing on the terminal the command: “python manage.py runserver”
  11. If the server starts successfully there should be a webpage up and running on the location: http://127.0.0.1:8000
  12. While in the terminal type Ctrl+C to stop the server
  13. Everything from now on will be performed inside this python activated environment
  14. We are stopping the server so that we can create the database tables first and then apply the changes before restarting the server

Creating Project CSS File

  1. Open the Django project folder your code editor
  2. Open the “users” app folder
  3. In the “users” app folder, create a folder labeled “static”
  4. Inside the created “static” folder create another folder labeled “users”
  5. Inside the “users” folder just created inside the “static” folder, create a css file labeled “main.css”
  6. Copy the code below into the “main.css” file

Creating Database Tables

We will not need to create any databases table as we will use the default “User” database table provided by Django as a built-in database table/model

Configure Project Settings

  1. In order to apply the database changes we just made we need to register the apps we have created in the projects settings. Here is how to do so:
  2. Open your Django project folder: “djangogmailemailclient”
  3. Locate a folder with a similar name to your Django project folder, this folder is in the same directory as your “users” app folder
  4. Inside this folder is a python file labeled “settings.py”
  5. Open the “settings.py” file and locate the variable INSTALLED_APPS
  6. The variable INSTALLED_APPS is a list where you will insert the apps we just created
  7. Insert the code below inside the list:

Here we are registering the “users” app we created and also the “crispy_forms” app we installed to help use beautify our web app.

Creating “Users” HTML Templates

  1. On these HTML templates is where the different users data will be displayed
  2. We will start by creating HTML templates related to the “users” app we created, which are:
    • login.html – The log in page
    • logout.html – The log out page
    • signup.html – The sign up page
    • index.html – The default home page for the web app with brief instructions on how the web app works
    • base.html – This is the page that will be inherited/extended by all other HTML template pages
    • password_reset.html – The page a user will input their email for a password reset link to be sent to
    • password_reset_complete.html – The page that will notify a user that a password reset link has been successfully sent to the provided email address
    • password_reset_confirm.html – This page where a user will enter their new password
    • password_reset_done.html – This page will be used to display to the user the success message after the password has been changed
    • send_email.html – This page will be used to display the registered users in the system, for the logged in user to select one to send an email to.
  3. To create the above “users” HTML templates do the following:
    • In your project folder navigate into the “users” folder
    • Create a folder labeled “templates”
    • Inside the “templates” folder create another folder and label it “users”
    • Inside the “users” folder you have just created inside the “templates” folder
    • Create the following blank HTML pages; login.html, logout.html, signup.html, index.html, base.html, password_reset.html, password_reset_complete.html, password_reset_confirm.html, password_reset_done.html and send_email.html.
    • Below is a screenshot of the “users” directory tree:

Below are the HTML codes to be placed on each HTML page:

Create User Profile Forms

These are the forms used to render user data onto the sign up page and the user emailing page

  1. Open the “users” app folder
  2. Locate/create a python filed labeled “forms.py”
  3. Paste the code below:

User Sign up Form Logic

We start by importing a Django form that we will use to extend the form we are about to create. The form to be created is a Python class that uses object oriented programming techniques to inherit certain properties from an already built in Django form called “UserCreationForm”.

This form is used within Django to create or register new users when used inside a HTML page. We will instantiate the email field inside this form, so as to make it a mandatory field, we will also set the form to interact with the model or database table called “User”, while also stating that specific fields from the user table to be displayed on the form when displayed for user input.

These fields are:

  • “first_name”: a field to enter a user’s first name
  • “last_name”: a field to enter a user’s last name
  • “username”: a field to enter a user’s username to be used during log ins
  • “email”: a field to enter a user’s email address
  • “password1”: a field to enter the new password for the user account to be created
  • “password2”: a field to confirm the password entered in the first password field

Email Message Form

We start by importing Django forms and user database tables we created. We then create a python class called “EmailMessageForm” that will inherit from python’s “form.Form” class, doing so changes this python class to a form class than can be instantiated and passed to a HTML page to be displayed as a form. We are extending from the python Django “form.Form” class so as to make a few tweaks to the form.

We want our form to have a users’ drop down list for a user to select another user to send an email to. This drop down list will be a HTML select element with the values as the user ids and the displayed drop down value as a concatenation of the user’s first name and last name.

The form will also have subject field for the user to enter the email’s subject and also a message filed for the user to compose the email message to be sent to the selected user.

We will also set some custom HTML styles for our subject and message form fields, inside the class’ constructor

Creating your business logic for Users App

These are the functions that will be executed by the web app URLs in order to return a HTML page. They are usually placed in a file called “views.py”. Do the following to edit this file:

  1. Open the “users” app folder
  2. Locate a python filed labeled “views.py”
  3. Paste the code below

Views Code Logic

We start by importing the following methods:

  • Render – This method is used to return a HTML page to the user
  • Redirect – This method is used to redirect a user to a different page
  • User – The built in django database table or model called “User”
  • Client and OTP – The two database tables or models we created
  • Messages – This is a built in Django method that allows one to send messages back to the template they are rendering
  • UserSignUpForm, EmailMessageForm – The two forms or model forms we created
  • login_required- a built in Django method called a decorator that is embedded at the top of a method definition so as to add more functionality to the method. In this case this decorator is added on top of a view method so as to check first if a user has logged in before they view a particular view or HTML page

We now build the views/functions or methods below:

  • Index – This is a method or function view that accepts a web request and returns back the index HTML page render
  • Sign Up– This is a method or function view that accepts a web request and displays to the user a HTML sign up page if the request used to get to this view was a “GET” request. Else if a user entered their data on the page and submits the data, a “POST” request is sent back to the same view, which then saves the users data into the database after validation and informs the user their account has been created successfully and finally redirects them to the log in page.
  • Send Email– This is a method or function view that accepts a web request and first checks whether the user has logged in, by applying the imported Django python decorator called “login_required“, if so return back the about HTML page responsible for composing an email to another user, if the user has not logged in redirect them back to the log in page.

If the request to this view was via a browser GET request, display the form responsible for composing an email i.e. “EmailMessageForm” else if a user has selected the user to send an email to, entered the subject, message and then submitted the form, a POST request is sent back to this view.

If the request is a POST get the email subject, message and the selected user’s id, using this user id get the specific user associated with this id and then send an email to them.

Creating the Users App URLs

These are the URLs that will be used by the user to navigate the “users” web app. They are usually placed in a file called “urls.py”. Do the following to create/edit this file:

  1. Open the “users” app folder
  2. Locate/create a python filed labeled “urls.py”
  3. Paste the code below:

URLs Code Logic

We will import the views we created and the built in Django authentication view module. All URLs are placed inside a list that will contain the URL paths to the specific view, the path is a method that takes the URL name, this name will be used to access this URL inside the HTML templates, the view the URL associates with and the URL that will be displayed on the browser’s URL bar.

You can include other URL paths inside a URL if they will be using part of the same URL path name, by using the include tag as it is displayed in the ‘signup/’ URL

It is in this URL file that we will implement the logic to use when resetting a user’s password via a link sent to the email. To do this we will leverage the built in python Django classes, to hasten and ease development, the python Django package to use for this is “auth_views” that we will import.

The following are the URLs to be created and the views associated with this process:

  • “passwod-reset/” – a URL path to a page where a user enters their email to request for a password reset
  • “passwod-reset-confirm/<uidb64>/<token>/” – the link to the page where you will reset your password, this link will be emailed to you using the email settings provided in the projects settings.py file
  • “passwod-reset/done/” – a URL path to a page to inform the user that an email with the link above has been successfully sent
  • “passwod-reset-complete/” – a URL path to a page a user will be redirected to once they reset their email from the emailed link above

Configure Settings

Here we will perform some final settings configurations, which are:

  1. Configure the Crispy package/app to use bootstart4 in its styling
  2. Set the Log In URL
  3. Set the URL a user will be redirected to once they log in
  4. Set up the Google Email Client

To perform the above:

  1. Open your Django project folder
  2. Locate a folder with a similar name to your Django project folder, this folder is in the same directory as your “users” app folder
  3. Inside this folder is a python file labeled “settings.py”
  4. Open the “settings.py” file and paste code below at the very start of the file

Explanation of the code logic above:

We are trying to access the Google account details inside the JSON file:

  1. Import the python JSON module to use in reading a JSON file
  2. Use the “with” python context manager to open the JSON file as a variable
  3. Load the data inside this JSON file variable into a different variable called “config”
  4. The above methods loads the data from a JSON format into a python dictionary format, a python data structure that can be easily traversed
  5. Paste code below at the very end of the file

Explanation of the code logic above:

If you saved the google account data above inside a JSON file and extracted the data into a python dictionary, you can access the individual JSON data using their parameter names by calling the “get” method on the dictionary the JSON data was saved into.

If you saved the data inside window’s environmental variable, use the imported “os” module that’s at the top of the settings file to access the “environ” method that returns a dictionary of all user environmental variables. Use the “get” method on the returned dictionary to get the google account host name and password.

Project Tree

Below is a screenshot of how your project tree should look like, assuming the name of your Django project is “djangogmailemailclient”:

Run the server

  1. cd/navigate into the “djangogmailemailclient” Django project via the terminal
  2. Activate the virtual environment
  3. Start the server by typing the command: python manage.py runserver
  4. If there’s nothing wrong, the server should be up on http:127.0.0.1:8000

Testing the System

  1. Once the server is up
  2. Go to the web page address e.g. http://127.0.0.1:8000
  3. Follow the instructions on the home page on how to test the resetting password via email and sending email to a registered user

Conclusion

This application gives the user a different understanding in implementing security measures during logging in apart from other known methods. I also sheds light away from the use of SMS short codes for SMS campaigns and alert services and into security authentication.

Further improvements could be done on the project such as, allowing users to enter their password of choice during sign up instead of being provided a predefined password, another alternative would be for the system to provide a random password that is sent to the users email address and also allow a user to reset their password.

Finally, you can find the code snippets in this @repo.

Quick Guide

If you just want to clone the project and get it up running, below is how to do so in minutes:

  1. Clone it:
    • git clone https://bitbucket.org/dans0l/djangogmailemailclient.git
  2. Cd into it:
    • cd djangogmailemailclient
  3. Create a venv:
    • python3 -m venv venv
  4. Activate venv:
    • Mac/Linux: source venv/bin/activate
    • Windows: venv\Scripts\activate
  5. Install the requirements:
    • pip install -r requirements.txt
  6. Create DB
    • python manage.py makemigrations
  7. Apply DB Changes:
    • python manage.py migrate
  8. Configure your Google Email Client:
    • Create your Google Account if you don’t have one
    • Generate your Google Account Generate App Passwords (read above how to do so)
    • Open a json  file labeled “config.json” inside the “djangogmailemailclient” project folder
    • Enter the credentials in the file
  9. Run the server:
    • python manage.py runserver
  10. Navigate to the site: http://127.0.0.1:8000
  11. Follow the instructions on the home page to start using the site
  12. Open your email accounts to view the emails sent

Thank you.

9 Shares:
You May Also Like