Help on Email Parsing

deelan ggg at zzz.it
Mon Feb 23 09:50:07 EST 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 extract.py 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)
     f.close()

     # 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')
         f.write(data)
         f.close()

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

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



-- 
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
<#me> a foaf:Person ; foaf:nick "deelan" ;
foaf:weblog <http://www.deelan.com/> .



More information about the Python-list mailing list