email-validator Documentation

repository·main·Indexed 23 days ago

https://github.com/joshdata/python-email-validator

A robust Python library for validating email address syntax and deliverability. It supports internationalized domain names (IDN) and local parts, provides human-readable error messages via EmailNotValidError, and handles Unicode normalization. The library includes the validate_email function for syntax and DNS checks, a caching_resolver for performance, and returns a ValidatedEmail object containing normalized and ASCII forms of the address.

Tokens
1.6K
Snippets
5
Records
7
Agent score
31%

What's inside email-validator

  1. How Unicode normalization works in email-validator

    main

    The library performs Unicode normalization to ensure that different but semantically equivalent strings are treated identically. This is critical for internationalized email addresses.

    • Domain Normalization: Converts fullwidth/halfwidth characters to ASCII (via IDNA/Punycode) and applies Unicode NFC normalization.
    • Local Part Normalization: Applies Unicode NFC normalization and removes unnecessary quotes or backslash-escaping in quoted-string local parts.
    • Consistency: The normalized field provides the consistent form you should use for database queries and storage to prevent duplicate accounts caused by different Unicode representations of the same address.
    emailinfo = validate_email("me@Domain.com")
    print(emailinfo.normalized)
    print(emailinfo.ascii_email)
    # prints "me@domain.com" twice
  2. Allow test domain names like @test

    main

    By default, the library rejects special-use domain names like localhost or test to prevent abuse. In non-production test environments, you can allow these in three ways:

    1. Pass test_environment=True to the validate_email call.
    2. Set the global variable email_validator.TEST_ENVIRONMENT = True.
    3. Manually remove a specific domain from the allowed list: email_validator.SPECIAL_USE_DOMAIN_NAMES.remove("test").
    import email_validator
    email_validator.SPECIAL_USE_DOMAIN_NAMES.remove("test")
  3. Quick Start: Validate an email address

    main

    Use validate_email to check if an email address is syntactically valid and optionally check its deliverability.

    Important Best Practices:

    1. Use the normalized form: Always use the .normalized attribute of the returned object for database storage and for subsequent lookups (like login).
    2. Handle exceptions: Catch EmailNotValidError to get human-readable error messages for end-users.
    3. Optimize for login: When validating during a login process, set check_deliverability=False to avoid unnecessary and slow DNS queries.
    from email_validator import validate_email, EmailNotValidError
    
    email = "my+address@example.org"
    
    try:
      # Check that the email address is valid. Turn on check_deliverability
      # for first-time validations like on account creation pages (but not
      # login pages).
      emailinfo = validate_email(email, check_deliverability=False)
    
      # After this point, use only the normalized form of the email address,
      # especially before going to a database query.
      email = emailinfo.normalized
    
    except EmailNotValidError as e:
      # The exception message is human-readable explanation of why it's
      # not a valid (or deliverable) email address.
      print(str(e))
  4. Configure a caching DNS resolver

    main

    To improve performance when validating many email addresses, use caching_resolver to create a dns.resolver.Resolver with an LRU cache. Reuse this resolver instance across multiple calls to validate_email.

    from email_validator import validate_email, caching_resolver
    
    resolver = caching_resolver(timeout=10)
    
    while True:
      validate_email(email, dns_resolver=resolver)
  5. Use validate_email() with configuration options

    main

    The validate_email(email_address, ...) function accepts several keyword arguments to control validation behavior.

    OptionDefaultDescription
    check_deliverabilityTruePerforms DNS queries to check if the domain can receive mail. Set to False for login forms.
    dns_resolverNonePass a dns.resolver.Resolver instance to control timeouts or use a cache.
    test_environmentFalseIf True, disables DNS checks and permits .test domains.
    allow_smtputf8TrueIf False, prohibits internationalized addresses requiring the SMTPUTF8 extension.
    allow_quoted_localFalseIf True, allows quoted-string local parts (e.g., containing spaces or @).
    allow_domain_literalFalseIf True, allows bracketed IPv4/IPv6 addresses in the domain part.
    allow_display_nameFalseIf True, allows input like "My Name" <me@example.com>.
    allow_empty_localFalseIf True, allows an empty local part (e.g., @example.com).
    strictFalseIf True, performs additional syntax checks like local part length.
  6. Understand the ValidatedEmail return object fields

    main

    When validate_email succeeds, it returns an object containing the following fields. You should primarily use the normalized field for storage and comparison.

    FieldDescription
    normalizedThe normalized form of the email address (use this for your database).
    ascii_emailThe ASCII-only form (using Punycode for the domain). None if the local part is internationalized.
    local_partThe normalized local part (before the @-sign).
    ascii_local_partThe ASCII-only version of the local part.
    domainThe canonical internationalized Unicode form of the domain.
    ascii_domainThe Punycode-encoded form of the domain (as sent on the wire).
    domain_addressAn ipaddress.IPv4Address or ipaddress.IPv6Address object if a domain literal was used.
    display_nameThe unquoted/unescaped display name, if present.
    smtputf8Boolean indicating if SMTPUTF8 is required (true if local part is non-ASCII).
    mxA list of (priority, domain) tuples from DNS MX records.
    mx_fallback_typeThe type of DNS record used if no MX was found (A or AAAA).
    spfAny SPF record found during deliverability checks.