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)
278 fname = str(g.save_counter) + fname
282 outfile = open(os.path.join(g.destination_dir, fname), 'w')
283 output = outfile.write
292 def decode_part(msg):
293 "Decode one part of the message"
297 # Test all mask lists and find what to do with this content type
299 ctype = msg.get_content_type()
302 mtype = msg.get_content_maintype()
304 masks.append(mtype + '/*')
308 for content_type in masks:
309 if content_type in g.totext_mask or \
310 content_type in g.decoded_binary_mask:
312 elif content_type in g.binary_mask:
316 encoding = msg["Content-Transfer-Encoding"]
317 if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
318 outstring = msg.get_payload()
319 else: # Decode from transfer ecoding to text or binary form
320 outstring = msg.get_payload(decode=1)
321 set_header(msg, "Content-Transfer-Encoding", "8bit")
322 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, g.host_name, me)
324 for content_type in masks:
325 if content_type in g.totext_mask:
326 outstring = totext(msg, outstring)
328 elif content_type in g.binary_mask or \
329 content_type in g.decoded_binary_mask:
333 elif content_type in g.ignore_mask:
335 output("\nMessage body of type %s skipped.\n" % ctype)
337 elif content_type in g.error_mask:
340 # Neither content type nor masks were listed - decode by default
341 outstring = totext(msg, outstring)
343 for content_type in masks:
344 if content_type in g.save_headers_mask:
345 _save_message(msg, outstring, save_headers=True, save_body=False)
346 elif content_type in g.save_body_mask:
347 _save_message(msg, outstring, save_headers=False, save_body=True)
348 elif content_type in g.save_message_mask:
349 _save_message(msg, outstring, save_headers=True, save_body=True)
351 for content_type in masks:
352 if content_type in g.error_mask:
353 raise ValueError, "content type %s prohibited" % ctype
355 def decode_multipart(msg):
361 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
362 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
363 if msg.preamble is not None:
367 boundary = msg.get_boundary()
369 for subpart in msg.get_payload():
372 first_subpart = False
375 output("--%s\n" % boundary)
377 # Recursively decode all parts of the subpart
378 decode_message(subpart)
381 output("\n--%s--\n" % boundary)
387 def decode_message(msg):
390 if msg.is_multipart():
391 decode_multipart(msg)
392 elif len(msg): # Simple one-part message (there are headers) - decode it
394 else: # Not a message, just text - copy it literally
395 output(msg.as_string())
399 from m_lib.defenc import default_encoding
400 recode_charset = 1 # recode charset of message body
404 # A list of headers to decode
405 decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
408 # A list of headers parameters to decode
409 decode_header_params = [
410 ("Content-Type", "name"),
411 ("Content-Disposition", "filename"),
414 # A list of headers to remove
416 # A list of headers parameters to remove
417 remove_headers_params = []
419 # A list of header/value pairs to set
420 set_header_value = []
421 # A list of header/parameter/value triples to set
422 set_header_param = []
424 totext_mask = [] # A list of content-types to decode
425 binary_mask = [] # A list of content-types to pass through
426 decoded_binary_mask = [] # A list of content-types to pass through (content-transfer-decoded)
427 ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
428 error_mask = [] # Raise error if encounter one of these
431 save_headers_mask = []
433 save_message_mask = []
435 input_filename = None
436 output_filename = None
437 destination_dir = os.curdir
443 from getopt import getopt, GetoptError
446 options, arguments = getopt(sys.argv[1:],
447 'hVcCDPH:f:d:p:r:R:b:B:e:i:t:O:o:',
448 ['help', 'version', 'host=',
449 'save-headers=', 'save-body=', 'save-message=',
450 'set-header=', 'set-param='])
454 for option, value in options:
455 if option in ('-h', '--help'):
457 elif option in ('-V', '--version'):
463 elif option in ('-H', '--host'):
466 g.default_encoding = value
468 if value.startswith('*'):
469 g.decode_headers = []
470 g.decode_headers.append(value)
472 g.decode_headers = []
474 g.decode_header_params.append(value.split(':', 1))
476 g.decode_header_params = []
478 g.remove_headers.append(value)
480 g.remove_headers_params.append(value.split(':', 1))
481 elif option == '--set-header':
482 g.set_header_value.append(value.split(':', 1))
483 elif option == '--set-param':
484 header, value = value.split(':', 1)
486 param, value = value.split('=', 1)
488 param, value = value.split(':', 1)
489 g.set_header_param.append((header, param, value))
491 g.totext_mask.append(value)
493 g.binary_mask.append(value)
495 g.decoded_binary_mask.append(value)
497 g.ignore_mask.append(value)
499 g.error_mask.append(value)
500 elif option == '--save-headers':
501 g.save_headers_mask.append(value)
502 elif option == '--save-body':
503 g.save_body_mask.append(value)
504 elif option == '--save-message':
505 g.save_message_mask.append(value)
507 g.destination_dir = value
509 g.output_filename = value
516 if __name__ == "__main__":
517 arguments = get_opts()
521 g.input_filename = '-'
523 if g.output_filename:
524 outfile = open(os.path.join(g.destination_dir, g.output_filename), 'w')
526 g.output_filename = '-'
529 if (arguments[0] == '-'):
530 g.input_filename = '-'
533 g.input_filename = arguments[0]
534 infile = open(arguments[0], 'r')
536 if g.output_filename:
537 outfile = open(os.path.join(g.destination_dir, g.output_filename), 'w')
539 g.output_filename = '-'
542 if g.output_filename:
543 usage(1, 'Too many output filenames')
544 if (arguments[1] == '-'):
545 g.output_filename = '-'
548 g.output_filename = arguments[1]
549 outfile = open(os.path.join(g.destination_dir, g.output_filename), 'w')
551 usage(1, 'Too many arguments')
553 if (infile is sys.stdin) and sys.stdin.isatty():
554 if (outfile is sys.stdout) and sys.stdout.isatty():
556 usage(1, 'Filtering from console is forbidden')
560 g.host_name = socket.gethostname()
563 output = outfile.write
565 msg = email.message_from_file(infile)
567 for header, value in g.set_header_value:
570 for header, param, value in g.set_header_param:
572 msg.set_param(param, value, header)