### Install Test Requirements and Run Tests Source: https://github.com/joshdata/python-email-validator/blob/main/README.md Installs necessary dependencies for testing and then executes the test suite. Ensure you have `test_requirements.txt` in your directory. ```sh pip install -r test_requirements.txt make test ``` -------------------------------- ### Example: Empty Domain Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Demonstrates an invalid email format where the domain part is missing. ```python validate_email("user@") ``` -------------------------------- ### Example: Period at Domain Start or End Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Illustrates invalid email formats with a period at the beginning or end of the domain name. ```python validate_email("user@.example.com") or validate_email("user@example.com.") ``` -------------------------------- ### Install email-validator Source: https://github.com/joshdata/python-email-validator/blob/main/README.md Install the email-validator package using pip. You might need to use pip3 depending on your environment. ```sh pip install email-validator ``` -------------------------------- ### Example Usage of DeliverabilityInfo Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/types.md Demonstrates how to use DeliverabilityInfo in type hints for a function that checks email deliverability. Requires importing necessary components. ```python from email_validator.deliverability import validate_email_deliverability, DeliverabilityInfo from typing import Optional def check_deliverability(domain: str) -> Optional[DeliverabilityInfo]: try: result = validate_email_deliverability(domain, domain) return result except Exception: return None ``` -------------------------------- ### Example: Starting or Ending with Period Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Shows invalid email formats where the local part or domain begins or ends with a period. ```python validate_email(".user@example.com") or validate_email("user@.example.com") ``` -------------------------------- ### Example: Missing @ Sign Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Demonstrates a common syntax error where the email address is missing the '@' symbol. ```python validate_email("userexample.com") ``` -------------------------------- ### Example: Multiple @ Signs Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Illustrates an invalid email format with multiple '@' symbols in the unquoted address. ```python validate_email("user@example@com") ``` -------------------------------- ### Example: Domain Lacks Period Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Illustrates a syntax error when a domain is missing a period, specifically when `globally_deliverable` is set to `True`. ```python validate_email("user@localhost") ``` -------------------------------- ### Example: Empty Local Part Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Shows an invalid email address with an empty local part, which is disallowed unless explicitly permitted. ```python validate_email("@example.com") without allow_empty_local=True ``` -------------------------------- ### Example: Domain is Special-Use Name Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Demonstrates an invalid email address using a special-use domain name, unless `test_environment` is enabled. ```python validate_email("user@localhost") or user@test without test_environment=True ``` -------------------------------- ### Example: Display Name Without Permission Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Shows an invalid email format where a display name is included, but `allow_display_name` is set to `False`. ```python validate_email('"Name" ', allow_display_name=False) ``` -------------------------------- ### Unicode Normalization Example Source: https://github.com/joshdata/python-email-validator/blob/main/README.md Demonstrates how the library normalizes fullwidth Latin characters in domain names to their ASCII counterparts. Use the normalized and ascii_email fields for database operations. ```python emailinfo = validate_email("me@Domain.com") print(emailinfo.normalized) print(emailinfo.ascii_email) # prints "me@domain.com" twice ``` -------------------------------- ### Basic Email Validation Example Source: https://github.com/joshdata/python-email-validator/blob/main/README.md Shows the structure of the returned object for a standard email address, including normalized and ASCII forms. ```python ValidatedEmail( normalized='test@joshdata.me', local_part='test', domain='joshdata.me', ascii_email='test@joshdata.me', ascii_local_part='test', ascii_domain='joshdata.me', smtputf8=False) ``` -------------------------------- ### Example: Mismatched Quotes Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Demonstrates an invalid email syntax caused by improperly matched quotation marks in the address. ```python validate_email('"user@example.com')" ``` -------------------------------- ### Example: Consecutive Periods Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Demonstrates an invalid email syntax where two periods appear consecutively in the local part. ```python validate_email("user..name@example.com") ``` -------------------------------- ### Get Package Version Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/API-INDEX.md Access the package version string from the module-level constant. ```python __version__: str = "2.3.0" ``` -------------------------------- ### validate_email() function Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/README.md Documentation for the main `validate_email()` function, including its signature, parameters, return type, exceptions raised, and usage examples. ```APIDOC ## validate_email() ### Description The primary function for validating email addresses. It performs a series of checks to determine the validity and deliverability of an email. ### Signature `validate_email(email: str, ...)` ### Parameters (Details on parameters like `email`, `allow_empty_local`, `check_deliverability`, etc. would be found in `api-reference/validate_email.md`) ### Return Type `ValidatedEmail` object if the email is valid. ### Exceptions - `EmailNotValidError`: Raised when the email address is not valid. - `EmailSyntaxError`: Raised for syntax-related issues. - `EmailUndeliverableError`: Raised if deliverability checks fail. ### Usage Examples (Examples would be provided in `api-reference/validate_email.md`) ``` -------------------------------- ### Example: Invalid Characters in Domain Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Shows an invalid email address with disallowed characters within the domain name. ```python validate_email("user@exam ple.com") ``` -------------------------------- ### Example: Email Address Too Long Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Illustrates an invalid email address that exceeds the maximum allowed length. ```python validate_email("a" * 300 + "@example.com") ``` -------------------------------- ### Example: Domain Literal Without Permission Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Demonstrates an invalid email address using a domain literal (IP address) when `allow_domain_literal` is disabled. ```python validate_email("user@[192.0.2.1]", allow_domain_literal=False) ``` -------------------------------- ### Missing or Malformed @ Sign Examples Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/errors.md Demonstrates common syntax errors related to the '@' sign in email addresses, including missing, full-width, and small commercial variants. ```python userexample.com ``` ```python user@example.com ``` ```python user﹫example.com ``` -------------------------------- ### Example: Non-ASCII Bytes in Email String Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Illustrates an invalid email address containing non-ASCII bytes, which can lead to syntax errors. ```python validate_email(b"user@\xff example.com") ``` -------------------------------- ### Example: Unsafe Unicode Characters Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Demonstrates an invalid email syntax caused by the presence of unsafe Unicode characters, such as control characters. ```python validate_email("user@exam\x00ple.com") (control characters) ``` -------------------------------- ### Reconstruct ValidatedEmail Object Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/ValidatedEmail.md Use `as_constructor()` to get a string representation that can be used to recreate the `ValidatedEmail` object, useful for documentation and testing. ```python result = validate_email("test@joshdata.me", check_deliverability=False) print(result.as_constructor()) # ValidatedEmail( # original='test@joshdata.me', # normalized='test@joshdata.me', # local_part='test', # domain='joshdata.me', # ... # ) ``` -------------------------------- ### Example: Invalid Characters in Local Part Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Highlights an invalid email syntax due to disallowed characters in the local part, unless quoting is used. ```python validate_email("user!invalid@example.com") without quoting ``` -------------------------------- ### Example: Invalid IPv4 Address in Domain Literal Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Illustrates an invalid email syntax with an improperly formatted IPv4 address within a domain literal. ```python validate_email("user@[999.999.999.999]", allow_domain_literal=True) ``` -------------------------------- ### Example: Quoted Local Part Without Permission Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Illustrates an invalid email format where a quoted local part is used, but `allow_quoted_local` is disabled. ```python validate_email('"user"@example.com', allow_quoted_local=False) ``` -------------------------------- ### Example: International Characters Without Permission Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Shows an invalid email address containing international characters when `allow_smtputf8` is set to `False`. ```python validate_email("ツ@example.com", allow_smtputf8=False) ``` -------------------------------- ### Enable Domain Literals Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/configuration.md Allows domain literals, such as bracketed IPv4 and IPv6 addresses, to be used instead of domain names by setting ALLOW_DOMAIN_LITERAL to True. Examples include user@[192.0.2.1]. ```python import email_validator from email_validator import validate_email # Enable domain literals email_validator.ALLOW_DOMAIN_LITERAL = True result = validate_email("user@[192.0.2.1]", check_deliverability=False) print(result.domain) # [192.0.2.1] ``` -------------------------------- ### Example: Invalid IPv6 Address in Domain Literal Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Shows an invalid email address due to an improperly formatted IPv6 address within a domain literal. ```python validate_email("user@[IPv6:invalid]", allow_domain_literal=True) ``` -------------------------------- ### Example: Invalid IDNA Encoding Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Shows an invalid email address due to incorrect Internationalized Domain Names in Applications (IDNA) encoding. ```python validate_email("user@xn--invalid") ``` -------------------------------- ### Batch Validation with Progress Reporting Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/caching_resolver.md Provides an example of validating a list of emails in batches using the caching resolver and handling potential `EmailNotValidError` exceptions. This pattern is suitable for processing large email lists. ```python from email_validator import validate_email, caching_resolver, EmailNotValidError emails = ["user1@example.com", "user2@example.com", "user3@example.com", ...] resolver = caching_resolver(timeout=15) valid_emails = [] invalid_emails = [] for email in emails: try: result = validate_email(email, dns_resolver=resolver) valid_emails.append(result.normalized) except EmailNotValidError as e: invalid_emails.append((email, str(e))) print(f"Valid: {len(valid_emails)}, Invalid: {len(invalid_emails)}") ``` -------------------------------- ### Example: Local Part Too Long (Strict Mode) Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Shows an email address failing validation due to an excessively long local part when `strict` mode is enabled. ```python validate_email("a" * 100 + "@example.com", strict=True) ``` -------------------------------- ### Configure Global Email Validation Settings Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/README.md Modify global constants to change default validation behavior. For example, set `CHECK_DELIVERABILITY` to `False` to skip DNS checks globally. ```python import email_validator email_validator.CHECK_DELIVERABILITY = False # Skip DNS checks email_validator.ALLOW_SMTPUTF8 = False # Reject non-ASCII local parts email_validator.TEST_ENVIRONMENT = True # Allow test domains email_validator.STRICT = True # Enforce length limits ``` -------------------------------- ### as_constructor() Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/ValidatedEmail.md Returns a string representation suitable for reconstructing the object. Used primarily for documentation/testing purposes. ```APIDOC ## as_constructor() ### Description Returns a string representation suitable for reconstructing the object. Used primarily for documentation/testing purposes. ### Method `as_constructor()` ### Returns - `str` - A string representation of the ValidatedEmail object that can be used to reconstruct it. ### Example ```python result = validate_email("test@joshdata.me", check_deliverability=False) print(result.as_constructor()) # ValidatedEmail( # original='test@joshdata.me', # normalized='test@joshdata.me', # local_part='test', # domain='joshdata.me', # ... # ) ``` ``` -------------------------------- ### Custom Cache Implementation with LRUCache Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/caching_resolver.md Shows how to provide a custom cache object, such as `dns.resolver.LRUCache` with specific settings (e.g., `maxsize`), to the caching_resolver. This allows for fine-grained control over cache behavior. ```python from email_validator import validate_email, caching_resolver import dns.resolver # Create a custom cache with specific settings if needed custom_cache = dns.resolver.LRUCache(maxsize=1000) resolver = caching_resolver(timeout=15, cache=custom_cache) result = validate_email("user@example.com", dns_resolver=resolver) ``` -------------------------------- ### Using Caching Resolver with an Existing Resolver Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/caching_resolver.md Demonstrates how to wrap an existing `dns.resolver.Resolver` instance with caching capabilities provided by `caching_resolver`. This is useful when you need to use custom nameservers or other pre-configured resolver settings. ```python from email_validator import validate_email, caching_resolver import dns.resolver # You have an existing resolver existing_resolver = dns.resolver.Resolver() existing_resolver.nameservers = ["8.8.8.8", "8.8.4.4"] # Custom nameservers # Configure it with caching resolver = caching_resolver(timeout=10, dns_resolver=existing_resolver) result = validate_email("user@example.com", dns_resolver=resolver) ``` -------------------------------- ### Configure for Test Environments Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/configuration.md Enables test-friendly options for non-production environments, allowing test domains and disabling DNS checks. ```python import email_validator # Enable test-friendly options email_validator.TEST_ENVIRONMENT = True email_validator.STRICT = False from email_validator import validate_email result = validate_email("developer@test") # Test domains allowed, DNS disabled ``` -------------------------------- ### Configure for Registration Forms Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/configuration.md Sets up global defaults for registration forms, enabling strict validation, deliverability checks, and support for SMTPUTF8. ```python import email_validator # Enable strict validation email_validator.STRICT = True email_validator.CHECK_DELIVERABILITY = True email_validator.ALLOW_SMTPUTF8 = True # Allow modern mail stacks from email_validator import validate_email result = validate_email(user_email) # Uses global settings ``` -------------------------------- ### Import and Access Global Settings Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/configuration.md Demonstrates how to import the email_validator package and access or modify its global configuration variables at runtime. ```python import email_validator # Access and modify global settings email_validator.ALLOW_SMTPUTF8 = False email_validator.CHECK_DELIVERABILITY = True ``` -------------------------------- ### Basic Usage of Caching Resolver Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/caching_resolver.md Demonstrates how to initialize and use the caching_resolver for validating a list of emails. This approach caches DNS lookups to speed up subsequent validations. ```python from email_validator import validate_email, caching_resolver resolver = caching_resolver() emails = ["user1@example.com", "user2@example.com", "user3@example.com"] for email in emails: try: result = validate_email(email, dns_resolver=resolver) print(f"{email}: Valid") except Exception as e: print(f"{email}: {e}") ``` -------------------------------- ### MX Record Handling Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/ValidatedEmail.md Demonstrates how to retrieve and process MX records for deliverability checks, including fallback mechanisms. ```python from email_validator import validate_email result = validate_email("user@example.com", check_deliverability=True) if result.mx: print("MX records:") for priority, host in result.mx: print(f" Priority {priority}: {host}") if result.mx_fallback_type: print(f"No MX records found; using {result.mx_fallback_type} record as fallback") ``` -------------------------------- ### Display Name Handling Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/ValidatedEmail.md Demonstrates how to parse and access the display name from an email address string. ```python from email_validator import validate_email result = validate_email(""John Doe" ", allow_display_name=True, check_deliverability=False) print(f"Display name: {result.display_name}") # John Doe print(f"Email: {result.normalized}") # john@example.com ``` -------------------------------- ### Using ValidatedEmail Type Hint Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/ValidatedEmail.md Demonstrates how to use the ValidatedEmail type hint for function parameters and return types. This helps in static analysis and improves code readability. Ensure 'email_validator' and 'typing' are imported. ```python from email_validator import validate_email, ValidatedEmail from typing import Optional def process_email(email: str) -> ValidatedEmail: return validate_email(email, check_deliverability=False) def check_domain(email: ValidatedEmail) -> str: return email.ascii_domain def get_mx_if_available(email: ValidatedEmail) -> Optional[list]: return email.mx ``` -------------------------------- ### Internationalized Domain Handling Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/ValidatedEmail.md Shows how to handle internationalized domain names, accessing both Unicode and ASCII (Punycode) versions. ```python from email_validator import validate_email result = validate_email("user@münchen.de", check_deliverability=False) print(f"Unicode domain: {result.domain}") # münchen.de print(f"ASCII domain (Punycode): {result.ascii_domain}") # xn--mnchen-3ya.de print(f"ASCII email: {result.ascii_email}") # user@xn--mnchen-3ya.de # If sending via SMTP, use ascii_email # If storing in database, use normalized ``` -------------------------------- ### Get Brief Representation of ValidatedEmail Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/ValidatedEmail.md The `__repr__()` method provides a concise string representation of the `ValidatedEmail` object, showing the normalized email address. ```python result = validate_email("user@example.com", check_deliverability=False) print(repr(result)) # ``` -------------------------------- ### Get Email Validation Results as Dictionary Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/ValidatedEmail.md Use `as_dict()` to retrieve all attributes of a validated email as a dictionary. The `domain_address` is converted to a string if present. ```python from email_validator import validate_email result = validate_email("user@example.com", check_deliverability=False) data = result.as_dict() print(data) # {'original': 'user@example.com', 'normalized': 'user@example.com', # 'local_part': 'user', 'domain': 'example.com', ...} ``` -------------------------------- ### Release to PyPI Source: https://github.com/joshdata/python-email-validator/blob/main/README.md Executes a script to publish the package distributions to the Python Package Index (PyPI). This command should be run after tagging and pushing the new version. ```sh ./release_to_pypi.sh ``` -------------------------------- ### Configuration Options Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/README.md Details on the global configuration options available for the email-validator library, including `ALLOW_SMTPUTF8` and `CHECK_DELIVERABILITY`. ```APIDOC ## Configuration Options ### Description Provides a list of module-level attributes that can be configured to alter the library's behavior. ### Configurable Attributes - **`ALLOW_SMTPUTF8`** (bool): Whether to allow SMTPUTF8 extensions. - **`CHECK_DELIVERABILITY`** (bool): Whether to perform deliverability checks. - **`TEST_ENVIRONMENT`** (bool): Flag to indicate if running in a test environment. (Other configuration options would be listed here with their descriptions and default values) ``` -------------------------------- ### Handling DNS Timeouts Gracefully Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/caching_resolver.md Demonstrates how to handle potential DNS lookup timeouts when using the caching resolver with a short timeout value. It includes a check for timeout-related errors in the exception message. ```python from email_validator import validate_email, caching_resolver, EmailNotValidError resolver = caching_resolver(timeout=5) # Short timeout email = "user@slow-dns-server.example" try: result = validate_email(email, dns_resolver=resolver) print(f"Valid: {result.normalized}") except EmailNotValidError as e: if "timeout" in str(e).lower(): print("DNS lookup timed out, consider retrying or disabling checks") else: print(f"Validation failed: {e}") ``` -------------------------------- ### Enable Test Environment for Domain Validation Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/configuration.md Set `TEST_ENVIRONMENT` to `True` to permit test domain names like `@test` and `@example.test`. This also automatically disables DNS deliverability checks. ```python import email_validator from email_validator import validate_email # Enable test environment email_validator.TEST_ENVIRONMENT = True # Now test domains are allowed result = validate_email("user@mytestdomain.test") print(result.normalized) # user@mytestdomain.test ``` -------------------------------- ### Configure for Login Forms Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/configuration.md Disables expensive DNS checks globally for login forms to improve performance. Validation will be faster as it skips deliverability queries. ```python import email_validator # Disable expensive DNS checks email_validator.CHECK_DELIVERABILITY = False from email_validator import validate_email result = validate_email(user_email) # Fast, no DNS queries ``` -------------------------------- ### Configure DNS Resolver with Timeout and Cache Source: https://github.com/joshdata/python-email-validator/blob/main/README.md Create a reusable DNS resolver instance with a specified timeout to improve performance when validating multiple email addresses. This instance can be passed to `validate_email` to leverage caching. ```python from email_validator import validate_email, caching_resolver resolver = caching_resolver(timeout=10) while True: validate_email(email, dns_resolver=resolver) ``` -------------------------------- ### Modify Special Use Domain Names List Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/configuration.md Customize the `SPECIAL_USE_DOMAIN_NAMES` list to control which reserved domain names are rejected. This example shows how to temporarily allow the 'test' domain. ```python import email_validator from email_validator import validate_email # Allow the "test" domain in a non-test environment email_validator.SPECIAL_USE_DOMAIN_NAMES.remove("test") result = validate_email("user@test", check_deliverability=False) print(result.normalized) # user@test # Restore the list if needed email_validator.SPECIAL_USE_DOMAIN_NAMES.append("test") ``` -------------------------------- ### as_dict() Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/ValidatedEmail.md Returns the instance attributes as a dictionary. The domain_address field, if present, is converted to its string representation. ```APIDOC ## as_dict() ### Description Returns the instance attributes as a dictionary. The `domain_address` field, if present, is converted to its string representation. ### Method `as_dict()` ### Returns - `dict[str, Any]` - A dictionary containing the attributes of the ValidatedEmail object. ### Example ```python from email_validator import validate_email result = validate_email("user@example.com", check_deliverability=False) data = result.as_dict() print(data) # {'original': 'user@example.com', 'normalized': 'user@example.com', # 'local_part': 'user', 'domain': 'example.com', ...} ``` ``` -------------------------------- ### Type Checking with Email Validation Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/exceptions.md Demonstrates how to use type hints and a try-except block to safely validate an email address, returning either the normalized email or a string representation of the validation error. ```python from email_validator import validate_email, EmailNotValidError from typing import Union def safe_validate(email: str) -> Union[str, str]: """Returns normalized email or error message.""" try: result = validate_email(email, check_deliverability=False) return result.normalized except EmailNotValidError as e: return str(e) ``` -------------------------------- ### Domain Literal Handling Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/ValidatedEmail.md Shows how to validate email addresses with domain literals (IP addresses) and access the numeric IP address. ```python from email_validator import validate_email result = validate_email("user@[192.0.2.1]", allow_domain_literal=True, check_deliverability=False) print(f"Domain: {result.domain}") # [192.0.2.1] print(f"Domain address type: {type(result.domain_address)}") # IPv4Address print(f"Numeric IP: {result.domain_address}") # 192.0.2.1 ``` -------------------------------- ### Tag and Push Git Repository Source: https://github.com/joshdata/python-email-validator/blob/main/README.md Creates a Git tag with the current version number and pushes it to the remote repository. The version is read from `email_validator/version.py`. ```sh git tag v$(cat email_validator/version.py | sed "s/.* = //" | sed 's/"//g') git push --tags ``` -------------------------------- ### File Structure Overview Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/README.md This snippet shows the directory structure of the Python email validator project. It outlines the purpose of each file, aiding in navigation and understanding the project's organization. ```text output/ ├── README.md # This file ├── module-overview.md # Project overview and architecture ├── types.md # Type definitions ├── configuration.md # Global configuration options ├── errors.md # Complete error catalog └── api-reference/ ├── validate_email.md # Main validation function ├── ValidatedEmail.md # Result class ├── exceptions.md # Exception classes └── caching_resolver.md # DNS resolver helper ``` -------------------------------- ### Setting Global Configuration Options Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/validate_email.md Demonstrates how to modify global settings for the email validator library. These settings apply to all validation calls unless overridden locally. Ensure the 'email_validator' library is imported before setting these options. ```python import email_validator # Disable SMTPUTF8 support globally email_validator.ALLOW_SMTPUTF8 = False # Enable check_deliverability by default email_validator.CHECK_DELIVERABILITY = True # Enable test environments globally email_validator.TEST_ENVIRONMENT = True ``` -------------------------------- ### Internationalized Local Part Handling Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/ValidatedEmail.md Illustrates handling internationalized local parts, including when SMTPUTF8 is required and ASCII conversion is not possible. ```python from email_validator import validate_email result = validate_email("ツ@example.com", check_deliverability=False) print(f"Local part: {result.local_part}") # ツ print(f"ASCII local part: {result.ascii_local_part}") # None (SMTPUTF8 required) print(f"SMTPUTF8 required: {result.smtputf8}") # True print(f"ASCII email: {result.ascii_email}") # None (cannot be ASCII) # Database: use result.normalized # Mail relay must support SMTPUTF8 ``` -------------------------------- ### Validate Email with Dynamic Configuration Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/configuration.md Applies context-specific validation settings by temporarily modifying global configuration parameters. Always restore original settings in a finally block to ensure predictable behavior. ```python import email_validator from email_validator import validate_email, EmailNotValidError def validate_user_email(email: str, is_test_env: bool) -> dict: """Validate email with context-aware configuration.""" # Save original settings original_test_env = email_validator.TEST_ENVIRONMENT original_check_deliverability = email_validator.CHECK_DELIVERABILITY try: # Apply context-specific settings email_validator.TEST_ENVIRONMENT = is_test_env email_validator.CHECK_DELIVERABILITY = not is_test_env # Validate result = validate_email(email) return {"valid": True, "normalized": result.normalized} except EmailNotValidError as e: return {"valid": False, "error": str(e)} finally: # Restore original settings email_validator.TEST_ENVIRONMENT = original_test_env email_validator.CHECK_DELIVERABILITY = original_check_deliverability ``` -------------------------------- ### DeliverabilityInfo Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/types.md A TypedDict used internally to represent DNS deliverability check results. All keys are optional. ```APIDOC ## DeliverabilityInfo (TypedDict) ### Description A typed dictionary used internally to represent DNS deliverability check results. All keys are optional (`total=False`), meaning any subset of keys may be present. ### Fields | Field | Type | Description | |-------|------|-------------| | `mx` | `list[tuple[int, str]]` | List of (priority, exchange) tuples representing MX records. Present when MX records are found. Each tuple contains the priority (int) and mail exchange domain name (str). | | `mx_fallback_type` | `Optional[str]` | Either `"A"`, `"AAAA"`, or `None`. Present when an A or AAAA record was used as a fallback instead of an MX record. `None` if MX records were found. | | `unknown-deliverability` | `str` | Present when deliverability could not be determined. Contains either `"no_nameservers"` (all nameservers failed) or `"timeout"` (DNS query timed out). When this key is present, `mx` and `mx_fallback_type` may not be. | ### Usage This type is not directly instantiated by library users; it is returned internally by `validate_email_deliverability()`. However, it may be referenced in type hints for advanced usage. ```python from email_validator.deliverability import validate_email_deliverability, DeliverabilityInfo from typing import Optional def check_deliverability(domain: str) -> Optional[DeliverabilityInfo]: try: result = validate_email_deliverability(domain, domain) return result except Exception: return None ``` ``` -------------------------------- ### Enable Display Name Format Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/configuration.md Permits the RFC 5322 display name format (e.g., "John Doe" ) by setting ALLOW_DISPLAY_NAME to True. It extracts the display name and the normalized email address. ```python import email_validator from email_validator import validate_email # Enable display names email_validator.ALLOW_DISPLAY_NAME = True result = validate_email('"John Doe" ', check_deliverability=False) print(result.display_name) # John Doe print(result.normalized) # john@example.com ``` -------------------------------- ### Basic Field Access Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/ValidatedEmail.md Demonstrates accessing basic email components like normalized, local part, domain, and ASCII domain. ```python from email_validator import validate_email result = validate_email("john.doe+tag@example.com", check_deliverability=False) print(f"Normalized: {result.normalized}") # john.doe+tag@example.com print(f"Local part: {result.local_part}") # john.doe+tag print(f"Domain: {result.domain}") # example.com print(f"ASCII domain: {result.ascii_domain}") # example.com ``` -------------------------------- ### Configure for Internal Services Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/configuration.md Disables the global deliverability check and allows non-standard domains like single-label or special internal domains for internal services. ```python import email_validator # Disable global deliverability check email_validator.GLOBALLY_DELIVERABLE = False # Allow single-label or special domains from email_validator import validate_email result = validate_email("admin@internal") # Single-label domain allowed ``` -------------------------------- ### Batch Email Validation with Caching Resolver Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/DOCUMENTATION-MANIFEST.txt Optimize batch email validation by using a caching DNS resolver. Instantiate the resolver with a specified timeout and pass it to validate_email. ```python from email_validator import caching_resolver resolver = caching_resolver(timeout=10) for email in email_list: result = validate_email(email, dns_resolver=resolver) ``` -------------------------------- ### Configure for Legacy Mail Systems Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/configuration.md Adjusts global settings to disable features not supported by legacy mail systems, such as SMTPUTF8 and quoted local parts. ```python import email_validator # Disable unsupported features email_validator.ALLOW_SMTPUTF8 = False email_validator.ALLOW_QUOTED_LOCAL = False email_validator.ALLOW_DOMAIN_LITERAL = False from email_validator import validate_email result = validate_email(user_email) # Only ASCII, standard formats ``` -------------------------------- ### Global Configuration Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/module-overview.md Module-level configuration variables that control the default behavior of the email validation process. ```APIDOC ## Global Configuration ### Description Module-level configuration variables that control the default behavior of the email validation process. ### Boolean Options - **ALLOW_SMTPUTF8**: Allow non-ASCII local parts. Default: `True` - **ALLOW_EMPTY_LOCAL**: Allow empty local parts (e.g., `@domain.com`). Default: `False` - **ALLOW_QUOTED_LOCAL**: Allow quoted local parts (e.g., `"quoted"@domain.com`). Default: `False` - **ALLOW_DOMAIN_LITERAL**: Allow domain literals (e.g., `[192.0.2.1]`). Default: `False` - **ALLOW_DISPLAY_NAME**: Allow display names (e.g., `"Name" `). Default: `False` - **STRICT**: Enforce additional length checks. Default: `False` - **GLOBALLY_DELIVERABLE**: Require domains with periods. Default: `True` - **CHECK_DELIVERABILITY**: Perform DNS lookups. Default: `True` - **TEST_ENVIRONMENT**: Allow test domains. Default: `False` ### Integer Options - **DEFAULT_TIMEOUT**: DNS timeout in seconds. Default: `15` ### List Options - **SPECIAL_USE_DOMAIN_NAMES**: Reserved domain names to reject. This list can be modified. ### Example ```python import email_validator # Disable deliverability checks globally email_validator.CHECK_DELIVERABILITY = False # Set a custom DNS timeout email_validator.DEFAULT_TIMEOUT = 30 ``` ``` -------------------------------- ### Import Top-Level Components from email_validator Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/API-INDEX.md Import all public functions, classes, exceptions, constants, and global configuration variables directly from the email_validator package. ```python from email_validator import ( # Functions validate_email, caching_resolver, # Classes ValidatedEmail, # Exceptions EmailNotValidError, EmailSyntaxError, EmailUndeliverableError, # Constants __version__, # Global configuration (module-level attributes) ALLOW_SMTPUTF8, ALLOW_EMPTY_LOCAL, ALLOW_QUOTED_LOCAL, ALLOW_DOMAIN_LITERAL, ALLOW_DISPLAY_NAME, STRICT, GLOBALLY_DELIVERABLE, CHECK_DELIVERABILITY, TEST_ENVIRONMENT, DEFAULT_TIMEOUT, SPECIAL_USE_DOMAIN_NAMES, ) ``` -------------------------------- ### Integration with Flask Web Application Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/caching_resolver.md Shows how to integrate the caching resolver into a Flask web application to validate emails submitted via an API endpoint. The resolver is initialized once at application startup for efficiency. ```python from email_validator import validate_email, caching_resolver, EmailNotValidError from flask import Flask, request, jsonify app = Flask(__name__) # Create a cached resolver at application startup dns_resolver = caching_resolver(timeout=10) @app.route('/validate-email', methods=['POST']) def validate(): email = request.json.get('email') try: result = validate_email( email, check_deliverability=True, dns_resolver=dns_resolver ) return jsonify({ 'valid': True, 'normalized': result.normalized, 'domain': result.domain }) except EmailNotValidError as e: return jsonify({ 'valid': False, 'error': str(e) }), 400 ``` -------------------------------- ### __repr__() Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/ValidatedEmail.md Returns a brief representation of the object showing the normalized email. ```APIDOC ## __repr__() ### Description Returns a brief representation of the object showing the normalized email. ### Method `__repr__()` ### Returns - `str` - A string representation of the ValidatedEmail object, typically showing the normalized email address. ### Example ```python result = validate_email("user@example.com", check_deliverability=False) print(repr(result)) # ``` ``` -------------------------------- ### Equality and Comparison Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/api-reference/ValidatedEmail.md The ValidatedEmail class implements __eq__() for testing. Two instances are equal if all relevant fields match. ```APIDOC ## Equality and Comparison ### Description The `ValidatedEmail` class implements `__eq__()` for testing. Two instances are equal if all relevant fields match (original, normalized, local_part, domain, ascii fields, smtputf8, mx records, mx_fallback_type, and display_name). ### Example ```python result1 = validate_email("user@example.com", check_deliverability=False) result2 = validate_email("user@example.com", check_deliverability=False) assert result1 == result2 ``` ``` -------------------------------- ### Special Use Domain Names List Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/errors.md This list contains domains that are typically rejected by default. Ensure `test_environment=True` or manually adjust the list if these domains need to be accepted. ```python ["arpa", "invalid", "local", "localhost", "onion", "test"] ``` -------------------------------- ### caching_resolver() function Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/README.md Documentation for the `caching_resolver()` helper function, which facilitates DNS resolution with caching for multiple validation operations. ```APIDOC ## caching_resolver() ### Description A helper function that provides a DNS resolver with caching capabilities, useful for optimizing multiple email validations. ### Signature `caching_resolver(...)` ### Usage (Information on how to use and configure the caching resolver would be here) ### Return Value (Details on what the function returns, likely a resolver object) ``` -------------------------------- ### Override Global Default for Deliverability Check Source: https://github.com/joshdata/python-email-validator/blob/main/_autodocs/configuration.md Demonstrates how to override the global CHECK_DELIVERABILITY setting for a single email validation call. The global setting remains unchanged for subsequent calls. ```python import email_validator from email_validator import validate_email # Set global default email_validator.CHECK_DELIVERABILITY = True # This call uses the global setting (performs DNS check) result1 = validate_email("user@example.com") # This call overrides the global setting (skips DNS check) result2 = validate_email("user@example.com", check_deliverability=False) # Global setting remains unchanged result3 = validate_email("user@example.com") # Still performs DNS check ```