Repository navigation
Expand file tree
/
Copy pathemailaddress.py
More file actions
112 lines (87 loc) · 3.14 KB
/
Copy pathemailaddress.py
File metadata and controls
112 lines (87 loc) · 3.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
from collections.abc import Iterable
import pyparsing as pp
# parsing rule for email addresses
_mailaddress = pp.Regex(r"[a-zA-Z0-9._%+-]+@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,6}")
class EmailAddress:
"""Name and email address type
"""
def __init__(self, *args):
"""Create/parse name + email address combination
Arguments:
-- name, email
First argument is name, second email
-- emailstring
Parsed for "name <email@org.x>",
otherwise parsed as email address
"""
if len(args) == 2 and args[1]:
try:
self.name = args[0]
self.email = _mailaddress.parse_string(args[1], True)[0]
except pp.ParseException:
raise ValueError(f"Cannot get email address from {args[1]}")
# no person, no email email address, return None
elif not args[0]:
self.name = ''
self.email = None
# try to parse email address and name from args[0]
elif '<' in args[0] and args[0].strip()[-1] == '>':
try:
self.name = args[0].split('<')[0].strip()
self.email = _mailaddress.parse_string(
args[0].split('<')[1][:-1].strip())
except pp.ParseException:
raise ValueError(f"Cannot get email address from {args[0]}")
else:
try:
self.email = _mailaddress.parse_string(args[0], True)[0]
self.name = self.email
except pp.ParseException:
raise ValueError(f"Cannot get email address from {args[0]}")
def __str__(self):
if self.name:
return f"{self.name} <{self.email}>"
return self.email or ''
def getEmail(self):
return self.email
def parseEmails(*args, single=False):
res = []
if args[0] is None:
args = ('', *args[1:])
# here, assume the e-mail is in the args[1]
if len(args) == 2 and args[1]:
# Equal number of names and email addresses
if args[0].count(',') == args[1].count(','):
for name, email in zip(args[0].split(','), args[1].split(',')):
res.append(EmailAddress(name, email))
# One name, possibly multiple email addresses
elif ',' not in args[0]:
for email in args[1].split(','):
res.append(EmailAddress(args[0], email))
# Only one email address
else:
res.append(EmailAddress(*args))
# assume all in the first string
else:
for name_email in args[0].split(','):
res.append(EmailAddress(name_email))
# return only the first name/email
if single and res:
if len(res) > 1:
print(f"Warning, ignoring emails {res[1:]}")
return res[0]
elif single:
return None
return res
def addressEmails(mails: Iterable[EmailAddress]):
"""Convert email into printable string
Parameters
----------
mails : Iterable[EmailAddress]
Mails to convert
Returns
-------
str
Comma-separated list of name+email address
"""
return ', '.join(map(str, mails))