2 """Decode MIME message"""
4 from mimedecode_version import __version__, __author__, __copyright__, __license__
9 me = os.path.basename(sys.argv[0])
14 Broytman mimedecode.py version %s, %s
15 """ % (__version__, __copyright__))
18 def usage(code=0, errormsg=''):
21 Usage: %s [-h|--help] [-V|--version] [-cCDP] [-H|--host=hostname] [-f charset] [-d header1[,h2,...]|*[,-h1,...]] [-p header1[,h2,h3,...]:param1[,p2,p3,...]] [-r header] [-R header:param] [--remove-params=header] [-beit mask] [-o output_file] [input_file [output_file]]
24 sys.stderr.write(errormsg + '\n')
28 def output_headers(msg):
29 unix_from = msg.get_unixfrom()
31 output(unix_from + '\n')
32 for key, value in msg.items():
33 output("%s: %s\n" % (key, value))
34 output("\n") # End of headers
37 def recode(s, charset):
38 return unicode(s, charset, "replace").encode(gopts.default_encoding, "replace")
40 def recode_if_needed(s, charset):
41 if charset and charset.lower() <> gopts.default_encoding:
42 s = recode(s, charset)
46 def _decode_header(s):
47 """Return a decoded string according to RFC 2047.
48 NOTE: This is almost the same as email.Utils.decode.
52 L = email.Header.decode_header(s)
53 if not isinstance(L, list):
58 for atom, charset in L:
62 rtn.append(recode_if_needed(atom, charset))
64 del rtn[-1] # remove the last space
66 # Now that we've decoded everything, we just need to join all the parts
67 # together into the final string.
70 def decode_header(msg, header):
71 "Decode mail header (if exists) and put it back, if it was encoded"
73 if msg.has_key(header):
75 new_value = _decode_header(value)
76 if new_value <> value: # do not bother to touch msg if not changed
77 set_header(msg, header, new_value)
80 def _decode_header_param(s):
81 return recode_if_needed(s[2], s[0])
83 def decode_header_param(msg, header, param):
84 "Decode mail header's parameter (if exists) and put it back, if it was encoded"
86 if msg.has_key(header):
87 value = msg.get_param(param, header=header)
89 if isinstance(value, tuple):
90 new_value = _decode_header_param(value)
92 new_value = _decode_header(value)
93 if new_value <> value: # do not bother to touch msg if not changed
94 msg.set_param(param, new_value, header)
97 def _get_exceptions(list):
98 return [x[1:].lower() for x in list[1:] if x[0]=='-']
100 def decode_headers(msg):
101 "Decode message headers according to global options"
103 for header in gopts.remove_headers:
106 for header in gopts.remove_all_params:
108 if value is None: # No such header
110 if ';' not in value: # There are no parameters
112 del msg[header] # Delete all such headers
113 # Get the value without parameters and set it back
114 msg[header] = value.split(';')[0].strip()
116 for header, param in gopts.remove_header_params:
117 msg.del_param(param, header)
119 for header_list in gopts.decode_headers:
120 header_list = header_list.split(',')
121 if header_list[0] == '*': # Decode all headers except listed
122 header_list = _get_exceptions(header_list)
123 for header in msg.keys():
124 if header.lower() not in header_list:
125 decode_header(msg, header)
126 else: # Decode listed headers
127 for header in header_list:
128 decode_header(msg, header)
130 for header_list, param_list in gopts.decode_header_params:
131 header_list = header_list.split(',')
132 param_list = param_list.split(',')
133 decode_all_params = param_list[0] == '*' # Decode all params except listed
134 if decode_all_params:
135 param_list = _get_exceptions(param_list)
136 if header_list[0] == '*': # Decode for all headers except listed
137 header_list = _get_exceptions(header_list)
138 for header in msg.keys():
139 if header.lower() not in header_list:
140 if decode_all_params:
141 params = msg.get_params(header=header)
143 for param, value in params:
144 if param not in param_list:
145 decode_header_param(msg, header, param)
147 for param in param_list:
148 decode_header_param(msg, header, param)
149 else: # Decode for listed headers
150 for header in header_list:
151 if decode_all_params:
152 params = msg.get_params(header=header)
154 for param, value in params:
155 if param not in param_list:
156 decode_header_param(msg, header, param)
158 for param in param_list:
159 decode_header_param(msg, header, param)
162 def set_header(msg, header, value):
165 if msg.has_key(header):
166 msg.replace_header(header, value)
171 def set_content_type(msg, newtype, charset=None):
172 msg.set_type(newtype)
175 msg.set_param("charset", charset, "Content-Type")
178 caps = None # Globally stored mailcap database; initialized only if needed
180 def decode_body(msg, s):
181 "Decode body to plain text using first copiousoutput filter from mailcap"
183 import mailcap, tempfile
187 caps = mailcap.getcaps()
189 content_type = msg.get_content_type()
190 filename = tempfile.mktemp()
193 entries = mailcap.lookup(caps, content_type, "view")
194 for entry in entries:
195 if entry.has_key('copiousoutput'):
196 if entry.has_key('test'):
197 test = mailcap.subst(entry['test'], content_type, filename)
198 if test and os.system(test) != 0:
200 command = mailcap.subst(entry["view"], content_type, filename)
206 file = open(filename, 'w')
210 pipe = os.popen(command, 'r')
215 set_content_type(msg, "text/plain")
216 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, gopts.host_name, command.split()[0])
221 def recode_charset(msg, s):
222 "Recode charset of the message to the default charset"
224 save_charset = charset = msg.get_content_charset()
225 if charset and charset.lower() <> gopts.default_encoding:
226 s = recode_if_needed(s, charset)
227 content_type = msg.get_content_type()
228 set_content_type(msg, content_type, gopts.default_encoding)
229 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, gopts.default_encoding, gopts.host_name, me)
233 def totext(msg, instring):
234 "Convert instring content to text"
236 # Decode body and recode charset
237 s = decode_body(msg, instring)
238 if gopts.recode_charset:
239 s = recode_charset(msg, s)
245 def decode_part(msg):
246 "Decode one part of the message"
249 encoding = msg["Content-Transfer-Encoding"]
251 if encoding in (None, '', '7bit', '8bit', 'binary'):
252 outstring = str(msg.get_payload())
253 else: # Decode from transfer ecoding to text or binary form
254 outstring = str(msg.get_payload(decode=1))
255 set_header(msg, "Content-Transfer-Encoding", "8bit")
256 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, gopts.host_name, me)
258 # Test all mask lists and find what to do with this content type
260 ctype = msg.get_content_type()
263 mtype = msg.get_content_maintype()
265 masks.append(mtype + '/*')
268 for content_type in masks:
269 if content_type in gopts.totext_mask:
270 totext(msg, outstring)
272 elif content_type in gopts.binary_mask:
276 elif content_type in gopts.ignore_mask:
278 output("\nMessage body of type `%s' skipped.\n" % content_type)
280 elif content_type in gopts.error_mask:
281 raise ValueError, "content type `%s' prohibited" % content_type
283 # Neither content type nor masks were listed - decode by default
284 totext(msg, outstring)
287 def decode_multipart(msg):
293 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
294 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
296 boundary = msg.get_boundary()
298 for subpart in msg.get_payload():
300 output("\n--%s\n" % boundary)
302 # Recursively decode all parts of the subpart
303 decode_message(subpart)
306 output("\n--%s--\n" % boundary)
312 def decode_message(msg):
315 if msg.is_multipart():
316 decode_multipart(msg)
317 elif len(msg): # Simple one-part message (there are headers) - decode it
319 else: # Not a message, just text - copy it literally
320 output(msg.as_string())
324 from m_lib.defenc import default_encoding
325 recode_charset = 1 # recode charset of message body
329 # A list of headers to decode
330 decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
333 # A list of headers parameters to decode
334 decode_header_params = [
335 ("Content-Type", "name"),
336 ("Content-Disposition", "filename"),
339 # A list of headers to remove
341 # A list of headers parameters to remove
342 remove_header_params = []
343 # A list of headers to be stripped of all parameters
344 remove_all_params = []
346 totext_mask = [] # A list of content-types to decode
347 binary_mask = [] # A list to pass through
348 ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
349 error_mask = [] # Raise error if encounter one of these
351 input_filename = None
352 output_filename = None
354 gopts = GlobalOptions
358 from getopt import getopt, GetoptError
361 options, arguments = getopt(sys.argv[1:],
362 'hVcCDPH:f:d:p:r:R:b:e:i:t:o:',
363 ['help', 'version', 'host=', 'remove-params='])
367 for option, value in options:
368 if option in ('-h', '--help'):
370 elif option in ('-V', '--version'):
373 gopts.recode_charset = 1
375 gopts.recode_charset = 0
376 elif option in ('-H', '--host'):
377 gopts.host_name = value
379 gopts.default_encoding = value
381 if value.startswith('*'):
382 gopts.decode_headers = []
383 gopts.decode_headers.append(value)
385 gopts.decode_headers = []
387 gopts.decode_header_params.append(value.split(':', 1))
389 gopts.decode_header_params = []
391 gopts.remove_headers.append(value)
393 gopts.remove_header_params.append(value.split(':', 1))
394 elif option == '--remove-params':
395 gopts.remove_all_params.append(value)
397 gopts.totext_mask.append(value)
399 gopts.binary_mask.append(value)
401 gopts.ignore_mask.append(value)
403 gopts.error_mask.append(value)
405 gopts.output_filename = value
412 if __name__ == "__main__":
413 arguments = get_opt()
417 gopts.input_filename = '-'
419 if gopts.output_filename:
420 outfile = open(gopts.output_filename, 'w')
422 gopts.output_filename = '-'
425 if (arguments[0] == '-'):
426 gopts.input_filename = '-'
429 gopts.input_filename = arguments[0]
430 infile = open(arguments[0], 'r')
432 if gopts.output_filename:
433 outfile = open(gopts.output_filename, 'w')
435 gopts.output_filename = '-'
438 if gopts.output_filename:
439 usage(1, 'Too many output filenames')
440 if (arguments[1] == '-'):
441 gopts.output_filename = '-'
444 gopts.output_filename = arguments[1]
445 outfile = open(arguments[1], 'w')
447 usage(1, 'Too many arguments')
449 if (infile is sys.stdin) and sys.stdin.isatty():
450 if (outfile is sys.stdout) and sys.stdout.isatty():
452 usage(1, 'Filtering from console is forbidden')
454 if not gopts.host_name:
456 gopts.host_name = socket.gethostname()
458 gopts.outfile = outfile
459 output = outfile.write
462 decode_message(email.message_from_file(infile))