Fuu
Fuu

Reputation: 3474

Using the Pythons email.message API, how do you remove a specific part of the message

I have email message with an unwanted attachment (a PKCS-7 signature in this particular case). I can detect the signature in the email with this piece of code:

payloads = mail.get_payload()

for index in xrange(len(payloads)):
    if payloads[index].get_content_type() == "application/pkcs7-signature":
        print("Found PKCS-7 Signature", index)

How would I remove this particular payload from the message? The email.message API seems to only have methods for reading and writing whole payloads: get_payload() and set_payload(). Neither of these allow specifying payload index of what to read or write.

Upvotes: 1

Views: 865

Answers (1)

erny
erny

Reputation: 2489

One possible solution:

def remove_signature(mail):
    payload = mail.get_payload()
    if isinstance(payload, list):
        for part in payload:
            if part.get_content_type().startswith('application/pkcs7-signature'):
                payload.remove(part)
    return mail

Upvotes: 1

Related Questions