Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract attachements using mailbox python?

Tags:

python

email

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 ?

like image 503
jOSe Avatar asked Jul 18 '15 08:07

jOSe


2 Answers

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()
like image 107
jOSe Avatar answered Nov 15 '22 08:11

jOSe


Use the get_payload() method .

Return the current payload, which will be a list of Message objects when is_multipart() is True, or a string when is_multipart() is False.

Ex:

print message.get_payload()
like image 23
user590028 Avatar answered Nov 15 '22 09:11

user590028