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)
274 for forbidden in chr(0), '/', '\\':
275 if forbidden in fname:
284 fname = str(g.save_counter) + fname
288 outfile = open_output_file(fname)
289 output = outfile.write
298 def decode_part(msg):
299 "Decode one part of the message"
303 # Test all mask lists and find what to do with this content type
305 ctype = msg.get_content_type()
308 mtype = msg.get_content_maintype()
310 masks.append(mtype + '/*')
314 for content_type in masks:
315 if content_type in g.totext_mask or \
316 content_type in g.decoded_binary_mask:
318 elif content_type in g.binary_mask:
322 encoding = msg["Content-Transfer-Encoding"]
323 if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
324 outstring = msg.get_payload()
325 else: # Decode from transfer ecoding to text or binary form
326 outstring = msg.get_payload(decode=1)
327 set_header(msg, "Content-Transfer-Encoding", "8bit")
328 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, g.host_name, me)
330 for content_type in masks:
331 if content_type in g.totext_mask:
332 outstring = totext(msg, outstring)
334 elif content_type in g.binary_mask or \
335 content_type in g.decoded_binary_mask:
339 elif content_type in g.ignore_mask:
341 output("\nMessage body of type %s skipped.\n" % ctype)
343 elif content_type in g.error_mask:
346 # Neither content type nor masks were listed - decode by default
347 outstring = totext(msg, outstring)
349 for content_type in masks:
350 if content_type in g.save_headers_mask:
351 _save_message(msg, outstring, save_headers=True, save_body=False)
352 elif content_type in g.save_body_mask:
353 _save_message(msg, outstring, save_headers=False, save_body=True)
354 elif content_type in g.save_message_mask:
355 _save_message(msg, outstring, save_headers=True, save_body=True)
357 for content_type in masks:
358 if content_type in g.error_mask:
359 raise ValueError, "content type %s prohibited" % ctype
361 def decode_multipart(msg):
367 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
368 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
369 if msg.preamble is not None:
373 boundary = msg.get_boundary()
375 for subpart in msg.get_payload():
378 first_subpart = False
381 output("--%s\n" % boundary)
383 # Recursively decode all parts of the subpart
384 decode_message(subpart)
387 output("\n--%s--\n" % boundary)
393 def decode_message(msg):
396 if msg.is_multipart():
397 decode_multipart(msg)
398 elif len(msg): # Simple one-part message (there are headers) - decode it
400 else: # Not a message, just text - copy it literally
401 output(msg.as_string())
404 def open_output_file(filename):
405 fullpath = os.path.abspath(os.path.join(g.destination_dir, filename))
406 full_dir = os.path.dirname(fullpath)
407 create = not os.path.isdir(full_dir)
409 os.makedirs(full_dir)
411 return open(fullpath, 'w')
414 os.removedirs(full_dir)
418 from m_lib.defenc import default_encoding
419 recode_charset = 1 # recode charset of message body
423 # A list of headers to decode
424 decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
427 # A list of headers parameters to decode
428 decode_header_params = [
429 ("Content-Type", "name"),
430 ("Content-Disposition", "filename"),
433 # A list of headers to remove
435 # A list of headers parameters to remove
436 remove_headers_params = []
438 # A list of header/value pairs to set
439 set_header_value = []
440 # A list of header/parameter/value triples to set
441 set_header_param = []
443 totext_mask = [] # A list of content-types to decode
444 binary_mask = [] # A list of content-types to pass through
445 decoded_binary_mask = [] # A list of content-types to pass through (content-transfer-decoded)
446 ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
447 error_mask = [] # Raise error if encounter one of these
450 save_headers_mask = []
452 save_message_mask = []
454 input_filename = None
455 output_filename = None
456 destination_dir = os.curdir
462 from getopt import getopt, GetoptError
465 options, arguments = getopt(sys.argv[1:],
466 'hVcCDPH:f:d:p:r:R:b:B:e:i:t:O:o:',
467 ['help', 'version', 'host=',
468 'save-headers=', 'save-body=', 'save-message=',
469 'set-header=', 'set-param='])
473 for option, value in options:
474 if option in ('-h', '--help'):
476 elif option in ('-V', '--version'):
482 elif option in ('-H', '--host'):
485 g.default_encoding = value
487 if value.startswith('*'):
488 g.decode_headers = []
489 g.decode_headers.append(value)
491 g.decode_headers = []
493 g.decode_header_params.append(value.split(':', 1))
495 g.decode_header_params = []
497 g.remove_headers.append(value)
499 g.remove_headers_params.append(value.split(':', 1))
500 elif option == '--set-header':
501 g.set_header_value.append(value.split(':', 1))
502 elif option == '--set-param':
503 header, value = value.split(':', 1)
505 param, value = value.split('=', 1)
507 param, value = value.split(':', 1)
508 g.set_header_param.append((header, param, value))
510 g.totext_mask.append(value)
512 g.binary_mask.append(value)
514 g.decoded_binary_mask.append(value)
516 g.ignore_mask.append(value)
518 g.error_mask.append(value)
519 elif option == '--save-headers':
520 g.save_headers_mask.append(value)
521 elif option == '--save-body':
522 g.save_body_mask.append(value)
523 elif option == '--save-message':
524 g.save_message_mask.append(value)
526 g.destination_dir = value
528 g.output_filename = value
535 if __name__ == "__main__":
536 arguments = get_opts()
540 g.input_filename = '-'
542 if g.output_filename:
543 outfile = open_output_file(g.output_filename)
545 g.output_filename = '-'
548 if (arguments[0] == '-'):
549 g.input_filename = '-'
552 g.input_filename = arguments[0]
553 infile = open(arguments[0], 'r')
555 if g.output_filename:
556 outfile = open_output_file(g.output_filename)
558 g.output_filename = '-'
561 if g.output_filename:
562 usage(1, 'Too many output filenames')
563 if (arguments[1] == '-'):
564 g.output_filename = '-'
567 g.output_filename = arguments[1]
568 outfile = open_output_file(g.output_filename)
570 usage(1, 'Too many arguments')
572 if (infile is sys.stdin) and sys.stdin.isatty():
573 if (outfile is sys.stdout) and sys.stdout.isatty():
575 usage(1, 'Filtering from console is forbidden')
579 g.host_name = socket.gethostname()
582 output = outfile.write
584 msg = email.message_from_file(infile)
586 for header, value in g.set_header_value:
587 set_header(msg, header, value)
589 for header, param, value in g.set_header_param:
591 msg.set_param(param, value, header)