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] [--save-headers|body|message mask] [-O dest_dir] [-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_if_needed(s, charset):
38 if charset and charset.lower() <> g.default_encoding:
39 s = unicode(s, charset, "replace").encode(g.default_encoding, "replace")
43 def _decode_header(s):
44 """Return a decoded string according to RFC 2047.
45 NOTE: This is almost the same as email.Utils.decode.
49 L = email.Header.decode_header(s)
50 if not isinstance(L, list):
55 for atom, charset in L:
59 rtn.append(recode_if_needed(atom, charset))
61 del rtn[-1] # remove the last space
63 # Now that we've decoded everything, we just need to join all the parts
64 # together into the final string.
67 def decode_header(msg, header):
68 "Decode mail header (if exists) and put it back, if it was encoded"
70 if msg.has_key(header):
72 new_value = _decode_header(value)
73 if new_value <> value: # do not bother to touch msg if not changed
74 set_header(msg, header, new_value)
77 def decode_header_param(msg, header, param):
78 "Decode mail header's parameter (if exists) and put it back, if it was encoded"
80 if msg.has_key(header):
81 value = msg.get_param(param, header=header)
83 if isinstance(value, tuple):
84 new_value = recode_if_needed(value[2], value[0])
86 new_value = _decode_header(value)
87 if new_value <> value: # do not bother to touch msg if not changed
88 msg.set_param(param, new_value, header)
91 def _get_exceptions(list):
92 return [x[1:].lower() for x in list[1:] if x[0]=='-']
94 def _decode_headers_params(msg, header, decode_all_params, param_list):
96 params = msg.get_params(header=header)
98 for param, value in params:
99 if param not in param_list:
100 decode_header_param(msg, header, param)
102 for param in param_list:
103 decode_header_param(msg, header, param)
105 def _remove_headers_params(msg, header, remove_all_params, param_list):
106 if remove_all_params:
107 params = msg.get_params(header=header)
110 for param, value in params:
111 if param not in param_list:
112 msg.del_param(param, header)
115 if value is None: # No such header
117 if ';' not in value: # There are no parameters
119 del msg[header] # Delete all such headers
120 # Get the value without parameters and set it back
121 msg[header] = value.split(';')[0].strip()
123 for param in param_list:
124 msg.del_param(param, header)
126 def decode_headers(msg):
127 "Decode message headers according to global options"
129 for header_list in g.remove_headers:
130 header_list = header_list.split(',')
131 if header_list[0] == '*': # Remove all headers except listed
132 header_list = _get_exceptions(header_list)
133 for header in msg.keys():
134 if header.lower() not in header_list:
136 else: # Remove listed headers
137 for header in header_list:
140 for header_list, param_list in g.remove_headers_params:
141 header_list = header_list.split(',')
142 param_list = param_list.split(',')
143 remove_all_params = param_list[0] == '*' # Remove all params except listed
144 if remove_all_params:
145 param_list = _get_exceptions(param_list)
146 if header_list[0] == '*': # Remove for all headers except listed
147 header_list = _get_exceptions(header_list)
148 for header in msg.keys():
149 if header.lower() not in header_list:
150 _remove_headers_params(msg, header, remove_all_params, param_list)
151 else: # Decode for listed headers
152 for header in header_list:
153 _remove_headers_params(msg, header, remove_all_params, param_list)
155 for header_list in g.decode_headers:
156 header_list = header_list.split(',')
157 if header_list[0] == '*': # Decode all headers except listed
158 header_list = _get_exceptions(header_list)
159 for header in msg.keys():
160 if header.lower() not in header_list:
161 decode_header(msg, header)
162 else: # Decode listed headers
163 for header in header_list:
164 decode_header(msg, header)
166 for header_list, param_list in g.decode_header_params:
167 header_list = header_list.split(',')
168 param_list = param_list.split(',')
169 decode_all_params = param_list[0] == '*' # Decode all params except listed
170 if decode_all_params:
171 param_list = _get_exceptions(param_list)
172 if header_list[0] == '*': # Decode for all headers except listed
173 header_list = _get_exceptions(header_list)
174 for header in msg.keys():
175 if header.lower() not in header_list:
176 _decode_headers_params(msg, header, decode_all_params, param_list)
177 else: # Decode for listed headers
178 for header in header_list:
179 _decode_headers_params(msg, header, decode_all_params, param_list)
182 def set_header(msg, header, value):
185 if msg.has_key(header):
186 msg.replace_header(header, value)
191 def set_content_type(msg, newtype, charset=None):
192 msg.set_type(newtype)
195 msg.set_param("charset", charset, "Content-Type")
198 caps = None # Globally stored mailcap database; initialized only if needed
200 def decode_body(msg, s):
201 "Decode body to plain text using first copiousoutput filter from mailcap"
203 import mailcap, tempfile
207 caps = mailcap.getcaps()
209 content_type = msg.get_content_type()
210 filename = tempfile.mktemp()
213 entries = mailcap.lookup(caps, content_type, "view")
214 for entry in entries:
215 if entry.has_key('copiousoutput'):
216 if entry.has_key('test'):
217 test = mailcap.subst(entry['test'], content_type, filename)
218 if test and os.system(test) != 0:
220 command = mailcap.subst(entry["view"], content_type, filename)
226 file = open(filename, 'w')
230 pipe = os.popen(command, 'r')
235 set_content_type(msg, "text/plain")
236 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
241 def recode_charset(msg, s):
242 "Recode charset of the message to the default charset"
244 save_charset = charset = msg.get_content_charset()
245 if charset and charset.lower() <> g.default_encoding:
246 s = recode_if_needed(s, charset)
247 content_type = msg.get_content_type()
248 set_content_type(msg, content_type, g.default_encoding)
249 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, g.default_encoding, g.host_name, me)
253 def totext(msg, instring):
254 "Convert instring content to text"
256 # Decode body and recode charset
257 s = decode_body(msg, instring)
259 s = recode_charset(msg, s)
266 def _save_message(msg, outstring, save_headers=False, save_body=False):
267 for header, param in (
268 ("Content-Disposition", "filename"),
269 ("Content-Type", "name"),
271 fname = msg.get_param(param, header=header)
273 if isinstance(fname, tuple):
274 fname = fname[2] # Do not recode if it isn't recoded yet
276 for forbidden in chr(0), '/', '\\':
277 if forbidden in fname:
286 fname = str(g.save_counter) + fname
290 outfile = open_output_file(fname)
291 output = outfile.write
300 def decode_part(msg):
301 "Decode one part of the message"
305 # Test all mask lists and find what to do with this content type
307 ctype = msg.get_content_type()
310 mtype = msg.get_content_maintype()
312 masks.append(mtype + '/*')
316 for content_type in masks:
317 if content_type in g.totext_mask or \
318 content_type in g.decoded_binary_mask:
320 elif content_type in g.binary_mask:
324 encoding = msg["Content-Transfer-Encoding"]
325 if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
326 outstring = msg.get_payload()
327 else: # Decode from transfer ecoding to text or binary form
328 outstring = msg.get_payload(decode=1)
329 set_header(msg, "Content-Transfer-Encoding", "8bit")
330 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, g.host_name, me)
332 for content_type in masks:
333 if content_type in g.totext_mask:
334 outstring = totext(msg, outstring)
336 elif content_type in g.binary_mask or \
337 content_type in g.decoded_binary_mask:
341 elif content_type in g.ignore_mask:
343 output("\nMessage body of type %s skipped.\n" % ctype)
345 elif content_type in g.error_mask:
348 # Neither content type nor masks were listed - decode by default
349 outstring = totext(msg, outstring)
351 for content_type in masks:
352 if content_type in g.save_headers_mask:
353 _save_message(msg, outstring, save_headers=True, save_body=False)
354 elif content_type in g.save_body_mask:
355 _save_message(msg, outstring, save_headers=False, save_body=True)
356 elif content_type in g.save_message_mask:
357 _save_message(msg, outstring, save_headers=True, save_body=True)
359 for content_type in masks:
360 if content_type in g.error_mask:
361 raise ValueError, "content type %s prohibited" % ctype
363 def decode_multipart(msg):
369 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
370 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
371 if msg.preamble is not None:
375 boundary = msg.get_boundary()
377 for subpart in msg.get_payload():
380 first_subpart = False
383 output("--%s\n" % boundary)
385 # Recursively decode all parts of the subpart
386 decode_message(subpart)
389 output("\n--%s--\n" % boundary)
395 def decode_message(msg):
398 if msg.is_multipart():
399 decode_multipart(msg)
400 elif len(msg): # Simple one-part message (there are headers) - decode it
402 else: # Not a message, just text - copy it literally
403 output(msg.as_string())
406 def open_output_file(filename):
407 fullpath = os.path.abspath(os.path.join(g.destination_dir, filename))
408 full_dir = os.path.dirname(fullpath)
409 create = not os.path.isdir(full_dir)
411 os.makedirs(full_dir)
413 return open(fullpath, 'w')
416 os.removedirs(full_dir)
420 from m_lib.defenc import default_encoding
421 recode_charset = 1 # recode charset of message body
425 # A list of headers to decode
426 decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
429 # A list of headers parameters to decode
430 decode_header_params = [
431 ("Content-Type", "name"),
432 ("Content-Disposition", "filename"),
435 # A list of headers to remove
437 # A list of headers parameters to remove
438 remove_headers_params = []
440 # A list of header/value pairs to set
441 set_header_value = []
442 # A list of header/parameter/value triples to set
443 set_header_param = []
445 totext_mask = [] # A list of content-types to decode
446 binary_mask = [] # A list of content-types to pass through
447 decoded_binary_mask = [] # A list of content-types to pass through (content-transfer-decoded)
448 ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
449 error_mask = [] # Raise error if encounter one of these
452 save_headers_mask = []
454 save_message_mask = []
456 input_filename = None
457 output_filename = None
458 destination_dir = os.curdir
464 from getopt import getopt, GetoptError
467 options, arguments = getopt(sys.argv[1:],
468 'hVcCDPH:f:d:p:r:R:b:B:e:i:t:O:o:',
469 ['help', 'version', 'host=',
470 'save-headers=', 'save-body=', 'save-message=',
471 'set-header=', 'set-param='])
475 for option, value in options:
476 if option in ('-h', '--help'):
478 elif option in ('-V', '--version'):
484 elif option in ('-H', '--host'):
487 g.default_encoding = value
489 if value.startswith('*'):
490 g.decode_headers = []
491 g.decode_headers.append(value)
493 g.decode_headers = []
495 g.decode_header_params.append(value.split(':', 1))
497 g.decode_header_params = []
499 g.remove_headers.append(value)
501 g.remove_headers_params.append(value.split(':', 1))
502 elif option == '--set-header':
503 g.set_header_value.append(value.split(':', 1))
504 elif option == '--set-param':
505 header, value = value.split(':', 1)
507 param, value = value.split('=', 1)
509 param, value = value.split(':', 1)
510 g.set_header_param.append((header, param, value))
512 g.totext_mask.append(value)
514 g.binary_mask.append(value)
516 g.decoded_binary_mask.append(value)
518 g.ignore_mask.append(value)
520 g.error_mask.append(value)
521 elif option == '--save-headers':
522 g.save_headers_mask.append(value)
523 elif option == '--save-body':
524 g.save_body_mask.append(value)
525 elif option == '--save-message':
526 g.save_message_mask.append(value)
528 g.destination_dir = value
530 g.output_filename = value
537 if __name__ == "__main__":
538 arguments = get_opts()
542 g.input_filename = '-'
544 if g.output_filename:
545 outfile = open_output_file(g.output_filename)
547 g.output_filename = '-'
550 if (arguments[0] == '-'):
551 g.input_filename = '-'
554 g.input_filename = arguments[0]
555 infile = open(arguments[0], 'r')
557 if g.output_filename:
558 outfile = open_output_file(g.output_filename)
560 g.output_filename = '-'
563 if g.output_filename:
564 usage(1, 'Too many output filenames')
565 if (arguments[1] == '-'):
566 g.output_filename = '-'
569 g.output_filename = arguments[1]
570 outfile = open_output_file(g.output_filename)
572 usage(1, 'Too many arguments')
574 if (infile is sys.stdin) and sys.stdin.isatty():
575 if (outfile is sys.stdout) and sys.stdout.isatty():
577 usage(1, 'Filtering from console is forbidden')
581 g.host_name = socket.gethostname()
584 output = outfile.write
586 msg = email.message_from_file(infile)
588 for header, value in g.set_header_value:
589 set_header(msg, header, value)
591 for header, param, value in g.set_header_param:
593 msg.set_param(param, value, header)