PurpleVermont PurpleVermont - 4 years ago 109
Python Question

extracting email Received: headers with Python email package

I'd like to extract the Final Received: email header from a message. I have the Message as returned from


Using the
methods don't guarantee which of the many Received: headers I will get.
returns them all, but doesn't guarantee an order. Is there a way to be guaranteed to get the last one?

hd1 hd1
Answer Source

Received: headers are timestamped:

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

So, do messageInstance.get_all() and sort the resulting list however you see fit, an example of how to do this:

import email.utils
import operator
def sort_key(received_header):
    received_date = email.utils.parsedate_tz(received_header)
    return received_date


If it doesn't work, do leave a comment and I'll be happy to look into it further.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download