Help on Email Parsing

deelan ggg at
Mon Feb 23 15:50:07 CET 2004

dont bother wrote:

> Hey,
> I have been trying to parse emails:
> But I could not find any examples or snippets of
> parsing emails in python from the documentation.
> Google did not help me much too.
> I am trying to understand the module 'email' and the
> functions described there to parse email but seems
> difficult.
> Can anyone help me in locating some pointers or
> snippets on this issue.

this script will extract one or more images
from an email message given as argument

hope this helps.

"""Extracts all images from given rfc822-compliant email message.
A quick hack by deelan

python filename

# good MIME's
mimes = 'image/gif', 'image/jpeg', 'image/png'

import email

def main(filename):
     f = file(filename, 'r')
     m = email.message_from_file(f)

     # loop thru message body and look for JPEG, GIF and PNG images
     images = [(part.get_filename(), part.get_payload(decode=True))
               for part in m.get_payload() if part.get_type() in mimes]

     for name, data in images:
         print 'writing', name, '...'
         f = file(name, 'wb')

     print 'done %d image(s).' % len(images)

if __name__ == '__main__':
     import sys
     if len(sys.argv) > 1:
         print __doc__

@prefix foaf: <> .
<#me> a foaf:Person ; foaf:nick "deelan" ;
foaf:weblog <> .

More information about the Python-list mailing list