使用Python分解电子邮件地址

4

我正在尝试找到最清晰的方法来解析电子邮件头。

Python的类https://docs.python.org/3/library/email.message.html允许访问诸如email['To']之类的标头。

这是类型为_UniqueAddressHeader,在https://docs.python.org/3/library/email.headerregistry.html中声明。

email['To']似乎没有公开的方法,并且始终返回复合字符串。

我尝试使用明确创建Address类型的方式:

mailTo = email.headerregistry.Address(mail['To'])

然而,这样做并不能正确地构成对象——所有字符都被吞掉到“display_name”属性中,这不是我们所需要的。
编辑:这是我的自定义函数,可能需要更加健壮以处理诸如不匹配的<>等错误。
def addressSplit(e):
    """
    :param e: email.header
    :return: displayName, localpart, domainpart str
    """
    s = str(e)
    displayName = ''
    openB = s.find('<')
    closeB = s.find('>')
    if openB>=0 and closeB>=0:
        displayName = s[:openB].strip(' ')
        s = s[openB+1:closeB].strip(' ')        # this is the address part
    localpart, domainpart = s.split('@')
    return displayName, localpart, domainpart
1个回答

4
头部通过其地址属性公开地址详细信息。

给定此消息:

>>> from email.message import EmailMessage
>>> from email.headerregistry import Address
>>> msg = EmailMessage()
>>> msg['to'] = [Address('Jane Smith', 'jane.smith', 'example.com'), Address('John Smith', 'john.smith', 'example.com')]
>>> print(msg)
to: Jane Smith <jane.smith@example.com>, John Smith <john.smith@example.com>

地址可以看作是这样的:
>>> to = msg['to']
>>> to
'Jane Smith <jane.smith@example.com>, John Smith <john.smith@example.com>'
>>> type(to)
<class 'email.headerregistry._UniqueAddressHeader'>
>>> to.addresses
(Address(display_name='Jane Smith', username='jane.smith', domain='example.com'), Address(display_name='John Smith', username='john.smith', domain='example.com'))

可以通过索引访问单个地址:

>>> jane = to.addresses[0]
>>> jane.display_name
'Jane Smith'
>>> jane.username
'jane.smith'
>>> jane.domain
'example.com'
>>> jane.
jane.addr_spec     jane.display_name  jane.domain        jane.username      
>>> jane.addr_spec
'jane.smith@example.com'
>>> str(jane)
'Jane Smith <jane.smith@example.com>'

解析器似乎可以处理格式不正确的标头:

>>> from email.parser import Parser
>>> from email.policy import default

>>> # Malformed address (missing '>')
>>> s = 'to: Jane Smith <jane.smith@example.com, John Smith <john.smith@example.com>'


>>> p = Parser(policy=default)
>>> msg = p.parsestr(s)
>>> to = msg['to']
>>> to.addresses
(Address(display_name='Jane Smith', username='jane.smith', domain='example.com'), Address(display_name='John Smith', username='john.smith', domain='example.com'))
>>> 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接