我想解析To:
电子邮件字段中的电子邮件地址。
确实,当在mbox中的电子邮件上循环时:
mbox = mailbox.mbox('test.mbox')
for m in mbox:
print m['To']
我们可以得到类似的东西:
info@test.org, Blahblah <blah@test.com>, <another@blah.org>, "Hey" <last@one.com>
应解析为:
[{email: "info@test.org", name: ""},
{email: "blah@test.com", name: "Blahblah"},
{email: "another@blah.org", name: ""},
{email: "last@one.com", name: "Hey"}]
是否有内置(在mailbox
或其他模块中)的内容或其他内容?
我读过几次this doc,但我找不到相关内容。
答案 0 :(得分:2)
您可以使用email.utils.getaddresses()
:
>>> getaddresses(['info@test.org, Blahblah <blah@test.com>, <another@blah.org>, "Hey" <last@one.com>'])
[('', 'info@test.org'), ('Blahblah', 'blah@test.com'), ('', 'another@blah.org'), ('Hey', 'last@one.com')]
(请注意,该函数需要一个列表,因此您必须将该字符串括在[...]
中。)
答案 1 :(得分:1)
email.parser
包含您正在寻找的模块。 email.message
仍然相关,因为解析器将使用此结构返回消息,因此您将从中获取标头数据。但实际上读取中的文件,email.parser
是可行的方法。
答案 2 :(得分:1)
正如@TheSpooniest指出的,email
有一个解析器:
import email
s = 'info@test.org, Blahblah <blah@test.com>, <another@blah.org>, "Hey" <last@one.com>'
for em in s.split(','):
print email.utils.parseaddr(em)
给出:
('', 'info@test.org')
('Blahblah', 'blah@test.com')
('', 'another@blah.org')
('Hey', 'last@one.com')
答案 3 :(得分:0)
Python提供 email.Header.decode_header()用于解码标头。该函数解码每个原子并返回一个元组列表(文本,编码),您仍需要解码和连接以获取全文。
对于地址,Python提供了 email.utils.getaddresses(),它将地址拆分为元组列表(显示名称,地址)。 display-name也需要解码,地址必须与RFC2822语法匹配。功能 getmailaddresses()完成所有工作。
这是一个可能有助于http://blog.magiksys.net/parsing-email-using-python-header
的教程