2

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)?

Community
  • 1
  • 1
tuck1s
  • 1,002
  • 9
  • 28
  • When you say 3.x do you mean the legacy `email` library which was the default up through 3.5, or the new revamped one (which was available as an option I believe from 3.4 but not promoted much before 3.6)? – tripleee Dec 20 '17 at 10:10
  • I was testing this using `Python 3.6.2 :: Anaconda custom (x86_64)` interpreter under PyCharm. The actual filename of the package appears to be under `anaconda3/lib/python3.6/email/utils.py` and the file has a comment at the top: # Copyright (C) 2001-2010 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """Miscellaneous utilities.""" – tuck1s Jan 21 '18 at 14:53
  • Another minor improvement in readability: you can assign the return value of `getaddresses()` to a named tuple, like this `for (name, addr) in email.utils.getaddresses(msg.get_all(hdr)):` – tuck1s Jan 21 '21 at 12:50

2 Answers2

5

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])
tuck1s
  • 1,002
  • 9
  • 28
5

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)
TheDavidFactor
  • 1,647
  • 2
  • 19
  • 18
  • Thank you, that's shorter and more elegant than the way I found. Pycharm does not provide any information on the `remove` method, nor can it step into it, but it works for me. Perhaps that's because it's a builtin? – tuck1s Aug 27 '19 at 12:55