Add header at top with email.message

Jason Friedman jsf80238 at gmail.com
Sat Sep 15 14:52:48 EDT 2018


>
> the EmailMessage class of email.message provides the methods
> add_header() and __setitem__() to add a header to a message.
> add_header() effectively calls __setitem__(), which does
> `self._headers.append(self.policy.header_store_parse(name, val))`.  This
> inserts the header at the bottom.
>
> It is, however, sometimes desired to insert a new header at the top of
> an (existing) message.  This API doesn’t directly allow this.  In my
> opinion, add_header() should have a flag at_top=False or similar, so
> that one can get this behaviour (it’ll be a bit difficult with
> __setitem__).  What do you think about this?  Is there a feasible way to
> do this and change the library?  Should I post it somewhere where the
> devs can hear it and suggest that?\
>

I see this in the docs at
https://docs.python.org/3/library/email.message.html#email.message.EmailMessage.get_unixfrom
:

The following methods implement the mapping-like interface for accessing
the message’s headers. Note that there are some semantic differences
between these methods and a normal mapping (i.e. dictionary) interface. For
example, in a dictionary there are no duplicate keys, but here there may be
duplicate message headers. Also, in dictionaries there is no guaranteed
order to the keys returned by keys(), but in an EmailMessage object,
headers are always returned in the order they appeared in the original
message, or in which they were added to the message later. Any header
deleted and then re-added is always appended to the end of the header list.

I suppose you already figured out that you can call __delitem__() to clear
the headers and add them back in whatever order you like.
I'm interested in learning more about your use case.  Do you have a third
party with fixed logic that requires the headers in a particular order?



More information about the Python-list mailing list