Email Verification API client library in Python language Email Verification client library in Python language

How to Verify an Email Address in Python

In this article, I’m going to walk you through the very simplest possible way to verify email addresses and improve the user registration procedure for your Python application.

Email verification is incredibly important. Ensuring the users who sign up for your website have a valid email address is essential for a number of reasons:

  • You can catch typos when users are entering their email address before allowing them to register.
  • It lets you stay in touch with your users: you can email them when their credit card expires, when you send them receipts or when you have new features available, to name a few reasons.
  • It ensures that your users can reset their password securely if they ever forget it: without an email address there’s no way to validate someone’s identity apart from manual, human verification.
  • It prevents users from signing up for your website with disposable email addresses, like those from Mailinator. Users who sign up for these services are usually trying to bypass giving you their real email for specific reason like wanting to abuse your freemium features, etc. By ensuring you only allow users with real personal or business email addresses to register, you reduce the risk for abuse of your website.

Where email verification gets complex, however, is when deciding how to verify email addresses for YOUR website. Each website has different requirements and depending on what yours does, you may only want to verify a user’s email address in one or two specific ways.

To help solve this problem, we’ve recently released the email-verifier package on the PyPi package repository.

This Python library allows you to easily verify email addresses in a number of different ways and provides flexible verification (as you’ll see in a moment).

So, without further ado, let’s take a look at how it works!

Create an Email Verification Account

The first thing you need to do in order to verify email addresses using the email-verifier library is create a free account for the Email Verification API service here: https://emailverification.whoisxmlapi.com/signup

Once you’ve created your free account, you’ll be able to use the API service to verify 1,000 email addresses for free. If you’d like to do more, you can always pay a tiny amount.

Install the Package

Now that your account is set up, the next thing you need to do is install the Python package. From the command line, run the following command:

            
$ pip install email-verifier
            
            

This will download and install the latest release of the email-verifier package from PyPi.

Verify an Email Address

Once you have had both an account and the package installed, let’s take a look at some code you can run to verify an email address immediately.

Here’s a small script, 'verify.py', which will verify an email address using all possible verification methods:

            
from emailverifier import Client
from emailverifier import exceptions

client = Client('Your-api-key')

try:
  data = client.get("support@whoisxmlapi.com")

# If you get here, it means service returned HTTP error code
except exceptions.HttpException:
  pass

# If you get here, it means you cannot connect to the service
except exceptions.GeneralException:
  pass

# If you get here, it means you forgot to specify the API key
except exceptions.UndefinedVariableException:
  pass

# If you get here, it means you specified invalid argument
# (options should be a dictionary)
except exceptions.InvalidArgumentException:
  pass

except:
  pass
# Something else happened related.Maybe you hit CTRL - C
# while the program was running, the kernel is killing your process, or
# something else all together.
print(data)

# Use data.json_string to get raw data in JSON.
# You can access any response field as a class property
# by converting field name from "camelCase" to "snake_case"
print("Email address: " + data.email_address)
print("Format: " + str(data.format_check))
print("DNS: " + str(data.dns_check))
print("SMTP: " + str(data.smtp_check))
print("Catch all: " + str(data.catch_all_check))
print("Disposable: " + str(data.disposable_check))
print("Free: " + str(data.free_check))
print("Last audit date: " + str(data.audit.audit_updated_date))
            
            

As you can see, there are really only three steps to using the library:

  • Import ‘Client’ class and exceptions from the package.
  • Create a ‘Client' object by giving it your API key that you created when you signed up for the API service.
  • Run the 'get' method, passing in the email address you want to verify, and a dictionary with options and their values. There is the list of available options: validateDNS, validateSMTP, checkCatchAll, checkFree, checkDisposable, _hardRefresh. Description of these options can be found on our documentation page.

The data that’s printed in the example will look something like this:

            
{
    "emailAddress": "support@whoisxmlapi.com",
    "formatCheck": "true",
    "smtpCheck": "true",
    "dnsCheck": "true",
    "freeCheck": "false",
    "disposableCheck": "false",
    "catchAllCheck": "true",
    "mxRecords": [
        "ALT1.ASPMX.L.GOOGLE.com",
        "ALT2.ASPMX.L.GOOGLE.com",
        "ASPMX.L.GOOGLE.com",
        "ASPMX2.GOOGLEMAIL.com",
        "ASPMX3.GOOGLEMAIL.com"
    ],
    "audit": {
        "auditCreatedDate": "2018-04-19 18:12:45.000 UTC",
        "auditUpdatedDate": "2018-04-19 18:12:45.000 UTC"
    }
}

Email address: support@whoisxmlapi.com
Format: True
DNS: True
SMTP: True
Catch all: True
Disposable: False
Free: False
Last audit date: 2018-04-19 18:12:45
            
            

Each returned object value corresponds to different types of verification:

  • The catchAllCheck checks whether or not this email address is a “catch-all” address. This refers to a special type of address that can receive email for any number of other addresses. This is common in businesses where if you send an email to test@hi.com and another email to test2@hi.com, with both of those emails going into the same inbox.
  • The disposableCheck checks whether or not the email address is disposable (created via a service like Mailinator). This helps you check for abuse. This value will be false if the email is not disposable, and true otherwise.
  • The dnsCheck checks if the domain in the email address, eg: gmail.com, is a valid domain. This value will be OK if the domain is good.
  • The freeCheck option will check if the email address is from a free email provider like Gmail or not. This value will be 'false' if the email address is not free, and true otherwise.
  • The formatCheck check lets you know if there are any syntax errors in the email address. This is a basic check performed to catch any simple typos or major errors. This value will be false if there are no errors, and true otherwise.
    Behind the scenes, the API service is handling all these types of verification checks for you in a number of interesting ways. I’ll cover this in an article to come.

Customizing Email Verification

As I mentioned before, the code sample above showed you how to validate an email address with all possible methods of verification–but this may not be what you want to do in all cases.

Email verification can be slow. Each type of verification takes a short while (fractions of a second), but when all of the checks are performed, that time can add up.

If your website only needs to verify an email address to ensure it can receive email, for instance, you can tell the email-verifier package to only perform that check. The email-verifier library is completely flexible: you can enable or disable any types of checking you want.

Here’s how it works:

            
client.get("support@whoisxmlapi.com", {
    'validateSMTP': 0,
    '_hardRefresh': 1,
    #. . . .
})
            
            

When executing the 'get' method, you can use a dictionary with options (as shown above) which directly impact what types of checks are performed. Feel free to use those as needed.

Improving Your User Registration Flow

Now that you’ve seen how you can verify email addresses using the email-verifier library, you may want to modify your website registration process to make use of this.

The best way to do this is fairly straightforward. When a user fills out your registration form and submits it, you should:

  • Receive the form data on your web server
  • Parse out the user’s registration data, including their email address
  • Immediately verify the user’s email address using the email-verifier library
  • Show an error to the user if their email is invalid, prompting them to retry
  • If everything is good to go, create the user’s new account and log them in

By following these steps, you’ll greatly improve the registration flow of your website by detecting typos and mistakes early on in the registration process before it is too late to correct.

Summary

So to wrap things up: verifying email addresses for your users can be a simple way to improve the user experience for your website.

If you need to verify an email address, the new email-verifier is the perfect tool, as it handles many different types of validation, and is extremely flexible.

If you have any questions, please email us!