Removing Email attachments

Tim Williams listserver at tdw.net
Fri Aug 20 14:11:38 EDT 2004


On Thu, 19 Aug 2004 15:17:11 +0100, Tim Williams <listserver at tdw.net> 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,
(I
> can add new ones and/or  remove all) .
>
> Am I missing something,  or do I have to create a new email object  from
the
> remaining bits of the old one ?
>
> (I *have* googled)
>
> TIA

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():
        return
    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 :
            new_payload.append(old_payload[x])
        else:
            removed.append(filename)

    if removed:
        emailobj.set_payload(new_payload)




More information about the Python-list mailing list