Little Mail Validator in Python

Page content

wrote a little Mail Adresse Validator in Python. use it, modify it, like it … best practice for python is to use a virtual env like Poetry (or virtualenv) and add the “email-validator” module like this:

poetry add email-validator

Code

few lines of code …

#!/usr/bin/env python3

from email_validator import validate_email, EmailNotValidError

ok=[]
nok=[]

emails = [
        "my+address@mydomain.tld", "hans@dampf.ch", "gott@welt.net",
        "adsf@asdf.com", "asf.asdf", "franz!mueller@abc.com", "asdf@asdf.adf"
        ]

print ("\nMy Little Mail Validator\n")

for email in emails:

    try:
        # Validate.
        valid = validate_email(email)

        # Update with the n
        email = valid.email

        # Append to List
        ok.append(email)

    except EmailNotValidError as e:

        # email is not valid, exception message is human-readable
        nok.append(str(e))


print ("*** Mail ok ***")
for item in ok:
    print("ok: ", item)

print ("\n*** Mail NOT ok ***")
for item in nok:
    print("NOK:", item,"!")

print()

Run

just run and enjoy …

$ poetry run ./confirmmail.py

My Little Mail Validator

*** Mail ok ***
ok:  hans@dampf.ch
ok:  gott@welt.net
ok:  adsf@asdf.com
ok:  franz!mueller@abc.com

*** Mail NOT ok ***
NOK: The domain name mydomain.tld does not exist. !
NOK: The email address is not valid. It must have exactly one @-sign. !
NOK: The domain name asdf.adf does not exist. !

Any Comments ?

sha256: c063255a24b462198b032e1555206d0a0dfa0aca3046270baee731db9e15ebe8