Back to index

python3.2  3.2.2
Functions
email-unpack Namespace Reference

Functions

def main

Function Documentation

def email-unpack.main ( void  )

Definition at line 14 of file email-unpack.py.

00014 
00015 def main():
00016     parser = OptionParser(usage="""\
00017 Unpack a MIME message into a directory of files.
00018 
00019 Usage: %prog [options] msgfile
00020 """)
00021     parser.add_option('-d', '--directory',
00022                       type='string', action='store',
00023                       help="""Unpack the MIME message into the named
00024                       directory, which will be created if it doesn't already
00025                       exist.""")
00026     opts, args = parser.parse_args()
00027     if not opts.directory:
00028         parser.print_help()
00029         sys.exit(1)
00030 
00031     try:
00032         msgfile = args[0]
00033     except IndexError:
00034         parser.print_help()
00035         sys.exit(1)
00036 
00037     try:
00038         os.mkdir(opts.directory)
00039     except OSError as e:
00040         # Ignore directory exists error
00041         if e.errno != errno.EEXIST:
00042             raise
00043 
00044     fp = open(msgfile)
00045     msg = email.message_from_file(fp)
00046     fp.close()
00047 
00048     counter = 1
00049     for part in msg.walk():
00050         # multipart/* are just containers
00051         if part.get_content_maintype() == 'multipart':
00052             continue
00053         # Applications should really sanitize the given filename so that an
00054         # email message can't be used to overwrite important files
00055         filename = part.get_filename()
00056         if not filename:
00057             ext = mimetypes.guess_extension(part.get_content_type())
00058             if not ext:
00059                 # Use a generic bag-of-bits extension
00060                 ext = '.bin'
00061             filename = 'part-%03d%s' % (counter, ext)
00062         counter += 1
00063         fp = open(os.path.join(opts.directory, filename), 'wb')
00064         fp.write(part.get_payload(decode=True))
00065         fp.close()
00066 

Here is the call graph for this function: