Python 3.x email.message library: trying to remove specific header content such as bcc

2.5k Views Asked by At

The library functions for reading headers from an RFC822 compliant file are working just fine for me, for example:

    allRecips = []
    for hdrName in ['to', 'cc', 'bcc']:
        for i in email.utils.getaddresses(msg.get_all(hdrName, [])):
            r = {
                'address': {
                    'name': i[0],
                    'email': i[1]
                }
            }
            allRecips.append(r)

I now want to remove the bcc recipients from the msg structure in the above example. I looked at del_param() for this, but couldn't figure out what to pass in. Is there a good way to delete any bcc headers that may be present (1 or more)?

2

There are 2 best solutions below

1
On BEST ANSWER

a list has the remove method which searches for the item so the order is not important.

I believe you could accomplish the goal using this code:

for header in msg._headers:
    if header[0].lower() == 'bcc':
        msg._headers.remove(header)
0
On

I found a way to do it. The trick was to work backwards through the array of headers using reversed(), to avoid issues where content 'moves' in the array.

# Remove any bcc headers from the message payload. Work backwards, as deletion changes later indices.
for i in reversed(range(len(msg._headers))):
    hdrName = msg._headers[i][0].lower()
    if hdrName == 'bcc':
        del(msg._headers[i])