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_output_file(fname)
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())
398 def open_output_file(filename):
399 fullpath = os.path.abspath(os.path.join(g.destination_dir, filename))
400 full_dir = os.path.dirname(fullpath)
401 create = not os.path.isdir(full_dir)
403 os.makedirs(full_dir)
405 return open(fullpath, 'w')
408 os.removedirs(full_dir)
412 from m_lib.defenc import default_encoding
413 recode_charset = 1 # recode charset of message body
417 # A list of headers to decode
418 decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
421 # A list of headers parameters to decode
422 decode_header_params = [
423 ("Content-Type", "name"),
424 ("Content-Disposition", "filename"),
427 # A list of headers to remove
429 # A list of headers parameters to remove
430 remove_headers_params = []
432 # A list of header/value pairs to set
433 set_header_value = []
434 # A list of header/parameter/value triples to set
435 set_header_param = []
437 totext_mask = [] # A list of content-types to decode
438 binary_mask = [] # A list of content-types to pass through
439 decoded_binary_mask = [] # A list of content-types to pass through (content-transfer-decoded)
440 ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
441 error_mask = [] # Raise error if encounter one of these
444 save_headers_mask = []
446 save_message_mask = []
448 input_filename = None
449 output_filename = None
450 destination_dir = os.curdir
456 from getopt import getopt, GetoptError
459 options, arguments = getopt(sys.argv[1:],
460 'hVcCDPH:f:d:p:r:R:b:B:e:i:t:O:o:',
461 ['help', 'version', 'host=',
462 'save-headers=', 'save-body=', 'save-message=',
463 'set-header=', 'set-param='])
467 for option, value in options:
468 if option in ('-h', '--help'):
470 elif option in ('-V', '--version'):
476 elif option in ('-H', '--host'):
479 g.default_encoding = value
481 if value.startswith('*'):
482 g.decode_headers = []
483 g.decode_headers.append(value)
485 g.decode_headers = []
487 g.decode_header_params.append(value.split(':', 1))
489 g.decode_header_params = []
491 g.remove_headers.append(value)
493 g.remove_headers_params.append(value.split(':', 1))
494 elif option == '--set-header':
495 g.set_header_value.append(value.split(':', 1))
496 elif option == '--set-param':
497 header, value = value.split(':', 1)
499 param, value = value.split('=', 1)
501 param, value = value.split(':', 1)
502 g.set_header_param.append((header, param, value))
504 g.totext_mask.append(value)
506 g.binary_mask.append(value)
508 g.decoded_binary_mask.append(value)
510 g.ignore_mask.append(value)
512 g.error_mask.append(value)
513 elif option == '--save-headers':
514 g.save_headers_mask.append(value)
515 elif option == '--save-body':
516 g.save_body_mask.append(value)
517 elif option == '--save-message':
518 g.save_message_mask.append(value)
520 g.destination_dir = value
522 g.output_filename = value
529 if __name__ == "__main__":
530 arguments = get_opts()
534 g.input_filename = '-'
536 if g.output_filename:
537 outfile = open_output_file(g.output_filename)
539 g.output_filename = '-'
542 if (arguments[0] == '-'):
543 g.input_filename = '-'
546 g.input_filename = arguments[0]
547 infile = open(arguments[0], 'r')
549 if g.output_filename:
550 outfile = open_output_file(g.output_filename)
552 g.output_filename = '-'
555 if g.output_filename:
556 usage(1, 'Too many output filenames')
557 if (arguments[1] == '-'):
558 g.output_filename = '-'
561 g.output_filename = arguments[1]
562 outfile = open_output_file(g.output_filename)
564 usage(1, 'Too many arguments')
566 if (infile is sys.stdin) and sys.stdin.isatty():
567 if (outfile is sys.stdout) and sys.stdout.isatty():
569 usage(1, 'Filtering from console is forbidden')
573 g.host_name = socket.gethostname()
576 output = outfile.write
578 msg = email.message_from_file(infile)
580 for header, value in g.set_header_value:
581 set_header(msg, header, value)
583 for header, param, value in g.set_header_param:
585 msg.set_param(param, value, header)