# coding:utf-8
-'''
+"""
Public interface for flanker address (email or url) parsing and validation
capabilities.
EmailAddress or UrlAddress in flanker.addresslib.address.
See the parser.py module for implementation details of the parser.
-'''
+"""
import time
import flanker.addresslib.parser
@metrics_wrapper()
def parse(address, addr_spec_only=False, metrics=False):
- '''
+ """
Given an string, returns a scalar object representing a single full
mailbox (display name and addr-spec), addr-spec, or a url.
>>> print address.parse('foo')
None
- '''
+ """
mtimes = {'parsing': 0}
parser = flanker.addresslib.parser._AddressParser(False)
@metrics_wrapper()
def parse_list(address_list, strict=False, as_tuple=False, metrics=False):
- '''
+ """
Given an string or list of email addresses and/or urls seperated by a
delimiter (comma (,) or semi-colon (;)), returns an AddressList object
(an iterable list representing parsed email addresses and urls).
>>> address.parse_list('A <a@b>, D <d@e>, http://localhost')
[A <a@b>, D <d@e>, http://localhost]
- '''
+ """
mtimes = {'parsing': 0}
parser = flanker.addresslib.parser._AddressParser(strict)
@metrics_wrapper()
def validate_address(addr_spec, metrics=False):
- '''
+ """
Given an addr-spec, runs the pre-parser, the parser, DNS MX checks,
MX existence checks, and if available, ESP specific grammar for the
local part.
>>> address.validate_address('user.1234@gmail.com')
user.1234@gmail.com
- '''
+ """
mtimes = {'parsing': 0, 'mx_lookup': 0,
'dns_lookup': 0, 'mx_conn':0 , 'custom_grammar':0}
@metrics_wrapper()
def validate_list(addr_list, as_tuple=False, metrics=False):
- '''
+ """
Validates an address list, and returns a tuple of parsed and unparsed
portions.
>>> address.validate_address_list('a@b, c@d, e@example.com', as_tuple=True)
([a@mailgun.com, c@mailgun.com], ['e@example.com'])
- '''
+ """
mtimes = {'parsing': 0, 'mx_lookup': 0,
'dns_lookup': 0, 'mx_conn':0 , 'custom_grammar':0}
-
if addr_list is None:
return None, mtimes
class Address(object):
- '''
+ """
Base class that represents an address (email or URL). Use it to create
concrete instances of different addresses:
- '''
+ """
@property
def supports_routing(self):
- "Indicates that by default this address cannot be routed"
+ """
+ Indicates that by default this address cannot be routed.
+ """
return False
-
class Type(object):
- '''
+ """
Enumerates the types of addresses we support:
>>> parse('foo@example.com').addr_type
'email'
>>> parse('http://example.com').addr_type
'url'
- '''
+ """
Email = 'email'
Url = 'url'
class EmailAddress(Address):
- '''
+ """
Represents a fully parsed email address with built-in support for MIME
encoding. Note, do not use EmailAddress class directly, use the parse()
or parse_list() functions to return a scalar or iterable list respectively.
And full email spec is 100% ASCII, encoded for MIME:
>>> addr.full_spec()
'Bob Silva <bob@host.com>'
- '''
+ """
__slots__ = ['display_name', 'mailbox', 'hostname', 'address']
self.addr_type = self.Type.Email
def __repr__(self):
- '''
+ """
>>> repr(EmailAddress("John Smith", "john@smith.com"))
'John Smith <john@smith.com>'
- '''
+ """
return self.full_spec()
def __str__(self):
- '''
+ """
>>> str(EmailAddress("boo@host.com"))
'boo@host.com'
- '''
+ """
return self.address
@property
def supports_routing(self):
- "Email addresses can be routed"
+ """
+ Email addresses can be routed.
+ """
return True
@property
self._display_name = value
def full_spec(self):
- '''
+ """
Returns a full spec of an email address. Always in ASCII, RFC-2822
compliant, safe to be included into MIME:
'Ev K <ev@host.com>'
>>> EmailAddress("Жека", "ev@example.com").full_spec()
'=?utf-8?b?0JbQtdC60LA=?= <ev@example.com>'
- '''
+ """
if self._display_name:
return '{0} <{1}>'.format(self._display_name, self.address)
return u'{0}'.format(self.address)
def to_unicode(self):
- "Converts to unicode"
+ """
+ Converts to unicode.
+ """
if self.display_name:
return u'{0} <{1}>'.format(self.display_name, self.address)
return u'{0}'.format(self.address)
return True
def __eq__(self, other):
- "Allows comparison of two addresses"
+ """
+ Allows comparison of two addresses.
+ """
if other:
if isinstance(other, basestring):
other = parse(other)
return False
def __hash__(self):
- '''
+ """
Hashing allows using Address objects as keys in collections and compare
them in sets
>>> s.add(b)
>>> len(s)
1
- '''
+ """
return hash(self.address.lower())
-
class UrlAddress(Address):
- '''
+ """
Represents a parsed URL:
>>> url = UrlAddress("http://user@host.com:8080?q=a")
>>> url.hostname
Note: do not create UrlAddress class directly by passing raw "internet
data", use the parse() and parse_list() functions instead.
- '''
+ """
__slots__ = ['address', 'parse_result']
def to_unicode(self):
return self.address
- def __str__(self):
- return self.address
-
def __repr__(self):
return self.address
class AddressList(object):
- '''
+ """
Keeps the list of addresses. Each address is an EmailAddress or
URLAddress objectAddress-derived object.
False
>>> "bob@host.COM" in al
True
- '''
+ """
def __init__(self, container=None):
if container is None:
return len(self.container)
def __eq__(self, other):
- "When comparing ourselves to other lists we must ignore order"
+ """
+ When comparing ourselves to other lists we must ignore order.
+ """
if isinstance(other, list):
other = parse_list(other)
return set(self.container) == set(other.container)
- def __str__(self):
- return ''.join(['[', self.full_spec(), ']'])
-
def __repr__(self):
return ''.join(['[', self.full_spec(), ']'])
def __add__(self, other):
- "Adding two AddressLists together yields another AddressList"
+ """
+ Adding two AddressLists together yields another AddressList.
+ """
if isinstance(other, list):
result = self.container + parse_list(other).container
else:
return AddressList(result)
def full_spec(self, delimiter=", "):
- '''
+ """
Returns a full string which looks pretty much what the original was
like
>>> adl = AddressList("Foo <foo@host.com>, Bar <bar@host.com>")
>>> adl.full_spec(delimiter='; ')
'Foo <foo@host.com; Bar <bar@host.com>'
- '''
+ """
return delimiter.join(addr.full_spec() for addr in self.container)
def to_unicode(self, delimiter=u", "):
@property
def addresses(self):
- '''
+ """
Returns a list of just addresses, i.e. no names:
>>> adl = AddressList("Foo <foo@host.com>, Bar <bar@host.com>")
>>> adl.addresses
['foo@host.com', 'bar@host.com']
- '''
+ """
return [addr.address for addr in self.container]
def __str__(self):
@property
def hostnames(self):
- "Returns a set of hostnames used in addresses in this list"
+ """
+ Returns a set of hostnames used in addresses in this list.
+ """
return set([addr.hostname for addr in self.container])
@property
def addr_types(self):
- "Returns a set of address types used in addresses in this list"
+ """
+ Returns a set of address types used in addresses in this list.
+ """
return set([addr.addr_type for addr in self.container])
-
-
-
# coding:utf-8
-'''
+"""
Spelling corrector library, used to correct common typos in domains like
gmal.com instead of gmail.com.
if no suggestion exists.
[1] http://xlinux.nist.gov/dads/HTML/ratcliffObershelp.html
-'''
+"""
import difflib
def suggest(word, cutoff=0.77):
- '''
+ """
Given a domain and a cutoff heuristic, suggest an alternative or return the
original domain if no suggestion exists.
- '''
+ """
if word in LOOKUP_TABLE:
return LOOKUP_TABLE[word]
# coding:utf-8
-'''
+"""
_AddressParser is an implementation of a recursive descent parser for email
addresses and urls. While _AddressParser can be used directly it is not
recommended, use the the parse() and parse_list() methods which are provided
is 64 + 1 + 253 = 318 characters. Allow 194 characters for a display
name and the (very generous) limit becomes 512 characters. Allow 1024
mailboxes and the total limit on a mailbox-list is 524288 characters.
-'''
+"""
import re
import flanker.addresslib.address
class _AddressParser(object):
- '''
+ """
Do not use _AddressParser directly because it heavily relies on other
private classes and methods and it's interface is not guarenteed, it
will change in the future and possibly break your application.
Instead use the parse() and parse_list() functions in the address.py
module which will always return a scalar or iterable respectively.
- '''
+ """
def __init__(self, strict=False):
self.stream = None
self.strict = strict
def address_list(self, stream):
- '''
+ """
Extract a mailbox and/or url list from a stream of input, operates in
strict and relaxed modes.
- '''
+ """
# sanity check
if not stream:
raise ParserException('No input provided to parser.')
return self._address_list_relaxed()
def address(self, stream):
- '''
+ """
Extract a single address or url from a stream of input, always
operates in strict mode.
- '''
+ """
# sanity check
if not stream:
raise ParserException('No input provided to parser.')
return None
def address_spec(self, stream):
- '''
+ """
Extract a single address spec from a stream of input, always
operates in strict mode.
- '''
+ """
# sanity check
if stream is None:
raise ParserException('No input provided to parser.')
def _mailbox_post_processing_checks(self, address):
- "Additional post processing checks to ensure mailbox is valid."
+ """
+ Additional post processing checks to ensure mailbox is valid.
+ """
parts = address.split('@')
# check if local part is less than 1024 octets, the actual
return True
def _address_list_relaxed(self):
- "Grammar: address-list-relaxed -> address { delimiter address }"
+ """
+ Grammar: address-list-relaxed -> address { delimiter address }
+ """
#addrs = []
addrs = flanker.addresslib.address.AddressList()
unparsable = []
return addrs, unparsable
def _address_list_strict(self):
- "Grammar: address-list-strict -> address { delimiter address }"
+ """
+ Grammar: address-list-strict -> address { delimiter address }
+ """
#addrs = []
addrs = flanker.addresslib.address.AddressList()
return addrs
def _address(self):
- "Grammar: address -> name-addr-rfc | name-addr-lax | addr-spec | url"
+ """
+ Grammar: address -> name-addr-rfc | name-addr-lax | addr-spec | url
+ """
start_pos = self.stream.position
addr = self._name_addr_rfc() or self._name_addr_lax() or \
return addr
def _url(self):
- "Grammar: url -> url"
+ """
+ Grammar: url -> url
+ """
earl = self.stream.get_token(URL)
if earl is None:
return None
return flanker.addresslib.address.UrlAddress(to_utf8(earl))
def _name_addr_rfc(self):
- "Grammar: name-addr-rfc -> [ display-name-rfc ] angle-addr-rfc"
+ """
+ Grammar: name-addr-rfc -> [ display-name-rfc ] angle-addr-rfc
+ """
start_pos = self.stream.position
# optional displayname
return flanker.addresslib.address.EmailAddress(None, aaddr)
def _display_name_rfc(self):
- "Grammar: display-name-rfc -> [ whitespace ] word { whitespace word }"
+ """
+ Grammar: display-name-rfc -> [ whitespace ] word { whitespace word }
+ """
wrds = []
# optional whitespace
return cleanup_display_name(''.join(wrds))
def _angle_addr_rfc(self):
- '''
- Grammar: angle-addr-rfc -> [ whitespace ] < addr-spec > [ whitespace ]"
- '''
+ """
+ Grammar: angle-addr-rfc -> [ whitespace ] < addr-spec > [ whitespace ]
+ """
start_pos = self.stream.position
# optional whitespace
return aspec
def _name_addr_lax(self):
- "Grammar: name-addr-lax -> [ display-name-lax ] angle-addr-lax"
+ """
+ Grammar: name-addr-lax -> [ display-name-lax ] angle-addr-lax
+ """
start_pos = self.stream.position
# optional displayname
return flanker.addresslib.address.EmailAddress(None, aaddr)
def _display_name_lax(self):
- '''
+ """
Grammar: display-name-lax ->
- [ whitespace ] word { whitespace word } whitespace"
- '''
+ [ whitespace ] word { whitespace word } whitespace
+ """
start_pos = self.stream.position
wrds = []
return cleanup_display_name(''.join(wrds))
def _angle_addr_lax(self):
- "Grammar: angle-addr-lax -> addr-spec [ whitespace ]"
+ """
+ Grammar: angle-addr-lax -> addr-spec [ whitespace ]
+ """
start_pos = self.stream.position
# addr-spec
return aspec
def _addr_spec(self, as_string=False):
- '''
+ """
Grammar: addr-spec -> [ whitespace ] local-part @ domain [ whitespace ]
- '''
+ """
start_pos = self.stream.position
# optional whitespace
return flanker.addresslib.address.EmailAddress(None, aspec)
def _local_part(self):
- "Grammar: local-part -> dot-atom | quoted-string"
+ """
+ Grammar: local-part -> dot-atom | quoted-string
+ """
return self.stream.get_token(DOT_ATOM) or \
self.stream.get_token(QSTRING)
def _domain(self):
- "Grammar: domain -> dot-atom"
+ """
+ Grammar: domain -> dot-atom
+ """
return self.stream.get_token(DOT_ATOM)
def _word(self):
- "Grammar: word -> word-ascii | word-unicode"
+ """
+ Grammar: word -> word-ascii | word-unicode
+ """
start_pos = self.stream.position
# ascii word
return self._word_unicode()
def _word_ascii(self):
- "Grammar: word-ascii -> atom | qstring"
+ """
+ Grammar: word-ascii -> atom | qstring
+ """
wrd = self.stream.get_token(RELAX_ATOM) or self.stream.get_token(QSTRING)
if wrd and not contains_control_chars(wrd):
return wrd
return None
def _word_unicode(self):
- "Grammar: word-unicode -> unicode-atom | unicode-qstring"
+ """
+ Grammar: word-unicode -> unicode-atom | unicode-qstring
+ """
start_pos = self.stream.position
# unicode atom
def _whitespace(self):
- "Grammar: whitespace -> whitespace-ascii | whitespace-unicode"
+ """
+ Grammar: whitespace -> whitespace-ascii | whitespace-unicode
+ """
return self._whitespace_ascii() or self._whitespace_unicode()
def _whitespace_ascii(self):
- "Grammar: whitespace-ascii -> whitespace-ascii"
+ """
+ Grammar: whitespace-ascii -> whitespace-ascii
+ """
return self.stream.get_token(WHITESPACE)
def _whitespace_unicode(self):
- "Grammar: whitespace-unicode -> whitespace-unicode"
+ """
+ Grammar: whitespace-unicode -> whitespace-unicode
+ """
uwhite = self.stream.get_token(UNI_WHITE)
if uwhite and not is_pure_ascii(uwhite):
return uwhite
class ParserException(Exception):
- '''
+ """
Exception raised when the parser encounters some parsing exception.
- '''
+ """
def __init__(self, reason='Unknown parser error.'):
self.reason = reason
# coding:utf-8
-'''
+"""
TokenStream represents a stream of tokens that a parser will consume.
TokenStream can be used to consume tokens, peek ahead, and synchonize to a
delimiter token. The tokens that the token stream operates on are either
compiled regular expressions or strings.
-'''
+"""
import re
''', re.MULTILINE | re.VERBOSE | re.UNICODE)
class TokenStream(object):
- '''
+ """
Represents the stream of tokens that the parser will consume. The token
stream can be used to consume tokens, peek ahead, and synchonize to a
delimiter token.
When the strem reaches its end, the position is placed
at one plus the position of the last token.
- '''
+ """
def __init__(self, stream):
self.position = 0
self.stream = stream
def get_token(self, token, ngroup=None):
- '''
+ """
Get the next token from the stream and advance the stream. Token can
be either a compiled regex or a string.
- '''
+ """
# match single character
if isinstance(token, basestring) and len(token) == 1:
if self.peek() == token:
return None
def end_of_stream(self):
- '''
+ """
Check if the end of the stream has been reached, if it has, returns
True, otherwise false.
- '''
+ """
if self.position >= len(self.stream):
return True
return False
def synchronize(self):
- '''
+ """
Advances the stream to synchronizes to the delimiter token. Used primarily
in relaxed mode parsing.
- '''
+ """
start_pos = self.position
end_pos = len(self.stream)
return skip
def peek(self, token=None):
- '''
+ """
Peek at the stream to see what the next token is or peek for a
specific token.
- '''
+ """
# peek at whats next in the stream
if token is None:
if self.position < len(self.stream):
# coding:utf-8
-'''
+"""
Validation module that that supports alternate spelling suggestions for
domains, MX record lookup and query, as well as custom local-part grammar for
large ESPs.
* connect_to_mail_exchanger(mx_hosts)
Attempts to connect to a given mail exchanger to see if it exists.
-'''
+"""
import re
import redis
def suggest_alternate(addr_spec):
- '''
+ """
Given an addr-spec, suggests a alternate addr-spec if common spelling
mistakes are detected in the domain portion.
None
>>> validate.suggest_alternate('john@gmail..com')
'john@gmail.com'
- '''
+ """
# sanity check
if addr_spec is None:
return None
def preparse_address(addr_spec):
- '''
+ """
Preparses email addresses. Used to handle odd behavior by ESPs.
- '''
+ """
# sanity check, ensure we have both local-part and domain
parts = addr_spec.split('@')
if len(parts) < 2:
def plugin_for_esp(mail_exchanger):
- '''
+ """
Checks if custom grammar exists for a particular mail exchanger. If
a grammar is found, the plugin to validate an address for that particular
email service provider is returned, otherwise None is returned.
If you are adding the grammar for a email service provider, add the module
to the flanker.addresslib.plugins directory then update the
flanker.addresslib package to add it to the known list of custom grammars.
- '''
+ """
for grammar in flanker.addresslib.CUSTOM_GRAMMAR_LIST:
if grammar[0].match(mail_exchanger):
return grammar[1]
@metrics_wrapper()
def mail_exchanger_lookup(domain, metrics=False):
- '''
+ """
Looks up the mail exchanger for a domain. If MX records exist they will
be returned, if not it will attempt to fallback to A records, if neither
exist None will be returned.
- '''
+ """
mtimes = {'mx_lookup': 0, 'dns_lookup': 0, 'mx_conn': 0}
mx_cache = flanker.addresslib.mx_cache
def lookup_exchanger_in_cache(domain):
- '''
+ """
Uses a cache to store the results of the mail exchanger lookup to speed
up lookup times. The default is redis, but this can be overidden by your
own cache as long as it conforms to the same interface as that of a dict.
See the implimentation of the redis cache in the flanker.addresslib.driver
package for more details if you wish to implement your own cache.
- '''
+ """
mx_cache = flanker.addresslib.mx_cache
lookup = mx_cache[domain]
def lookup_domain(domain):
- '''
+ """
The dnspython package is used for dns lookups. The dnspython package uses
the dns server specified by your operating system. Just like the cache,
this can be overridden by your own dns lookup method of choice as long
as it conforms to the same interface as that of a dict. See the the
implimentation of the dnspython lookup in the flanker.addresslib.driver
package for more details.
- '''
+ """
dns_lookup = flanker.addresslib.dns_lookup
def connect_to_mail_exchanger(mx_hosts):
- '''
+ """
Given a list of MX hosts, attempts to connect to at least one on port 25.
Returns the mail exchanger it was able to connect to or None.
- '''
+ """
for host in mx_hosts:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)