解析电子邮件头部Cc字段的文本方法?
我有一个Cc头字段的纯文本,内容如下:
friend@email.com, John Smith <john.smith@email.com>,"Smith, Jane" <jane.smith@uconn.edu>
有没有经过实践检验的模块可以正确解析这个内容?
(如果是用Python写的就更好了!因为我知道的邮件模块只会返回原始文本,没有分割的方法)
(如果能把名字和地址分成两个字段,那就更棒了)
4 个回答
0
下面的内容完全没必要。我写这段话的时候还没意识到你可以给 getaddresses()
传一个包含多个地址的单个字符串列表。
我还没机会查看电子邮件头部地址的规范,不过根据你提供的字符串,这段代码应该能把它分割成一个列表,并确保在引号内的逗号(因此是名字的一部分)被忽略。
from email.utils import getaddresses
addrstring = ',friend@email.com, John Smith <john.smith@email.com>,"Smith, Jane" <jane.smith@uconn.edu>,'
def addrparser(addrstring):
addrlist = ['']
quoted = False
# ignore comma at beginning or end
addrstring = addrstring.strip(',')
for char in addrstring:
if char == '"':
# toggle quoted mode
quoted = not quoted
addrlist[-1] += char
# a comma outside of quotes means a new address
elif char == ',' and not quoted:
addrlist.append('')
# anything else is the next letter of the current address
else:
addrlist[-1] += char
return getaddresses(addrlist)
print addrparser(addrstring)
结果是:
[('', 'friend@email.com'), ('John Smith', 'john.smith@email.com'),
('Smith, Jane', 'jane.smith@uconn.edu')]
我很想知道其他人是怎么解决这个问题的!
0
我自己没用过,但看起来你可以很简单地使用csv这个包来解析数据。
17
有很多函数可以作为标准的Python模块使用,但我觉得你可能在寻找 email.utils.parseaddr() 或者 email.utils.getaddresses() 这两个函数。
>>> addresses = 'friend@email.com, John Smith <john.smith@email.com>,"Smith, Jane" <jane.smith@uconn.edu>'
>>> email.utils.getaddresses([addresses])
[('', 'friend@email.com'), ('John Smith', 'john.smith@email.com'), ('Smith, Jane', 'jane.smith@uconn.edu')]