Q:

Extract attachements using mailbox python?

I wanted to extract email attachments from mbox using mailbox library in python.
I've used following code to extract From, To, Subject, Date, Body
import mailbox    
mbox = mailbox.mbox('/tmp/Personal Folders/Inbox/mbox')
for message in mbox:
    print message['subject']
    print message['To']
    print message['From']
    print message['Date']

How to find and extract attachments in every mails? Do I need to include any more library ?

A:

The following python function extracts find and extracts attachment in native format :) don't forget to include 

import mailbox

def extractattachements(message):
    if message.get_content_maintype() == 'multipart':
        for part in message.walk():
            if part.get_content_maintype() == 'multipart': continue
            if part.get('Content-Disposition') is None: continue
            filename = part.get_filename()
            print filename
            fb = open(filename,'wb')
            fb.write(part.get_payload(decode=True))
            fb.close()

