How I Created an Email Address Verifier Using Flask

4/5 - (2 votes)

Email addresses are primarily used for communication. They are also used for authentication and authorization. Collecting email addresses is crucial for marketing companies and other businesses. It helps to promote their services and to provide good customer support.

βœ… Verification of email addresses involves confirming the authenticity or legitimacy of user’s email address. Integrating email verification in signup forms will ensure businesses have customer email addresses that are valid and reachable.

Notice the expression, ‘valid and reachable.’ This means an email can be valid but not reachable.

How to Verify Email Addresses?

There are several ways to check if an email address is valid and in existence.

Method 1: We can use a Regular Expression. The re Python module has search and match methods that return an object that matches the given pattern.

Regular Expression, though it works in most cases cannot be relied on to verify the authenticity of email addresses. And if you are like me who struggles to understand Regular Expression, you probably won’t consider it an ideal one to use.

What is more, Regular Expression only checks email formats but not their existence. You may want to try other ways of verifying email addresses.

Method 2: Another way to verify an email address is to use a Python package, validate-email-address. It also uses the re module to check if the email address is properly formatted, and a third-party Python package, py3dns to ensure it is active.

Here is a simple way to use the module:

from validate_email_address import validate_email
isValid = validate_email('melancholy@gmail.com', verify=True)
print(isValid)

If that email exists, it will print out True.

Method 3: The best and recommended way to verify an email address is by using an API. Dedicated third-party APIs such as emailvalidation.io provide a secure and reliable way to verify an email address.

In this project tutorial, we are going to implement such a feature in a Flask application. Go to the website, register with your email and password. Log in and you will see your API key. We will use the API key in our Flask application.

Creating a Flask Application

Create and activate a virtual environment in a new folder. Then, install the Flask package. Next, create a templates folder. Inside the folder, create base.html and index.html files.

For the base.html file, write the following:

<!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>Flask Email Verifier</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body style="background-color:rgb(248, 244, 244)">
    {% block content %}

    {% endblock %}
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

The index.html will inherit everything in the base.html. Write this inside the file:

<!-- extends is for inheriting from the base.html -->
{% extends 'base.html' %}
{% block content %}
<div class="row justify-content-center my-5">
          <div class="col-md-5 mt-4">
              <div class="card">
                  <h3 class="card-header">Email Verifier</h3>
                  <div class="card-body">
                    <form action="." method="POST">
                      
                      <div class="input-group">
                        <input type="text" required class="form-control" name="email-address" placeholder="Enter an email address to verify it">
                        <div class="input-group-append">
                          <button class="btn btn-primary fw-bold" type="submit">
                            Verify
                          </button>
                        </div>
                      </div>
                    </form>
                      <hr>
                      {% if response %}
                      <p>{{ response }}</p>
                     {% endif %}

{% endblock %}

Let’s write a function that sends a request to the API. Save the following script as email_verifier.py in your project folder:

import requests
from decouple import config

API_KEY = config('secret_key')


def is_valid_email(email):
    url = f"https://api.emailvalidation.io/v1/info?email={email}&apikey={API_KEY}"
    response = requests.get(url)
    if response.status_code == 200:
         json_res = response.json()
         format_valid = json_res['format_valid']
         mx_found = json_res['mx_found']
         smtp_check = json_res['smtp_check']
         state = json_res['state']
         return format_valid and mx_found and smtp_check and state == 'deliverable'
    return False

We import the requests module to be used to make a request to the API. We also import python-decouple module to load environment variables. So, you have to install these modules together with python-dotenv in your virtual environment. Check my GitHub page for the full code.

In your project folder, create a .env file to store your API key. Inside the file write these:

secret_key = 'Your API Key'

We then use the config class to load the API key. This is a safe way to import sensitive information. After sending a GET request to the API, we have the following as the response converted to JSON if the email is valid:

{
   "email":"support@emailvalidation.io",
   "user":"support",
   "tag":"",
   "domain":"emailvalidation.io",
   "smtp_check":true,
   "mx_found":true,
   "did_you_mean":"",
   "role":true,
   "disposable":false,
   "score":0.95,
   "state":"deliverable",
   "reason":"valid_mailbox",
   "free":false,
   "format_valid":true,
   "catch_all":"None"
}

The main fields to watch out for that confirms the authenticity of an email address are, format_valid, mx_found, smtp_check, and state. You can learn about them here.

The is_valid_function() function returns True if all the four fields are True else, it returns False. We will then call this function in our Flask application.

Create an app.py file and write the following:

from flask import Flask, render_template, request
from email_verifier import is_valid_email


app = Flask(__name__)

@app.route('/', methods=['POST', 'GET'])
def index():
    # checking if the method is POST
    if request.method == 'POST':
        # getting the email from the form input
        email = request.form['email-address']
        if is_valid_email(email) == True:
            response = f'Your email, {email} is valid'
            return render_template('index.html', response=response)
        else:
            response = f'Your email, {email} is not valid'
            return render_template('index.html', response=response)
    return render_template('index.html')

You can see we import the is_valid_email() function as well as the Flask class and other important functions we will use. After creating the application object and the routes, we send a POST request to retrieve data from the index.html file. This is the email address the user will input.

We then send it to the is_valid_email() function.

If it returns True, we use the render_template function to display a message stored in the response variable to the index.html file. In the render_template(), the response attribute is from the index.html file, the other response (a variable) is the one with the message.

If the callback function returns False, we display a different message. If the request is not POST, we simply display the empty form on the webpage.

Conclusion

We have learned how to implement an email verifier feature in a Flask application. There are so many ways to create this app as well as other APIs you can use to verify email addresses. You can implement this feature while creating user authentication in your Flask application.

By working on projects such as this, you are improving your skills and gaining confidence as a web developer.

πŸ’‘ Recommended: Full-Stack Web Developer β€” Income and Opportunity