Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
提取收到的电子邮件:使用Python电子邮件包提取邮件头_Python_Email - Fatal编程技术网

提取收到的电子邮件:使用Python电子邮件包提取邮件头

提取收到的电子邮件:使用Python电子邮件包提取邮件头,python,email,Python,Email,我想从邮件中提取最终接收到的电子邮件标题。我收到了从电子邮件返回的消息。Message\u from\u file() 使用Message.get()或Message.get\u item()方法无法保证我将获得许多已接收的标题中的哪一个:标题Message.get_all()返回所有内容,但不保证订单。是否有办法保证获得最后一个?已收到:标题有时间戳: Received: from lb-ex1.int.icgroup.com (localhost [127.0.0.1]) by lb-ex1

我想从邮件中提取最终接收到的电子邮件标题。我收到了从
电子邮件返回的消息。Message\u from\u file()


使用
Message.get()
Message.get\u item()
方法无法保证我将获得许多已接收的标题中的哪一个:标题
Message.get_all()
返回所有内容,但不保证订单。是否有办法保证获得最后一个?

已收到:
标题有时间戳:

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)

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

电子邮件解析器类
HeaderParser
实现了一个类似于字典的接口,但实际上它似乎按照您期望的顺序返回标题

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
有一个接受字节字符串而不是类似文件的对象的姐妹

如果“final”是指“newest”,那么它将是第一个与
If
匹配的,因此您可以在阅读后简单地
break
。如果“final”是指其他内容,则可以在
If
中以您认为合适的任何方式实现它


这是根据python 3.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).
    """

你为什么需要最后的头球?头的顺序肯定不重要吗?@接收到的
头的顺序是否重要:
头指示消息通过处理它的各个服务器的顺序。最后一个指示消息(假定)起源的服务器。(当然,它们可以伪造。)然而,正如hd1在其回复中指出的,它们也有时间戳,所以我可以使用这些信息。谢谢,我真傻,竟然忘了我可以使用时间戳。:)但请记住,在现实世界中,并非所有服务器的时钟都是精确的。我很确定头的顺序比时间戳可靠得多。此外,在现实世界中,许多服务器对
接收的
头使用奇怪的格式,这些格式不能保证是机器可读的或有用的。
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).
    """