PYTHON 18
Email.py Guest on 24th September 2020 03:00:20 PM
  1. import re
  2.  
  3. from .utils import validator
  4.  
  5. user_regex = re.compile(
  6.     # dot-atom
  7.     r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+"
  8.     r"(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*$"
  9.     # quoted-string
  10.     r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|'
  11.     r"""\\[\001-\011\013\014\016-\177])*"$)""",
  12.     re.IGNORECASE
  13. )
  14. domain_regex = re.compile(
  15.     # domain
  16.     r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
  17.     r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?$)'
  18.     # literal form, ipv4 address (SMTP 4.1.3)
  19.     r'|^\[(25[0-5]|2[0-4]\d|[0-1]?\d?\d)'
  20.     r'(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\]$',
  21.     re.IGNORECASE)
  22. domain_whitelist = ['localhost']
  23.  
  24.  
  25. @validator
  26. def email(value, whitelist=None):
  27.     """
  28.    Validate an email address.
  29.  
  30.    This validator is based on `Django's email validator`_. Returns
  31.    ``True`` on success and :class:`~validators.utils.ValidationFailure`
  32.    when validation fails.
  33.  
  34.    Examples::
  35.  
  36.        >>> email('[email protected]')
  37.        True
  38.  
  39.        >>> email('[email protected]@')
  40.        ValidationFailure(func=email, ...)
  41.  
  42.    .. _Django's email validator:
  43.       https://github.com/django/django/blob/master/django/core/validators.py
  44.  
  45.    .. versionadded:: 0.1
  46.  
  47.    :param value: value to validate
  48.    :param whitelist: domain names to whitelist
  49.  
  50.    :copyright: (c) Django Software Foundation and individual contributors.
  51.    :license: BSD
  52.    """
  53.  
  54.     if whitelist is None:
  55.         whitelist = domain_whitelist
  56.  
  57.     if not value or '@' not in value:
  58.         return False
  59.  
  60.     user_part, domain_part = value.rsplit('@', 1)
  61.  
  62.     if not user_regex.match(user_part):
  63.         return False
  64.  
  65.     if domain_part not in whitelist and not domain_regex.match(domain_part):
  66.         # Try for possible IDN domain-part
  67.         try:
  68.             domain_part = domain_part.encode('idna').decode('ascii')
  69.             return domain_regex.match(domain_part)
  70.         except UnicodeError:
  71.             return False
  72.     return True

Paste is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.