提取收到的电子邮件:带有Python电子邮件包的邮件头

2024-10-01 17:36:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从邮件中提取FinalReceived:email头。我收到了从email.message_from_file()返回的消息。在

使用Message.get()Message.get_item()方法不能保证我将得到许多Received:headers中的哪一个。Message.get_all()返回它们全部,但不保证顺序。有没有办法保证拿到最后一个?在


Tags: 方法from消息messageget顺序email邮件
3条回答

Received:标题的时间戳:

Received: from lb-ex1.int.icgroup.com (localhost [127.0.0.1])
by lb-ex1.localdomain (Postfix) with ESMTP id D6BDB1E26393
for <hd1@example.com>; Fri, 12 Dec 2014 12:09:24 -0500 (EST)

{{1}你可以看看这个列表是怎么做的:

^{pr2}$

如果它不起作用,请留下评论,我很乐意进一步调查。在

email.parserHeaderParser实现了一个类似字典的接口,但实际上似乎是按您期望的顺序返回头。在

from email.parser import HeaderParser

headers = HeaderParser().parse(open_filehandle, headersonly=True)
for key, value in headers.items():
    if key == 'Received':
        ... do things with the value

^{} method有一个姐妹^{} method,它接受字节字符串而不是类似文件的对象。在

如果你所说的“final”是指“最新的”,那么它将是第一个与if相匹配的,所以你可以在阅读完后break。如果所说的“final”意味着其他东西,那么可以在if中以任何你认为合适的方式实现它。在

这是改编自this answer to a related question。在

在Python3.6.7中,get_all()方法的注释明确指出,返回值的顺序与消息中的顺序相同,因此messageInstance.get_all('Received')应该可以正常工作。在

def get_all(self, name, failobj=None):
    """Return a list of all the values for the named field.

    These will be sorted in the order they appeared in the original
    message, and may contain duplicates.  Any fields deleted and
    re-inserted are always appended to the header list.

    If no such fields exist, failobj is returned (defaults to None).
    """

相关问题 更多 >

    热门问题