当前位置: 首页>>代码示例>>Python>>正文


Python utils.parseaddr方法代码示例

本文整理汇总了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 
开发者ID:simple-login,项目名称:app,代码行数:21,代码来源:email_utils.py

示例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 
开发者ID:kidig,项目名称:django-mailjet,代码行数:20,代码来源:backends.py

示例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)) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:23,代码来源:message.py

示例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() 
开发者ID:hadleyrich,项目名称:GerbLook,代码行数:27,代码来源:utils.py

示例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
# 
开发者ID:leapcode,项目名称:bitmask-dev,代码行数:25,代码来源:utils.py

示例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() 
开发者ID:IntegralDefense,项目名称:ACE,代码行数:20,代码来源:email.py

示例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) 
开发者ID:yunity,项目名称:karrot-backend,代码行数:18,代码来源:test_models.py

示例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 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:23,代码来源:general_name.py

示例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 
开发者ID:tp4a,项目名称:teleport,代码行数:26,代码来源:general_name.py

示例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 
开发者ID:tp4a,项目名称:teleport,代码行数:26,代码来源:general_name.py

示例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'>' 
开发者ID:wistbean,项目名称:learn_python3_spider,代码行数:21,代码来源:smtp.py

示例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)) 
开发者ID:quantmind,项目名称:lux,代码行数:18,代码来源:message.py

示例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')) 
开发者ID:IronLanguages,项目名称:ironpython3,代码行数:19,代码来源:test_email.py

示例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__() 
开发者ID:Scille,项目名称:parsec-cloud,代码行数:18,代码来源:types.py

示例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)) 
开发者ID:briancappello,项目名称:flask-unchained,代码行数:25,代码来源:flask_mail.py


注:本文中的email.utils.parseaddr方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。