authentik.lib.utils.email

Email utility functions

  1"""Email utility functions"""
  2
  3from email.utils import parseaddr
  4
  5Address = str | tuple[str, str] | list[str | tuple[str, str]] | None
  6
  7
  8def _normalize_single_address(item: str | tuple[str, str] | list[str]) -> tuple[str, str]:
  9    """Normalize a single address into a (name, email) tuple."""
 10    if isinstance(item, tuple | list):
 11        if len(item) != 2:  # noqa: PLR2004
 12            raise ValueError("Address tuple must be in the form (name, email)")
 13        name, email = item
 14        return (str(name or "").strip(), str(email or "").strip())
 15    if isinstance(item, str):
 16        # Only parse RFC 5322 style addresses ("Name <email>"), plain addresses are kept as-is
 17        # so that unusual but valid addresses are not mangled by parseaddr
 18        if "<" in item and item.rstrip().endswith(">"):
 19            name, email = parseaddr(item)
 20            if email:
 21                return (name.strip(), email.strip())
 22        return ("", item.strip())
 23    raise ValueError("Address must be a string or a (name, email) tuple")
 24
 25
 26def normalize_addresses(addr: Address) -> list[tuple[str, str]] | None:
 27    """Normalize email address parameter to list of (name, email) tuples.
 28
 29    Args:
 30        addr: Email address(es). Can be:
 31            - None: Returns None
 32            - Single email string: "user@example.com"
 33            - Formatted address string: "John Doe <user@example.com>"
 34            - (name, email) tuple: ("John Doe", "user@example.com")
 35            - List of any of the above
 36
 37    Returns:
 38        List of (name, email) tuples suitable for TemplateEmailMessage, or None
 39
 40    Raises:
 41        ValueError: If address list is empty or addr is not a valid type
 42    """
 43    if addr is None:
 44        return None
 45    if isinstance(addr, str | tuple):
 46        return [_normalize_single_address(addr)]
 47    if isinstance(addr, list):
 48        if not addr:
 49            raise ValueError("Address list cannot be empty")
 50        return [_normalize_single_address(item) for item in addr]
 51    raise ValueError("Address must be a string, a (name, email) tuple, or a list of those")
 52
 53
 54def mask_email(email: str | None) -> str | None:
 55    """Mask email address for privacy
 56
 57    Args:
 58        email: Email address to mask
 59    Returns:
 60        Masked email address or None if input is None
 61    Example:
 62        mask_email("myname@company.org")
 63        'm*****@c******.org'
 64    """
 65    if not email:
 66        return None
 67
 68    # Basic email format validation
 69    if email.count("@") != 1:
 70        raise ValueError("Invalid email format: Must contain exactly one '@' symbol")
 71
 72    local, domain = email.split("@")
 73    if not local or not domain:
 74        raise ValueError("Invalid email format: Local and domain parts cannot be empty")
 75
 76    domain_parts = domain.split(".")
 77    if len(domain_parts) < 2:  # noqa: PLR2004
 78        raise ValueError("Invalid email format: Domain must contain at least one dot")
 79
 80    limit = 2
 81
 82    # Mask local part (keep first char)
 83    if len(local) <= limit:
 84        masked_local = "*" * len(local)
 85    else:
 86        masked_local = local[0] + "*" * (len(local) - 1)
 87
 88    # Mask each domain part except the last one (TLD)
 89    masked_domain_parts = []
 90    for _i, part in enumerate(domain_parts[:-1]):  # Process all parts except TLD
 91        if not part:  # Check for empty parts (consecutive dots)
 92            raise ValueError("Invalid email format: Domain parts cannot be empty")
 93        if len(part) <= limit:
 94            masked_part = "*" * len(part)
 95        else:
 96            masked_part = part[0] + "*" * (len(part) - 1)
 97        masked_domain_parts.append(masked_part)
 98
 99    # Add TLD unchanged
100    if not domain_parts[-1]:  # Check if TLD is empty
101        raise ValueError("Invalid email format: TLD cannot be empty")
102    masked_domain_parts.append(domain_parts[-1])
103
104    return f"{masked_local}@{'.'.join(masked_domain_parts)}"
Address = str | tuple[str, str] | list[str | tuple[str, str]] | None
def normalize_addresses( addr: str | tuple[str, str] | list[str | tuple[str, str]] | None) -> list[tuple[str, str]] | None:
27def normalize_addresses(addr: Address) -> list[tuple[str, str]] | None:
28    """Normalize email address parameter to list of (name, email) tuples.
29
30    Args:
31        addr: Email address(es). Can be:
32            - None: Returns None
33            - Single email string: "user@example.com"
34            - Formatted address string: "John Doe <user@example.com>"
35            - (name, email) tuple: ("John Doe", "user@example.com")
36            - List of any of the above
37
38    Returns:
39        List of (name, email) tuples suitable for TemplateEmailMessage, or None
40
41    Raises:
42        ValueError: If address list is empty or addr is not a valid type
43    """
44    if addr is None:
45        return None
46    if isinstance(addr, str | tuple):
47        return [_normalize_single_address(addr)]
48    if isinstance(addr, list):
49        if not addr:
50            raise ValueError("Address list cannot be empty")
51        return [_normalize_single_address(item) for item in addr]
52    raise ValueError("Address must be a string, a (name, email) tuple, or a list of those")

Normalize email address parameter to list of (name, email) tuples.

Args: addr: Email address(es). Can be: - None: Returns None - Single email string: "user@example.com" - Formatted address string: "John Doe user@example.com" - (name, email) tuple: ("John Doe", "user@example.com") - List of any of the above

Returns: List of (name, email) tuples suitable for TemplateEmailMessage, or None

Raises: ValueError: If address list is empty or addr is not a valid type

def mask_email(email: str | None) -> str | None:
 55def mask_email(email: str | None) -> str | None:
 56    """Mask email address for privacy
 57
 58    Args:
 59        email: Email address to mask
 60    Returns:
 61        Masked email address or None if input is None
 62    Example:
 63        mask_email("myname@company.org")
 64        'm*****@c******.org'
 65    """
 66    if not email:
 67        return None
 68
 69    # Basic email format validation
 70    if email.count("@") != 1:
 71        raise ValueError("Invalid email format: Must contain exactly one '@' symbol")
 72
 73    local, domain = email.split("@")
 74    if not local or not domain:
 75        raise ValueError("Invalid email format: Local and domain parts cannot be empty")
 76
 77    domain_parts = domain.split(".")
 78    if len(domain_parts) < 2:  # noqa: PLR2004
 79        raise ValueError("Invalid email format: Domain must contain at least one dot")
 80
 81    limit = 2
 82
 83    # Mask local part (keep first char)
 84    if len(local) <= limit:
 85        masked_local = "*" * len(local)
 86    else:
 87        masked_local = local[0] + "*" * (len(local) - 1)
 88
 89    # Mask each domain part except the last one (TLD)
 90    masked_domain_parts = []
 91    for _i, part in enumerate(domain_parts[:-1]):  # Process all parts except TLD
 92        if not part:  # Check for empty parts (consecutive dots)
 93            raise ValueError("Invalid email format: Domain parts cannot be empty")
 94        if len(part) <= limit:
 95            masked_part = "*" * len(part)
 96        else:
 97            masked_part = part[0] + "*" * (len(part) - 1)
 98        masked_domain_parts.append(masked_part)
 99
100    # Add TLD unchanged
101    if not domain_parts[-1]:  # Check if TLD is empty
102        raise ValueError("Invalid email format: TLD cannot be empty")
103    masked_domain_parts.append(domain_parts[-1])
104
105    return f"{masked_local}@{'.'.join(masked_domain_parts)}"

Mask email address for privacy

Args: email: Email address to mask Returns: Masked email address or None if input is None Example: mask_email("myname@company.org") 'm*****@c******.org'