Skip to content

Instantly share code, notes, and snippets.

@coreindustries
Last active December 27, 2019 18:21
Show Gist options
  • Save coreindustries/9e0eec867585a9ca2731086c3f7808a0 to your computer and use it in GitHub Desktop.
Save coreindustries/9e0eec867585a9ca2731086c3f7808a0 to your computer and use it in GitHub Desktop.
Python: validate email address
def validate_email(email_address):
"""
Validate an email address.
We selected a "simple" validation with has a bias toward
letting more edge cases through rather than block them.
We want the feedback.
Returns True if the email is valid. False is not.
https://stackoverflow.com/questions/8022530/how-to-check-for-valid-email-address
"""
# simple regext
# EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+")
# https://emailregex.com/
EMAIL_REGEX = re.compile(r"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])")
# unencode. value comes in like this: 'jim%40jim.com'
try:
e = urllib.parse.unquote(email_address)
except Exception as e:
log.debug(f"ERROR decoding email: {email_address}")
return False
if not EMAIL_REGEX.fullmatch(e):
log.debug(f"validating email FAIL: {e}")
return False
else:
log.debug(f"validating email PASS: {e}")
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment