Best way to filter parts of a email.message.Message

Tim Chase python.list at tim.thechases.com
Thu Sep 4 03:59:58 CEST 2014


I'd like to do something like the following pseudocode

  existing_message = mailbox[key] # an email.message.Message
  new_message = email.message.Message()
  for part in existing_message.walk():
    if passes_test(part):
      new_message.add(part) # need proper call here
    else:
      log("skipping %r" % part)

or alternatively something like this pseudocode inverse

  new_message = copy.copy(existing_message)
  for part in new_message.walk():
    if fails_test(part):
      new_message.magic_delete_part_method(part)

However, I want to make sure that just the selected mime-parts get
eliminated and that everything else (other mime-parts as well as
headers) gets copied over.  Points giving me minor fits:

- mime-parts can be nested, so I need to recursively handle them

- making sure that if the source is/isn't multipart, that the
  resulting new message is the same

- ensuring that headers get preserved (including the order)


Is there an obvious way to do this without rolling up my sleeves and
getting into the source for email.message and friends?

Thanks,

-tkc






More information about the Python-list mailing list