On 2014-05-05, Tim Chase <python.l...@tim.thechases.com> wrote: > On 2014-05-05 20:58, Grant Edwards wrote: >> On 2014-05-05, Ethan Furman <et...@stoneleaf.us> wrote: >> > On 05/05/2014 12:51 PM, Grant Edwards wrote: >> >> I'd like to do the polite thing and add a "Received:" header, >> >> but I can't figure out how to get Python's email module to add >> >> it in the correct place. It always ends up at the "bottom" of >> >> the headers below From: To: etc. It's supposed to go at the >> >> above all the Received: headers that where there when I received >> >> it. >> > >> > I don't know that it matters, but which Python version? >> >> Sorry, should have mentioned it: 2.7.5 > > Looking at the stdlib source, it doesn't look like there's an easy > way to specify where it gets inserted.
Thanks. There's is a somewhat messy way to do it by calling msg.items() to retrieve all the current headers, removing all of them, and then adding them all back (includeing the new one) in the order I want them. > However, the source to email.message.Message.add_header() is all of 9 > lines of code, so it wouldn't be too hard to subclass Message and > twiddle self._headers as you would any other list (i.e., using > .insert() to specify an index). [ insert_header() method example that lets you specify an index ] A couple other options I was thinking about: * Just override __set_item__ so it treats 'Received' as a special case and inserts it before any existing 'Received' headers -- or prepends it if there aren't any. * Add a prepend_header() method that just sticks it at the top -- in most cases, I think that will be correct enough. I think I like your suggestion better. Since the keys() method preserves the order of header keys, that makes figuring out the insertion point trivial. -- Grant -- https://mail.python.org/mailman/listinfo/python-list