#!/usr/bin/python # Copyright 2011 Jeff Epler # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import email import glob import os import mimetypes import sys import tempfile import shutil import subprocess import re def convert_tnef_to_mime(message, part): content_type = part.get_content_type() print >>sys.stderr, "subpart", content_type if content_type != 'application/ms-tnef': return 0 print >>sys.stderr, "should convert this subpart" tempdir = tempfile.mkdtemp() print >>sys.stderr, "temporary directory", tempdir try: pipe = subprocess.Popen(['tnef', '-C', tempdir], stdin=subprocess.PIPE, stdout=sys.stderr) pipe.communicate(part.get_payload(decode=True)) pipe.wait() if pipe.returncode: print >>sys.stderr, "tnef exited with code %r" % pipe.returncode extracted = glob.glob(os.path.join(tempdir, "*")) print >>sys.stderr, "extracted", tempdir, extracted if extracted: payload = [] for fn in extracted: safename = re.sub("[^-a-zA-Z0-9_. ]", "", os.path.basename(fn)) mtype = mimetypes.guess_type(fn) if mtype: mtype = mtype[0] else: mtype = 'application/octet-stream' newsubpart = email.message.Message() newsubpart.set_type("%s; name=\"%s\"" % (mtype, safename)) newsubpart.set_payload(open(fn).read().encode("base64")) newsubpart.add_header("content-transfer-encoding", "base64") message.attach(newsubpart) print >>sys.stderr, "newsubpart:", safename return len(extracted) else: print >>sys.stderr, "tnef attachment appeared to have no contents" print >>sys.stderr, "left unchanged" return 0 finally: pass #shutil.rmtree(tempdir) mdata = sys.stdin.read() try: message = email.message_from_string(mdata) new_parts = 0 for part in message.walk(): new_parts += convert_tnef_to_mime(message, part) if new_parts: print >>sys.stderr, "Changed %d tnef attachment(s) to mime" % new_parts del message['content-length'] mdata = message.as_string(True) sys.stdout.write(mdata) except: sys.stdout.write(mdata) print >>sys.stderr, "Error encountered. Original message written on stdout" raise