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 ?
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()
                        Use the get_payload() method .
Return the current payload, which will be a list of
Messageobjects whenis_multipart()is True, or a string whenis_multipart()is False.
Ex:
print message.get_payload()
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With