Exemple #1
0
def normalize_email_address(email: str) -> NormalizedEmailAddress:
    """Normalize an email address.

    Returns a `NormalizedEmailAddress` object.

    Raises:
        BadEmailAddress: if the address is syntactically unacceptable
        InvalidEmailDomain: if the domain name is syntactically invalid

    """
    # Remove any surrounding whitespace
    email = email.strip()

    # Split the address
    try:
        local_part, domain = email.rsplit('@', 1)
    except ValueError:
        raise BadEmailAddress(email)

    # Lowercase and encode the domain name
    try:
        domain = domain.lower().encode('idna').decode()
    except UnicodeError as e:
        raise InvalidEmailDomain(email, domain, e)

    # Check the syntax and length of the address
    email = local_part + '@' + domain
    if not EMAIL_RE.match(email) or len(email) > 320:
        # The length limit is from https://tools.ietf.org/html/rfc3696#section-3
        raise BadEmailAddress(email)

    return str.__new__(NormalizedEmailAddress, email)
Exemple #2
0
def normalize_email_address(email):
    """Normalize an email address.

    Returns:
        str: the normalized email address

    Raises:
        BadEmailAddress: if the address appears to be invalid
        BadEmailDomain: if the domain name is invalid

    """
    # Remove any surrounding whitespace
    email = email.strip()

    # Split the address
    try:
        local_part, domain = email.rsplit('@', 1)
    except ValueError:
        raise BadEmailAddress(email)

    # Lowercase and encode the domain name
    try:
        domain = domain.lower().encode('idna').decode()
    except UnicodeError:
        raise BadEmailDomain(domain)

    # Check the syntax and length of the address
    email = local_part + '@' + domain
    if not EMAIL_RE.match(email) or len(email) > 320:
        # The length limit is from https://tools.ietf.org/html/rfc3696#section-3
        raise BadEmailAddress(email)

    # Check that the domain has at least one MX record
    if website.app_conf.check_email_domains:
        try:
            DNS.query(domain, 'MX')
        except DNSException:
            raise BadEmailDomain(domain)
        except Exception as e:
            website.tell_sentry(e, {})

    return email