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 header1[,h2,...]|*[,-h1,...]] [-R header1[,h2,h3,...]:param1[,p2,p3,...]] [--set-header header:value] [--set-param header:param=value] [-Bbeit 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_params(msg, header, decode_all_params, param_list):
101 if decode_all_params:
102 params = msg.get_params(header=header)
104 for param, value in params:
105 if param not in param_list:
106 decode_header_param(msg, header, param)
108 for param in param_list:
109 decode_header_param(msg, header, param)
111 def _remove_headers_params(msg, header, remove_all_params, param_list):
112 if remove_all_params:
113 params = msg.get_params(header=header)
116 for param, value in params:
117 if param not in param_list:
118 msg.del_param(param, header)
121 if value is None: # No such header
123 if ';' not in value: # There are no parameters
125 del msg[header] # Delete all such headers
126 # Get the value without parameters and set it back
127 msg[header] = value.split(';')[0].strip()
129 for param in param_list:
130 msg.del_param(param, header)
132 def decode_headers(msg):
133 "Decode message headers according to global options"
135 for header_list in gopts.remove_headers:
136 header_list = header_list.split(',')
137 if header_list[0] == '*': # Remove all headers except listed
138 header_list = _get_exceptions(header_list)
139 for header in msg.keys():
140 if header.lower() not in header_list:
142 else: # Remove listed headers
143 for header in header_list:
146 for header_list, param_list in gopts.remove_headers_params:
147 header_list = header_list.split(',')
148 param_list = param_list.split(',')
149 remove_all_params = param_list[0] == '*' # Remove all params except listed
150 if remove_all_params:
151 param_list = _get_exceptions(param_list)
152 if header_list[0] == '*': # Remove for all headers except listed
153 header_list = _get_exceptions(header_list)
154 for header in msg.keys():
155 if header.lower() not in header_list:
156 _remove_headers_params(msg, header, remove_all_params, param_list)
157 else: # Decode for listed headers
158 for header in header_list:
159 _remove_headers_params(msg, header, remove_all_params, param_list)
161 for header_list in gopts.decode_headers:
162 header_list = header_list.split(',')
163 if header_list[0] == '*': # Decode all headers except listed
164 header_list = _get_exceptions(header_list)
165 for header in msg.keys():
166 if header.lower() not in header_list:
167 decode_header(msg, header)
168 else: # Decode listed headers
169 for header in header_list:
170 decode_header(msg, header)
172 for header_list, param_list in gopts.decode_header_params:
173 header_list = header_list.split(',')
174 param_list = param_list.split(',')
175 decode_all_params = param_list[0] == '*' # Decode all params except listed
176 if decode_all_params:
177 param_list = _get_exceptions(param_list)
178 if header_list[0] == '*': # Decode for all headers except listed
179 header_list = _get_exceptions(header_list)
180 for header in msg.keys():
181 if header.lower() not in header_list:
182 _decode_headers_params(msg, header, decode_all_params, param_list)
183 else: # Decode for listed headers
184 for header in header_list:
185 _decode_headers_params(msg, header, decode_all_params, param_list)
188 def set_header(msg, header, value):
191 if msg.has_key(header):
192 msg.replace_header(header, value)
197 def set_content_type(msg, newtype, charset=None):
198 msg.set_type(newtype)
201 msg.set_param("charset", charset, "Content-Type")
204 caps = None # Globally stored mailcap database; initialized only if needed
206 def decode_body(msg, s):
207 "Decode body to plain text using first copiousoutput filter from mailcap"
209 import mailcap, tempfile
213 caps = mailcap.getcaps()
215 content_type = msg.get_content_type()
216 filename = tempfile.mktemp()
219 entries = mailcap.lookup(caps, content_type, "view")
220 for entry in entries:
221 if entry.has_key('copiousoutput'):
222 if entry.has_key('test'):
223 test = mailcap.subst(entry['test'], content_type, filename)
224 if test and os.system(test) != 0:
226 command = mailcap.subst(entry["view"], content_type, filename)
232 file = open(filename, 'w')
236 pipe = os.popen(command, 'r')
241 set_content_type(msg, "text/plain")
242 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, gopts.host_name, command.split()[0])
247 def recode_charset(msg, s):
248 "Recode charset of the message to the default charset"
250 save_charset = charset = msg.get_content_charset()
251 if charset and charset.lower() <> gopts.default_encoding:
252 s = recode_if_needed(s, charset)
253 content_type = msg.get_content_type()
254 set_content_type(msg, content_type, gopts.default_encoding)
255 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, gopts.default_encoding, gopts.host_name, me)
259 def totext(msg, instring):
260 "Convert instring content to text"
262 # Decode body and recode charset
263 s = decode_body(msg, instring)
264 if gopts.recode_charset:
265 s = recode_charset(msg, s)
271 def decode_part(msg):
272 "Decode one part of the message"
276 # Test all mask lists and find what to do with this content type
278 ctype = msg.get_content_type()
281 mtype = msg.get_content_maintype()
283 masks.append(mtype + '/*')
287 for content_type in masks:
288 if content_type in gopts.binary_mask:
292 encoding = msg["Content-Transfer-Encoding"]
293 if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
294 outstring = str(msg.get_payload())
295 else: # Decode from transfer ecoding to text or binary form
296 outstring = str(msg.get_payload(decode=1))
297 set_header(msg, "Content-Transfer-Encoding", "8bit")
298 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, gopts.host_name, me)
300 for content_type in masks:
301 if content_type in gopts.totext_mask:
302 totext(msg, outstring)
304 elif content_type in gopts.binary_mask or \
305 content_type in gopts.decoded_binary_mask:
309 elif content_type in gopts.ignore_mask:
311 output("\nMessage body of type `%s' skipped.\n" % content_type)
313 elif content_type in gopts.error_mask:
314 raise ValueError, "content type `%s' prohibited" % content_type
316 # Neither content type nor masks were listed - decode by default
317 totext(msg, outstring)
320 def decode_multipart(msg):
326 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
327 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
329 boundary = msg.get_boundary()
331 for subpart in msg.get_payload():
333 output("\n--%s\n" % boundary)
335 # Recursively decode all parts of the subpart
336 decode_message(subpart)
339 output("\n--%s--\n" % boundary)
345 def decode_message(msg):
348 if msg.is_multipart():
349 decode_multipart(msg)
350 elif len(msg): # Simple one-part message (there are headers) - decode it
352 else: # Not a message, just text - copy it literally
353 output(msg.as_string())
357 from m_lib.defenc import default_encoding
358 recode_charset = 1 # recode charset of message body
362 # A list of headers to decode
363 decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
366 # A list of headers parameters to decode
367 decode_header_params = [
368 ("Content-Type", "name"),
369 ("Content-Disposition", "filename"),
372 # A list of headers to remove
374 # A list of headers parameters to remove
375 remove_headers_params = []
377 # A list of header/value pairs to set
378 set_header_value = []
379 # A list of header/parameter/value triples to set
380 set_header_param = []
382 totext_mask = [] # A list of content-types to decode
383 binary_mask = [] # A list of content-types to pass through
384 decoded_binary_mask = [] # A list of content-types to pass through (content-transfer-decoded)
385 ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
386 error_mask = [] # Raise error if encounter one of these
388 input_filename = None
389 output_filename = None
391 gopts = GlobalOptions
395 from getopt import getopt, GetoptError
398 options, arguments = getopt(sys.argv[1:],
399 'hVcCDPH:f:d:p:r:R:b:B:e:i:t:o:',
400 ['help', 'version', 'host=', 'set-header=', 'set-param='])
404 for option, value in options:
405 if option in ('-h', '--help'):
407 elif option in ('-V', '--version'):
410 gopts.recode_charset = 1
412 gopts.recode_charset = 0
413 elif option in ('-H', '--host'):
414 gopts.host_name = value
416 gopts.default_encoding = value
418 if value.startswith('*'):
419 gopts.decode_headers = []
420 gopts.decode_headers.append(value)
422 gopts.decode_headers = []
424 gopts.decode_header_params.append(value.split(':', 1))
426 gopts.decode_header_params = []
428 gopts.remove_headers.append(value)
430 gopts.remove_headers_params.append(value.split(':', 1))
431 elif option == '--set-header':
432 gopts.set_header_value.append(value.split(':', 1))
433 elif option == '--set-param':
434 header, value = value.split(':', 1)
436 param, value = value.split('=', 1)
438 param, value = value.split(':', 1)
439 gopts.set_header_param.append((header, param, value))
441 gopts.totext_mask.append(value)
443 gopts.binary_mask.append(value)
445 gopts.decoded_binary_mask.append(value)
447 gopts.ignore_mask.append(value)
449 gopts.error_mask.append(value)
451 gopts.output_filename = value
458 if __name__ == "__main__":
459 arguments = get_opt()
463 gopts.input_filename = '-'
465 if gopts.output_filename:
466 outfile = open(gopts.output_filename, 'w')
468 gopts.output_filename = '-'
471 if (arguments[0] == '-'):
472 gopts.input_filename = '-'
475 gopts.input_filename = arguments[0]
476 infile = open(arguments[0], 'r')
478 if gopts.output_filename:
479 outfile = open(gopts.output_filename, 'w')
481 gopts.output_filename = '-'
484 if gopts.output_filename:
485 usage(1, 'Too many output filenames')
486 if (arguments[1] == '-'):
487 gopts.output_filename = '-'
490 gopts.output_filename = arguments[1]
491 outfile = open(arguments[1], 'w')
493 usage(1, 'Too many arguments')
495 if (infile is sys.stdin) and sys.stdin.isatty():
496 if (outfile is sys.stdout) and sys.stdout.isatty():
498 usage(1, 'Filtering from console is forbidden')
500 if not gopts.host_name:
502 gopts.host_name = socket.gethostname()
504 gopts.outfile = outfile
505 output = outfile.write
507 msg = email.message_from_file(infile)
509 for header, value in gopts.set_header_value:
512 for header, param, value in gopts.set_header_param:
514 msg.set_param(param, value, header)