本文整理匯總了Python中email.utils.getaddresses方法的典型用法代碼示例。如果您正苦於以下問題:Python utils.getaddresses方法的具體用法?Python utils.getaddresses怎麽用?Python utils.getaddresses使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類email.utils
的用法示例。
在下文中一共展示了utils.getaddresses方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: addr_header_encode
# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def addr_header_encode(text, header_name=None):
"""Encode and line-wrap the value of an email header field containing
email addresses."""
# Convert to unicode, if required.
if not isinstance(text, unicode):
text = unicode(text, "utf-8")
text = ", ".join(
formataddr((header_encode(name), emailaddr))
for name, emailaddr in getaddresses([text])
)
if is_ascii(text):
charset = "ascii"
else:
charset = "utf-8"
return Header(
text, header_name=header_name, charset=Charset(charset)
).encode()
示例2: forbid_multi_line_headers
# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def forbid_multi_line_headers(name, val, encoding):
"""Forbids multi-line headers, to prevent header injection."""
encoding = encoding or settings.DEFAULT_CHARSET
val = force_text(val)
if '\n' in val or '\r' in val:
raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name))
try:
val.encode('ascii')
except UnicodeEncodeError:
if name.lower() in ADDRESS_HEADERS:
val = ', '.join(sanitize_address(addr, encoding)
for addr in getaddresses((val,)))
else:
val = Header(val, encoding).encode()
else:
if name.lower() == 'subject':
val = Header(val).encode()
return str(name), val
示例3: forbid_multi_line_headers
# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def forbid_multi_line_headers(name, val, encoding):
"""Forbids multi-line headers, to prevent header injection."""
if '\n' in val or '\r' in val:
raise BadHeaderError(
"Header values can't contain newlines (got %r for header %r)" %
(val, name))
try:
val.encode('ascii')
except UnicodeEncodeError:
if name.lower() in ADDRESS_HEADERS:
val = ', '.join(sanitize_address(addr, encoding)
for addr in getaddresses((val,)))
else:
val = Header(val, encoding).encode()
else:
if name.lower() == 'subject':
val = Header(val).encode()
return str(name), val
示例4: parse_email_addresses
# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def parse_email_addresses(raw_header: str) -> (dict,):
"""
Parse email addresses from header
:param raw_header: example: '=?UTF-8?B?0J7Qu9C1=?= <name@company.ru>,\r\n "\'\\"z, z\\"\'" <imap.tools@ya.ru>'
:return: tuple(dict(name: str, email: str, full: str))
"""
result = []
for raw_name, email in getaddresses([raw_header]):
name = decode_value(*decode_header(raw_name)[0]).strip()
email = email.strip()
if not (name or email):
continue
result.append({
'email': email if '@' in email else '',
'name': name,
'full': '{} <{}>'.format(name, email) if name and email else name or email
})
return tuple(result)
示例5: clean_addresses
# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def clean_addresses(emails):
"""Takes a string of emails and returns a list of tuples of name/address
pairs that are symanticly valid"""
# Parse our string of emails, discarding invalid/illegal addresses
valid_emails_list = address.parse_list(emails)
# If no valid email addresses are found, return an empty list
if not valid_emails_list:
return []
# If we have valid emails, use flanker's unicode address list creator to
# give us something to pass to Python's email library's getaddresses
valid_emails = valid_emails_list.to_unicode()
# Return a list, in ('Name', 'email@dj.local')] form, the resulting emails
email_list = getaddresses([valid_emails])
# Lowercase all the email addresses in the list
lowered_list = [(name, email.lower()) for name, email in email_list]
return lowered_list
示例6: set_recipients
# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def set_recipients(self, name, value):
self.unset_all(name)
for pair in getaddresses([value]):
self.add(name, formataddr(pair))
示例7: send
# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def send(self, lines, to_addrs):
try:
if self.username or self.password:
self.smtp.login(self.username, self.password)
msg = "".join(lines)
# turn comma-separated list into Python list if needed.
if is_string(to_addrs):
to_addrs = [
email for (name, email) in getaddresses([to_addrs])
]
self.smtp.sendmail(self.envelopesender, to_addrs, msg)
except smtplib.SMTPResponseException:
err = sys.exc_info()[1]
self.environment.get_logger().error(
"*** Error sending email ***\n"
"*** Error %d: %s\n"
% (err.smtp_code, bytes_to_str(err.smtp_error))
)
try:
smtp = self.smtp
# delete the field before quit() so that in case of
# error, self.smtp is deleted anyway.
del self.smtp
smtp.quit()
except:
self.environment.get_logger().error(
"*** Error closing the SMTP connection ***\n"
"*** Exiting anyway ... ***\n"
"*** %s\n" % sys.exc_info()[1]
)
sys.exit(1)
示例8: test_getaddresses
# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def test_getaddresses(self):
eq = self.assertEqual
eq(utils.getaddresses(['aperson@dom.ain (Al Person)',
'Bud Person <bperson@dom.ain>']),
[('Al Person', 'aperson@dom.ain'),
('Bud Person', 'bperson@dom.ain')])
示例9: test_getaddresses_nasty
# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def test_getaddresses_nasty(self):
eq = self.assertEqual
eq(utils.getaddresses(['foo: ;']), [('', '')])
eq(utils.getaddresses(
['[]*-- =~$']),
[('', ''), ('', ''), ('', '*--')])
eq(utils.getaddresses(
['foo: ;', '"Jason R. Mastaler" <jason@dom.ain>']),
[('', ''), ('Jason R. Mastaler', 'jason@dom.ain')])
示例10: test_getaddresses_embedded_comment
# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def test_getaddresses_embedded_comment(self):
"""Test proper handling of a nested comment"""
eq = self.assertEqual
addrs = utils.getaddresses(['User ((nested comment)) <foo@bar.com>'])
eq(addrs[0][1], 'foo@bar.com')
示例11: addrs
# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def addrs(raw_addrs):
items = []
# TODO remove the cleaner!
# raw_addrs = [clean_string(convert_encoded(s.lower()),[EXPR_OPTS['fix_utf8'],(r'\t', ';'), (r'\n', ';') ]) for s in raw_addrs]
# arr = [clean_string(s.lower(), [EXPR_OPTS['fix_utf8'], (r'\t', ';'), (r'\n', ';') ]) for s in arr]
utf8_addrs = [convert_encoded(raw_addr) for raw_addr in raw_addrs]
for name, addr in getaddresses(utf8_addrs):
if u'@' in addr:
items.append(addr)
elif u'@' in name:
items.append(name)
return ([clean_string(s.lower(), [(r'\'', u'')]) for s in items], utf8_addrs)
示例12: format_addresses
# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def format_addresses(addrs, remove_empty=False):
if isinstance(addrs, basestring):
addrs = [addrs]
pairs = getaddresses(addrs)
if remove_empty:
pairs = [(x, y) for (x, y) in pairs if x or y]
# FIXME: Use encoding after getaddresses
return ", ".join(map(formataddr, pairs))
示例13: clean_recipients
# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def clean_recipients(recipients):
recipients = [addr for (name, addr) in getaddresses(recipients)]
return filter(None, (x.strip() for x in recipients))
示例14: addresses
# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def addresses(txt):
addrs = [
{
'addr': a[1].lower(),
'name': address_name(a),
'title': '"{}" <{}>'.format(*a) if a[0] else a[1],
'hash': hashlib.md5(a[1].strip().lower().encode()).hexdigest(),
} for a in getaddresses([txt])
]
return addrs
示例15: _get_addresses
# 需要導入模塊: from email import utils [as 別名]
# 或者: from email.utils import getaddresses [as 別名]
def _get_addresses(self, address_data, retain_name=False):
"""
Takes RFC-compliant email addresses in both terse (email only)
and verbose (name + email) forms and returns a list of
email address strings
(TODO: breaking change that returns a tuple of (name, email) per string)
"""
if retain_name:
raise NotImplementedError(
"Not yet implemented, but will need client-code changes too"
)
# We trust than an email address contains an "@" after
# email.utils.getaddresses has done the hard work. If we wanted
# to we could use a regex to check for greater email validity
# NB: getaddresses expects a list, so ensure we feed it appropriately
if isinstance(address_data, str):
if "[" not in address_data:
# Definitely turn these into a list
# NB: this is pretty assumptive, but still prob OK
address_data = [address_data]
output = [x[1] for x in getaddresses(address_data) if "@" in x[1]]
return output