Removing Email attachments

Tim Williams listserver at
Fri Aug 20 20:11:38 CEST 2004

On Thu, 19 Aug 2004 15:17:11 +0100, Tim Williams <listserver at> wrote:
> I need to take an email with none or more attachments,  remove attachments
> with certain file extensions and then send the remaining email onwards.
> The problem is that I can't find out how to remove single attachements,
> can add new ones and/or  remove all) .
> Am I missing something,  or do I have to create a new email object  from
> remaining bits of the old one ?
> (I *have* googled)

Easier than I thought :-)

here's a successful test I tried with the surrounding code removed.  It
needs needs a bit of error handling in real use,  but not much.

emailobj  = email.message_from_string(message_string)

def removeAttach(emailobj):
    if not emailobj.is_multipart():
    new_payload = []
    removed = []
    old_payload = emailobj.get_payload()
    ext_list = ['ade', 'adp', 'pp', 'asx']

    for x in range(len(old_payload)):
        filename = old_payload[x].get_filename()
        if filename:
            ext = filename.split('.')[-1].lower()
        if not filename or not ext in ext_list :

    if removed:

More information about the Python-list mailing list