本文整理汇总了Python中email.utils.parseaddr方法的典型用法代码示例。如果您正苦于以下问题:Python utils.parseaddr方法的具体用法?Python utils.parseaddr怎么用?Python utils.parseaddr使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类email.utils
的用法示例。
在下文中一共展示了utils.parseaddr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parseaddr_unicode
# 需要导入模块: from email import utils [as 别名]
# 或者: from email.utils import parseaddr [as 别名]
def parseaddr_unicode(addr) -> (str, str):
"""Like parseaddr but return name in unicode instead of in RFC 2047 format
'=?UTF-8?B?TmjGoW4gTmd1eeG7hW4=?= <abcd@gmail.com>' -> ('Nhơn Nguyễn', "abcd@gmail.com")
"""
name, email = parseaddr(addr)
email = email.strip().lower()
if name:
name = name.strip()
decoded_string, charset = decode_header(name)[0]
if charset is not None:
try:
name = decoded_string.decode(charset)
except UnicodeDecodeError:
LOG.warning("Cannot decode addr name %s", name)
name = ""
else:
name = decoded_string
return name, email
示例2: _parse_recipients
# 需要导入模块: from email import utils [as 别名]
# 或者: from email.utils import parseaddr [as 别名]
def _parse_recipients(self, message, recipients):
rcpts = []
recipient_vars = getattr(message, 'recipient_vars', {})
for addr in recipients:
rcpt = {}
to_name, to_email = parseaddr(sanitize_address(addr, message.encoding))
if to_name:
rcpt['Name'] = to_name
if to_email:
rcpt['Email'] = to_email
if recipient_vars.get(addr):
rcpt['Vars'] = recipient_vars.get(addr)
rcpts.append(rcpt)
return rcpts
示例3: sanitize_address
# 需要导入模块: from email import utils [as 别名]
# 或者: from email.utils import parseaddr [as 别名]
def sanitize_address(addr, encoding):
if isinstance(addr, six.string_types):
addr = parseaddr(force_text(addr))
nm, addr = addr
# This try-except clause is needed on Python 3 < 3.2.4
# http://bugs.python.org/issue14291
try:
nm = Header(nm, encoding).encode()
except UnicodeEncodeError:
nm = Header(nm, 'utf-8').encode()
try:
addr.encode('ascii')
except UnicodeEncodeError: # IDN
if '@' in addr:
localpart, domain = addr.split('@', 1)
localpart = str(Header(localpart, encoding))
domain = domain.encode('idna').decode('ascii')
addr = '@'.join([localpart, domain])
else:
addr = Header(addr, encoding).encode()
return formataddr((nm, addr))
示例4: send_email
# 需要导入模块: from email import utils [as 别名]
# 或者: from email.utils import parseaddr [as 别名]
def send_email(msg_to, msg_subject, msg_body, msg_from=None,
smtp_server='localhost', envelope_from=None,
headers={}):
if not msg_from:
msg_from = app.config['EMAIL_FROM']
if not envelope_from:
envelope_from = parseaddr(msg_from)[1]
msg = MIMEText(msg_body)
msg['Subject'] = Header(msg_subject)
msg['From'] = msg_from
msg['To'] = msg_to
msg['Date'] = formatdate()
msg['Message-ID'] = make_msgid()
msg['Errors-To'] = envelope_from
if request:
msg['X-Submission-IP'] = request.remote_addr
s = smtplib.SMTP(smtp_server)
s.sendmail(envelope_from, msg_to, msg.as_string())
s.close()
示例5: validate_address
# 需要导入模块: from email import utils [as 别名]
# 或者: from email.utils import parseaddr [as 别名]
def validate_address(address):
"""
Validate C{address} as defined in RFC 2822.
:param address: The address to be validated.
:type address: str
@return: A valid address.
@rtype: str
@raise smtp.SMTPBadRcpt: Raised if C{address} is invalid.
"""
leap_assert_type(address, str)
# in the following, the address is parsed as described in RFC 2822 and
# ('', '') is returned if the parse fails.
_, address = parseaddr(address)
if address == '':
raise smtp.SMTPBadRcpt(address)
return address
#
# String manipulation
#
示例6: normalize_email_address
# 需要导入模块: from email import utils [as 别名]
# 或者: from email.utils import parseaddr [as 别名]
def normalize_email_address(email_address):
"""Returns a normalized version of email address. Returns None if the address cannot be parsed."""
name, address = parseaddr(email_address)
if address is None:
return None
address = address.strip()
while address and address.startswith('<'):
address = address[1:]
while address and address.endswith('>'):
address = address[:-1]
if not address:
return None
return address.lower()
示例7: test_email_notification_reply_to_has_thread_id
# 需要导入模块: from email import utils [as 别名]
# 或者: from email.utils import parseaddr [as 别名]
def test_email_notification_reply_to_has_thread_id(self):
user = VerifiedUserFactory()
user2 = VerifiedUserFactory()
group = GroupFactory(members=[user, user2])
conversation = Conversation.objects.get_or_create_for_target(group)
mail.outbox = []
with execute_scheduled_tasks_immediately():
message = ConversationMessage.objects.create(author=user, conversation=conversation, content='asdf')
reply_to = parseaddr(mail.outbox[0].reply_to[0])[1]
local_part = reply_to.split('@')[0]
conversation_id, user_id, thread_id = parse_local_part(local_part)
self.assertEqual(conversation_id, conversation.id)
self.assertEqual(user_id, user2.id)
self.assertEqual(thread_id, message.id)
示例8: __init__
# 需要导入模块: from email import utils [as 别名]
# 或者: from email.utils import parseaddr [as 别名]
def __init__(self, value):
if not isinstance(value, six.text_type):
raise TypeError("value must be a unicode string")
name, address = parseaddr(value)
parts = address.split(u"@")
if name or not address:
# parseaddr has found a name (e.g. Name <email>) or the entire
# value is an empty string.
raise ValueError("Invalid rfc822name value")
elif len(parts) == 1:
# Single label email name. This is valid for local delivery.
# No IDNA encoding needed since there is no domain component.
encoded = address.encode("ascii")
else:
# A normal email of the form user@domain.com. Let's attempt to
# encode the domain component and reconstruct the address.
encoded = parts[0].encode("ascii") + b"@" + idna.encode(parts[1])
self._value = value
self._encoded = encoded
示例9: __init__
# 需要导入模块: from email import utils [as 别名]
# 或者: from email.utils import parseaddr [as 别名]
def __init__(self, value):
if isinstance(value, six.text_type):
try:
value.encode("ascii")
except UnicodeEncodeError:
value = self._idna_encode(value)
warnings.warn(
"RFC822Name values should be passed as an A-label string. "
"This means unicode characters should be encoded via "
"idna. Support for passing unicode strings (aka U-label) "
"will be removed in a future version.",
utils.DeprecatedIn21,
stacklevel=2,
)
else:
raise TypeError("value must be string")
name, address = parseaddr(value)
if name or not address:
# parseaddr has found a name (e.g. Name <email>) or the entire
# value is an empty string.
raise ValueError("Invalid rfc822name value")
self._value = value
示例10: __init__
# 需要导入模块: from email import utils [as 别名]
# 或者: from email.utils import parseaddr [as 别名]
def __init__(self, value):
if isinstance(value, six.text_type):
try:
value.encode("ascii")
except UnicodeEncodeError:
value = self._idna_encode(value)
warnings.warn(
"RFC822Name values should be passed as an A-label string. "
"This means unicode characters should be encoded via "
"idna. Support for passing unicode strings (aka U-label) "
"will be removed in a future version.",
utils.PersistentlyDeprecated2017,
stacklevel=2,
)
else:
raise TypeError("value must be string")
name, address = parseaddr(value)
if name or not address:
# parseaddr has found a name (e.g. Name <email>) or the entire
# value is an empty string.
raise ValueError("Invalid rfc822name value")
self._value = value
示例11: quoteaddr
# 需要导入模块: from email import utils [as 别名]
# 或者: from email.utils import parseaddr [as 别名]
def quoteaddr(addr):
"""
Turn an email address, possibly with realname part etc, into
a form suitable for and SMTP envelope.
"""
if isinstance(addr, Address):
return b'<' + bytes(addr) + b'>'
if isinstance(addr, bytes):
addr = addr.decode('ascii')
res = parseaddr(addr)
if res == (None, None):
# It didn't parse, use it as-is
return b'<' + bytes(addr) + b'>'
else:
return b'<' + res[1].encode('ascii') + b'>'
示例12: sanitize_address
# 需要导入模块: from email import utils [as 别名]
# 或者: from email.utils import parseaddr [as 别名]
def sanitize_address(addr, encoding):
if isinstance(addr, str):
addr = parseaddr(addr)
nm, addr = addr
nm = Header(nm, encoding).encode()
try:
addr.encode('ascii')
except UnicodeEncodeError: # IDN
if '@' in addr:
localpart, domain = addr.split('@', 1)
localpart = str(Header(localpart, encoding))
domain = domain.encode('idna').decode('ascii')
addr = '@'.join([localpart, domain])
else:
addr = Header(addr, encoding).encode()
return formataddr((nm, addr))
示例13: test_parseaddr_preserves_quoted_pairs_in_addresses
# 需要导入模块: from email import utils [as 别名]
# 或者: from email.utils import parseaddr [as 别名]
def test_parseaddr_preserves_quoted_pairs_in_addresses(self):
# issue 10005. Note that in the third test the second pair of
# backslashes is not actually a quoted pair because it is not inside a
# comment or quoted string: the address being parsed has a quoted
# string containing a quoted backslash, followed by 'example' and two
# backslashes, followed by another quoted string containing a space and
# the word 'example'. parseaddr copies those two backslashes
# literally. Per rfc5322 this is not technically correct since a \ may
# not appear in an address outside of a quoted string. It is probably
# a sensible Postel interpretation, though.
eq = self.assertEqual
eq(utils.parseaddr('""example" example"@example.com'),
('', '""example" example"@example.com'))
eq(utils.parseaddr('"\\"example\\" example"@example.com'),
('', '"\\"example\\" example"@example.com'))
eq(utils.parseaddr('"\\\\"example\\\\" example"@example.com'),
('', '"\\\\"example\\\\" example"@example.com'))
示例14: __init__
# 需要导入模块: from email import utils [as 别名]
# 或者: from email.utils import parseaddr [as 别名]
def __init__(self, email: str, label: str):
# TODO: how to check the email easily ?
if not isinstance(email, str) or not 0 < _bytes_size(email) < 255:
raise ValueError("Invalid email address")
if not isinstance(label, str) or not 0 < _bytes_size(label) < 255:
raise ValueError("Invalid label")
parsed_label, parsed_email = parseaddr(str(self))
if parsed_email != email:
raise ValueError("Invalid email address")
if parsed_label != label:
raise ValueError("Invalid label")
# No need to call super().__init__ given namedtuple set attributes during __new__
super().__init__()
示例15: sanitize_address
# 需要导入模块: from email import utils [as 别名]
# 或者: from email.utils import parseaddr [as 别名]
def sanitize_address(addr, encoding='utf-8'):
if isinstance(addr, str):
addr = parseaddr(force_text(addr))
nm, addr = addr
try:
nm = Header(nm, encoding).encode()
except UnicodeEncodeError:
nm = Header(nm, 'utf-8').encode()
try:
addr.encode('ascii')
except UnicodeEncodeError: # IDN
if '@' in addr:
localpart, domain = addr.split('@', 1)
try:
localpart = Header(localpart, encoding).encode()
except UnicodeEncodeError:
localpart = Header(localpart, 'utf-8').encode()
domain = domain.encode('idna').decode('ascii')
addr = '@'.join([localpart, domain])
else:
addr = Header(addr, encoding).encode()
return formataddr((nm, addr))