Validating and Verifying Emails in Django

Validating and Verifying Emails in Django

Table of contents

No heading

No headings in the article.

A valid email address consists of an email prefix and an email domain, both in acceptable formats. The prefix appears to the left of the @ symbol. The allowed characters in an email prefix are letters (a-z), numbers, underscores, periods, and dashes. An underscore, period, or dash must be followed by one or more letters or numbers. The domain appears to the right of the @ symbol.

For example, in the address , "example" is the email prefix, and "mail.com" is the email domain.

Django email field checks the value for a valid email address using EmailValidator. EmailValidator validates an email through a predefined regex that checks ‘@’ and a ‘.’ defined after it. If a user enters - for instance, , which does not exist the Django EmailField still accepts it as long as it is in the acceptable format. This does not fully verify an email as a user can enter unreal and non-existent addresses which may lead to future problems in the system.

To validate the email and also verify they exist two third-party packages can be used. Just like every other python package, we install validate-email and pyDNS before usage.

pip install validate-email
pip install pyDNS
pip3 install py3DNS    #for python 3.0 and above

validate-email checks whether the email is in a proper format while pyDNS checks the domain server and verifies if email truly exists.

Usage

from validate_email import validate_email
verify_email = validate_email('example@mail.com' , check_mx = True)
print(verify_email)

#This returns True if the email exists in real-world else False.

And that's all!!!. With this, we can be sure that user inputs from email fields in our forms are verified and real.

Also, regular expressions can be used although it is not always a good approach, it helps to customize our own version of validation but a more simple and efficient way is to use the validate email and pyDNS package. If you would like to read more on regular expressions, you can check here en.wikipedia.org/wiki/Regular_expression