1 # -*- coding: UTF-8 -*- |
|
2 # Copyright (c) 2008 - 2010, Pascal Volk |
|
3 # See COPYING for distribution information. |
|
4 |
|
5 """Virtual Mail Manager's EmailAddress class to handle e-mail addresses.""" |
|
6 |
|
7 from __main__ import re, ERR |
|
8 from Exceptions import VMMEmailAddressException as VMMEAE |
|
9 import VirtualMailManager as VMM |
|
10 |
|
11 RE_LOCALPART = """[^\w!#$%&'\*\+-\.\/=?^_`{\|}~]""" |
|
12 |
|
13 class EmailAddress(object): |
|
14 __slots__ = ('_localpart', '_domainname') |
|
15 def __init__(self, address): |
|
16 self._localpart = None |
|
17 self._domainname = None |
|
18 self.__chkAddress(address) |
|
19 |
|
20 def __eq__(self, other): |
|
21 if isinstance(other, self.__class__): |
|
22 return self._localpart == other._localpart\ |
|
23 and self._domainname == other._domainname |
|
24 return NotImplemented |
|
25 |
|
26 def __ne__(self, other): |
|
27 if isinstance(other, self.__class__): |
|
28 return self._localpart != other._localpart\ |
|
29 or self._domainname != other._domainname |
|
30 return NotImplemented |
|
31 |
|
32 def __repr__(self): |
|
33 return "EmailAddress('%s@%s')" % (self._localpart, self._domainname) |
|
34 |
|
35 def __str__(self): |
|
36 return "%s@%s" % (self._localpart, self._domainname) |
|
37 |
|
38 def __chkAddress(self, address): |
|
39 try: |
|
40 localpart, domain = address.split('@') |
|
41 except ValueError: |
|
42 raise VMMEAE(_(u"Missing '@' sign in e-mail address “%s”.") % |
|
43 address, ERR.INVALID_ADDRESS) |
|
44 except AttributeError: |
|
45 raise VMMEAE(_(u"“%s” doesn't look like an e-mail address.") % |
|
46 address, ERR.INVALID_ADDRESS) |
|
47 if len(domain) > 0: |
|
48 domain = VMM.VirtualMailManager.chkDomainname(domain) |
|
49 else: |
|
50 raise VMMEAE(_(u"Missing domain name after “%s@”.") % |
|
51 localpart, ERR.DOMAIN_NO_NAME) |
|
52 localpart = self.__chkLocalpart(localpart) |
|
53 self._localpart, self._domainname = localpart, domain |
|
54 |
|
55 def __chkLocalpart(self, localpart): |
|
56 """Validates the local-part of an e-mail address. |
|
57 |
|
58 Arguments: |
|
59 localpart -- local-part of the e-mail address that should be validated (str) |
|
60 """ |
|
61 if len(localpart) < 1: |
|
62 raise VMMEAE(_(u'No local-part specified.'), |
|
63 ERR.LOCALPART_INVALID) |
|
64 if len(localpart) > 64: |
|
65 raise VMMEAE(_(u'The local-part “%s” is too long') % |
|
66 localpart, ERR.LOCALPART_TOO_LONG) |
|
67 ic = set(re.findall(RE_LOCALPART, localpart)) |
|
68 if len(ic): |
|
69 ichrs = '' |
|
70 for c in ic: |
|
71 ichrs += u"“%s” " % c |
|
72 raise VMMEAE(_(u"The local-part “%(lpart)s” contains invalid\ |
|
73 characters: %(ichrs)s") % {'lpart': localpart, 'ichrs': ichrs}, |
|
74 ERR.LOCALPART_INVALID) |
|
75 return localpart |
|
76 |
|