How to parse winmail.dat with python

3k views Asked by At

I'm pulling emails with attachments off a server and placing them in folders based on certain criteria. This is no problem for emails that were sent with plain text encoding, but as we all know if they were sent with rich text then the attachments get converted to the winmail.dat format.

I've tried using a module called tnefparse, but haven't had any luck since I couldn't find any documentation or examples online.

Can anyone provide some examples on how to read in and convert the winmail.dat attachment, using tnefparse or any other Python module?

1

There are 1 answers

1
amonthedeamon On

It's pretty easy to use tnefparse from command line

First of all install it using pip

pip install tnefparse

to extract the attachment from winmail.dat just run

tnefparse -a winmail.dat

If you want to integrate this library in your Python code, just take the tnefparse command line implementation, which is really easy to understand. Anyway, here's is a sample piece of code that extract all attachments from winmail.dat into the current working directory:

import sys
from tnefparse.tnef import TNEF, TNEFAttachment, TNEFObject
from tnefparse.mapi import TNEFMAPI_Attribute
t = TNEF(open("winmail.dat").read(), do_checksum=True)
for a in t.attachments:
    with open(a.name, "wb") as afp:
        afp.write(a.data)
sys.exit("Successfully wrote %i files" % len(t.attachments))