Skip to content

Instantly share code, notes, and snippets.

@deangrant
Created February 13, 2023 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deangrant/011ed5bd839727c1890b33bb964da0d0 to your computer and use it in GitHub Desktop.
Save deangrant/011ed5bd839727c1890b33bb964da0d0 to your computer and use it in GitHub Desktop.
Checks if a string is a valid email address in Python. Uses a regular expression to check that the email address conforms to the syntax rules specified in RFC 5322.
def is_valid_email(
email_str: str
) -> bool:
"""
Check if a string is a valid email address. The regular expression checks
that the email address conforms to the syntax rules specified in RFC 5322.
Parameters:
email_str (str): The string to check.
Returns:
bool: True if the string is a valid email address, False otherwise.
Example:
>>> is_valid_email("user@example.com")
True
>>> is_valid_email("user@example")
False
"""
# Use email.utils.parseaddr to split the email address into parts
# and get the email address part.
email_address = email.utils.parseaddr(email_str)[1]
# Use a regular expression to check that the email address is valid.
regex = r"(?=.{1,64}@.{1,255}$)(?=.{1,64}\.{1,255}$)[^@ ]+@[^@ ]+\.[^@ ]{2,}$"
return re.match(regex, email_address) is not None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment