1 #! /usr/local/bin/python -O
2 """Decode MIME message.
4 Author: Oleg Broytmann <phd@phd.pp.ru>
5 Copyright: (C) 2001-2006 PhiloSoft Design
10 __version__ = "$Revision$"[11:-2]
11 __date__ = "$Date$"[7:-2]
12 __revision__ = "$Id$"[5:-2]
13 __author__ = "Oleg Broytmann <phd@phd.pp.ru>"
14 __copyright__ = "Copyright (C) 2001-2006 PhiloSoft Design"
15 __license__ = "GNU GPL"
16 __docformat__ = "epytext en"
23 from cStringIO import StringIO
25 from StringIO import StringIO
29 host_name = socket.gethostname()
31 me = os.path.basename(sys.argv[0])
36 BroytMann mimedecode.py version %s, %s
37 """ % (_version, __copyright__))
44 Usage: %s [-h|--help] [-V|--version] [-cCDP] [-f charset] [-d header] [-p header:param] [-beit mask] [filename]
49 def output(s, outfile = sys.stdout):
52 def output_headers(msg, outfile = sys.stdout):
53 unix_from = msg.get_unixfrom()
55 output(unix_from + os.linesep)
56 for key, value in msg.items():
57 output("%s: %s\n" % (key, value), outfile)
58 output("\n", outfile) # End of headers
61 def recode(s, charset):
62 return unicode(s, charset, "replace").encode(GlobalOptions.default_charset, "replace")
65 def recode2(s, charset):
66 if charset and charset <> GlobalOptions.default_charset:
67 s = recode(s, charset)
71 def _decode_header(s):
72 """Return a decoded string according to RFC 2047.
73 NOTE: This is almost the same as email.Utils.decode.
75 from types import ListType
78 L = email.Header.decode_header(s)
79 if not isinstance(L, ListType):
84 for atom, charset in L:
88 rtn.append(recode2(atom, charset))
90 del rtn[-1] # remove the last space
92 # Now that we've decoded everything, we just need to join all the parts
93 # together into the final string.
97 def decode_header(msg, header):
98 "Decode mail header (if exists) and put it back, if it was encoded"
100 if msg.has_key(header):
102 new_value = _decode_header(value)
103 if new_value <> value: # do not bother to touch msg if not changed
104 set_header(msg, header, new_value)
107 def _decode_header_param(s):
108 return recode2(s[2], s[0])
111 def decode_header_param(msg, header, param):
112 "Decode mail header's parameter (if exists) and put it back, if it was encoded"
114 if msg.has_key(header):
115 value = msg.get_param(param, header=header)
117 from types import TupleType
118 if isinstance(value, TupleType):
119 new_value = _decode_header_param(value)
121 new_value = _decode_header(value)
122 if new_value <> value: # do not bother to touch msg if not changed
123 msg.set_param(param, new_value, header)
126 def decode_headers(msg):
127 "Decode message headers according to global options"
129 for header in GlobalOptions.decode_headers:
130 decode_header(msg, header)
132 for header, param in GlobalOptions.decode_header_params:
133 decode_header_param(msg, header, param)
136 def set_header(msg, header, value):
139 if msg.has_key(header):
140 msg.replace_header(header, value)
145 def set_content_type(msg, newtype, charset=None):
146 msg.set_type(newtype)
149 msg.set_param("charset", charset, "Content-Type")
153 caps = None # Globally stored mailcap database; initialized only if needed
155 def decode_body(msg, s):
156 "Decode body to plain text using first copiousoutput filter from mailcap"
158 import mailcap, tempfile
162 caps = mailcap.getcaps()
164 content_type = msg.get_content_type()
165 filename = tempfile.mktemp()
168 entries = mailcap.lookup(caps, content_type, "view")
169 for entry in entries:
170 if entry.has_key('copiousoutput'):
171 if entry.has_key('test'):
172 test = mailcap.subst(entry['test'], content_type, filename)
173 if test and os.system(test) != 0:
175 command = mailcap.subst(entry["view"], content_type, filename)
181 file = open(filename, 'w')
185 pipe = os.popen(command, 'r')
190 set_content_type(msg, "text/plain")
191 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, host_name, command.split()[0])
196 def recode_charset(msg, s):
197 "Recode charset of the message to the default charset"
199 save_charset = charset = msg.get_content_charset()
200 if charset and charset <> GlobalOptions.default_charset:
201 s = recode2(s, charset)
202 content_type = msg.get_content_type()
203 set_content_type(msg, content_type, GlobalOptions.default_charset)
204 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, GlobalOptions.default_charset, host_name, me)
208 def totext(msg, instring):
209 "Convert instring content to text"
211 if msg.is_multipart(): # Recursively decode all parts of the multipart message
212 newfile = StringIO(str(msg))
217 # Decode body and recode charset
218 s = decode_body(msg, instring)
219 if GlobalOptions.recode_charset:
220 s = recode_charset(msg, s)
226 def decode_part(msg):
227 "Decode one part of the message"
230 encoding = msg["Content-Transfer-Encoding"]
232 if encoding in (None, '', '7bit', '8bit', 'binary'):
233 outstring = str(msg.get_payload())
234 else: # Decode from transfer ecoding to text or binary form
235 outstring = str(msg.get_payload(decode=1))
236 set_header(msg, "Content-Transfer-Encoding", "8bit")
237 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, host_name, me)
239 # Test all mask lists and find what to do with this content type
241 ctype = msg.get_content_type()
244 mtype = msg.get_content_maintype()
246 masks.append(mtype + '/*')
249 for content_type in masks:
250 if content_type in GlobalOptions.totext_mask:
251 totext(msg, outstring)
253 elif content_type in GlobalOptions.binary_mask:
257 elif content_type in GlobalOptions.ignore_mask:
259 output("\nMessage body of type `%s' skipped.\n" % content_type)
261 elif content_type in GlobalOptions.error_mask:
262 raise ValueError, "content type `%s' prohibited" % content_type
264 # Neither content type nor masks were listed - decode by default
265 totext(msg, outstring)
268 def decode_file(infile):
269 "Decode the entire message"
271 msg = email.message_from_file(infile)
272 boundary = msg.get_boundary()
274 if msg.is_multipart():
278 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
279 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
281 for subpart in msg.get_payload():
282 output("\n--%s\n" % boundary)
285 output("\n--%s--\n" % boundary)
291 if msg.has_key("Content-Type"): # Simple one-part message - decode it
294 else: # Not a message, just text - copy it literally
299 default_charset = sys.getdefaultencoding()
300 recode_charset = 1 # recode charset of message body
302 decode_headers = ["Subject", "From"] # A list of headers to decode
303 decode_header_params = [("Content-Type", "name"),
304 ("Content-Disposition", "filename")
305 ] # A list of headers' parameters to decode
307 totext_mask = [] # A list of content-types to decode
308 binary_mask = [] # A list to pass through
309 ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
310 error_mask = [] # Raise error if encounter one of these
314 from getopt import getopt, GetoptError
317 options, arguments = getopt(sys.argv[1:], 'hVcCDPf:d:p:b:e:i:t:',
322 for option, value in options:
325 elif option == '--help':
329 elif option == '--version':
332 GlobalOptions.recode_charset = 1
334 GlobalOptions.recode_charset = 0
336 GlobalOptions.default_charset = value
338 GlobalOptions.decode_headers.append(value)
340 GlobalOptions.decode_headers = []
342 GlobalOptions.decode_header_params.append(value.split(':', 1))
344 GlobalOptions.decode_header_params = []
346 GlobalOptions.totext_mask.append(value)
348 GlobalOptions.binary_mask.append(value)
350 GlobalOptions.ignore_mask.append(value)
352 GlobalOptions.error_mask.append(value)
359 if __name__ == "__main__":
362 if len(arguments) == 0:
364 elif len(arguments) <> 1:
366 elif arguments[0] == '-':
369 infile = open(arguments[0], 'r')