2 """Decode MIME message"""
4 from mimedecode_version import __version__, __author__, __copyright__, __license__
10 from cStringIO import StringIO
12 from StringIO import StringIO
14 me = os.path.basename(sys.argv[0])
19 Broytman mimedecode.py version %s, %s
20 """ % (__version__, __copyright__))
23 def usage(code=0, errormsg=''):
26 Usage: %s [-h|--help] [-V|--version] [-cCDP] [-H|--host=hostname] [-f charset] [-d header] [-p header:param] [-beit mask] [-o output_file] [input_file [output_file]]
29 sys.stderr.write(errormsg + '\n')
34 gopts.outfile.write(s)
36 def output_headers(msg):
37 unix_from = msg.get_unixfrom()
39 output(unix_from + '\n')
40 for key, value in msg.items():
41 output("%s: %s\n" % (key, value))
42 output("\n") # End of headers
45 def recode(s, charset):
46 return unicode(s, charset, "replace").encode(gopts.default_encoding, "replace")
49 def recode2(s, charset):
50 if charset and charset.lower() <> gopts.default_encoding:
51 s = recode(s, charset)
55 def _decode_header(s):
56 """Return a decoded string according to RFC 2047.
57 NOTE: This is almost the same as email.Utils.decode.
59 from types import ListType
62 L = email.Header.decode_header(s)
63 if not isinstance(L, ListType):
68 for atom, charset in L:
72 rtn.append(recode2(atom, charset))
74 del rtn[-1] # remove the last space
76 # Now that we've decoded everything, we just need to join all the parts
77 # together into the final string.
81 def decode_header(msg, header):
82 "Decode mail header (if exists) and put it back, if it was encoded"
84 if msg.has_key(header):
86 new_value = _decode_header(value)
87 if new_value <> value: # do not bother to touch msg if not changed
88 set_header(msg, header, new_value)
91 def _decode_header_param(s):
92 return recode2(s[2], s[0])
95 def decode_header_param(msg, header, param):
96 "Decode mail header's parameter (if exists) and put it back, if it was encoded"
98 if msg.has_key(header):
99 value = msg.get_param(param, header=header)
101 from types import TupleType
102 if isinstance(value, TupleType):
103 new_value = _decode_header_param(value)
105 new_value = _decode_header(value)
106 if new_value <> value: # do not bother to touch msg if not changed
107 msg.set_param(param, new_value, header)
110 def decode_headers(msg):
111 "Decode message headers according to global options"
113 for header in gopts.decode_headers:
114 decode_header(msg, header)
116 for header, param in gopts.decode_header_params:
117 decode_header_param(msg, header, param)
120 def set_header(msg, header, value):
123 if msg.has_key(header):
124 msg.replace_header(header, value)
129 def set_content_type(msg, newtype, charset=None):
130 msg.set_type(newtype)
133 msg.set_param("charset", charset, "Content-Type")
137 caps = None # Globally stored mailcap database; initialized only if needed
139 def decode_body(msg, s):
140 "Decode body to plain text using first copiousoutput filter from mailcap"
142 import mailcap, tempfile
146 caps = mailcap.getcaps()
148 content_type = msg.get_content_type()
149 filename = tempfile.mktemp()
152 entries = mailcap.lookup(caps, content_type, "view")
153 for entry in entries:
154 if entry.has_key('copiousoutput'):
155 if entry.has_key('test'):
156 test = mailcap.subst(entry['test'], content_type, filename)
157 if test and os.system(test) != 0:
159 command = mailcap.subst(entry["view"], content_type, filename)
165 file = open(filename, 'w')
169 pipe = os.popen(command, 'r')
174 set_content_type(msg, "text/plain")
175 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, gopts.host_name, command.split()[0])
180 def recode_charset(msg, s):
181 "Recode charset of the message to the default charset"
183 save_charset = charset = msg.get_content_charset()
184 if charset and charset.lower() <> gopts.default_encoding:
185 s = recode2(s, charset)
186 content_type = msg.get_content_type()
187 set_content_type(msg, content_type, gopts.default_encoding)
188 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, gopts.default_encoding, gopts.host_name, me)
192 def totext(msg, instring):
193 "Convert instring content to text"
195 if msg.is_multipart(): # Recursively decode all parts of the multipart message
196 newfile = StringIO(str(msg))
201 # Decode body and recode charset
202 s = decode_body(msg, instring)
203 if gopts.recode_charset:
204 s = recode_charset(msg, s)
210 def decode_part(msg):
211 "Decode one part of the message"
214 encoding = msg["Content-Transfer-Encoding"]
216 if encoding in (None, '', '7bit', '8bit', 'binary'):
217 outstring = str(msg.get_payload())
218 else: # Decode from transfer ecoding to text or binary form
219 outstring = str(msg.get_payload(decode=1))
220 set_header(msg, "Content-Transfer-Encoding", "8bit")
221 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, gopts.host_name, me)
223 # Test all mask lists and find what to do with this content type
225 ctype = msg.get_content_type()
228 mtype = msg.get_content_maintype()
230 masks.append(mtype + '/*')
233 for content_type in masks:
234 if content_type in gopts.totext_mask:
235 totext(msg, outstring)
237 elif content_type in gopts.binary_mask:
241 elif content_type in gopts.ignore_mask:
243 output("\nMessage body of type `%s' skipped.\n" % content_type)
245 elif content_type in gopts.error_mask:
246 raise ValueError, "content type `%s' prohibited" % content_type
248 # Neither content type nor masks were listed - decode by default
249 totext(msg, outstring)
252 def decode_file(infile):
253 "Decode the entire message"
255 msg = email.message_from_file(infile)
256 boundary = msg.get_boundary()
258 if msg.is_multipart():
262 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
263 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
265 for subpart in msg.get_payload():
266 output("\n--%s\n" % boundary)
269 output("\n--%s--\n" % boundary)
275 if msg.has_key("Content-Type"): # Simple one-part message - decode it
278 else: # Not a message, just text - copy it literally
283 from m_lib.defenc import default_encoding
284 recode_charset = 1 # recode charset of message body
288 decode_headers = ["From", "Subject"] # A list of headers to decode
289 decode_header_params = [
290 ("Content-Type", "name"),
291 ("Content-Disposition", "filename"),
292 ] # A list of headers' parameters to decode
294 totext_mask = [] # A list of content-types to decode
295 binary_mask = [] # A list to pass through
296 ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
297 error_mask = [] # Raise error if encounter one of these
299 input_filename = None
300 output_filename = None
302 gopts = GlobalOptions
306 from getopt import getopt, GetoptError
309 options, arguments = getopt(sys.argv[1:], 'hVcCDPH:f:d:p:b:e:i:t:o:',
310 ['help', 'version', 'host'])
314 for option, value in options:
315 if option in ('-h', '--help'):
317 elif option in ('-V', '--version'):
320 gopts.recode_charset = 1
322 gopts.recode_charset = 0
323 elif option in ('-H', '--host'):
324 gopts.host_name = value
326 gopts.default_encoding = value
328 gopts.decode_headers.append(value)
330 gopts.decode_headers = []
332 gopts.decode_header_params.append(value.split(':', 1))
334 gopts.decode_header_params = []
336 gopts.totext_mask.append(value)
338 gopts.binary_mask.append(value)
340 gopts.ignore_mask.append(value)
342 gopts.error_mask.append(value)
344 gopts.output_filename = value
351 if __name__ == "__main__":
352 arguments = get_opt()
356 gopts.input_filename = '-'
357 gopts.output_filename = '-'
361 if (arguments[0] == '-'):
362 gopts.input_filename = '-'
365 gopts.input_filename = arguments[0]
366 infile = open(arguments[0], 'r')
368 if gopts.output_filename:
369 outfile = open(gopts.output_filename, 'w')
371 gopts.output_filename = '-'
374 if gopts.output_filename:
375 usage(1, 'Too many output filenames')
376 if (arguments[1] == '-'):
377 gopts.output_filename = '-'
380 gopts.output_filename = arguments[1]
381 outfile = open(arguments[1], 'w')
383 usage(1, 'Too many arguments')
385 if (infile is sys.stdin) and (outfile is sys.stdout) and \
386 sys.stdin.isatty() and sys.stdout.isatty():
387 usage(1, 'Filtering from console to console is forbidden')
389 if not gopts.host_name:
391 gopts.host_name = socket.gethostname()
393 gopts.outfile = outfile