How to extract attachments from msg files using Python
<p>How do I extract attachments from msg files using Python...?</p>

<pre><code>import os
import sys
import email
import errno
import mimetypes
from optparse import OptionParser

if __name__ == "__main__":

    fp = open("C:/FNFData/emails/e_1512_1_message.msg")
    msg = email.message_from_file(fp)
    fp.close()

    counter = 1
    print msg['From']
    print msg['Subject']
    for part in msg.walk():
        # multipart/* are just containers
        if part.get_content_maintype() == 'multipart':
            continue
        # Applications should really sanitize the given filename so that an
        # email message can't be used to overwrite important files
        filename = part.get_filename()
        #print filename
        if not filename:
            ext = mimetypes.guess_extension(part.get_content_type())
            print "Extension :", ext
            if not ext:
                # Use a generic bag-of-bits extension
                ext = '.bin'
            filename = 'part-%03d%s' % (counter, ext)
        counter += 1
        fp = open(os.path.join("C:\\FNFData\\emails", filename), 'wb')
        fp.write(part.get_payload(decode=True))
        fp.close()
    print counter
</code></pre>

<p>This code doesnt work and identifies "ksh" as the extension of the attachment instead of pdf. Also it shows "To","From","Subject" everything as NONE...
Any ideas why?</p>

<p>Thanks</p>

<p>Parag</p>
