使用python和多个已接收记录进行电子邮件解析的问题

时间:2010-11-12 02:30:30

标签: python parsing email

我正在尝试使用python email.parser解析电子邮件。当我的电子邮件包含多个已接收记录时,email.parser似乎忽略了这些记录。

例如,输入:

...
Received: from localhost (jalapeno [127.0.0.1])
    by jmason.org (Postfix) with ESMTP id 5C4E816F6D
    for <jm@localhost>; Sun,  6 Oct 2002 22:54:39 +0100 (IST)
Received: from jalapeno [127.0.0.1]
    by localhost with IMAP (fetchmail-5.9.0)
    for jm@localhost (single-drop); Sun, 06 Oct 2002 22:54:39 +0100 (IST)
...

输出是:

...
Received ::: from localhost (jalapeno [127.0.0.1])
    by jmason.org (Postfix) with ESMTP id 5C4E816F6D
    for <jm@localhost>; Sun,  6 Oct 2002 22:54:39 +0100 (IST)
Received ::: from localhost (jalapeno [127.0.0.1])
    by jmason.org (Postfix) with ESMTP id 5C4E816F6D
    for <jm@localhost>; Sun,  6 Oct 2002 22:54:39 +0100 (IST)
...

我正在使用以下python代码

import email
f = open('email.txt', 'r')
data = f.read()
e = email.message_from_string(data)
for i in e.keys():
    print i, ':::', e[i]

这是email.parser的错误吗?

你建议任何其他电子邮件解析python库吗?

1 个答案:

答案 0 :(得分:2)

email.__getitem__()的{​​{3}}说:

  

请注意,如果出现指定的字段   不止一次在消息中   标题,究竟是哪些字段   将返回未定义的值。   使用get_all()方法获取   所有现存名称的值   头。

所以,使用e.get_all(i)而不是e [i]来获取Received:标题的所有值。