2 """Decode MIME message"""
5 from mimedecode_version import __version__, \
6 __author__, __copyright__, __license__
8 me = os.path.basename(sys.argv[0])
13 Broytman mimedecode.py version %s, %s
14 """ % (__version__, __copyright__))
17 def usage(code=0, errormsg=''):
20 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]]
23 sys.stderr.write(errormsg + '\n')
27 def output_headers(msg):
28 unix_from = msg.get_unixfrom()
30 output(unix_from + '\n')
31 for key, value in msg.items():
32 output("%s: %s\n" % (key, value))
33 output("\n") # End of headers
36 def recode_if_needed(s, charset):
37 if charset and charset.lower() <> g.default_encoding:
38 s = unicode(s, charset, "replace").encode(g.default_encoding, "replace")
42 def _decode_header(s):
43 """Return a decoded string according to RFC 2047.
44 NOTE: This is almost the same as email.Utils.decode.
48 L = email.Header.decode_header(s)
49 if not isinstance(L, list):
54 for atom, charset in L:
58 rtn.append(recode_if_needed(atom, charset))
60 del rtn[-1] # remove the last space
62 # Now that we've decoded everything, we just need to join all the parts
63 # together into the final string.
66 def decode_header(msg, header):
67 "Decode mail header (if exists) and put it back, if it was encoded"
69 if msg.has_key(header):
71 new_value = _decode_header(value)
72 if new_value <> value: # do not bother to touch msg if not changed
73 set_header(msg, header, new_value)
76 def decode_header_param(msg, header, param):
77 "Decode mail header's parameter (if exists) and put it back, if it was encoded"
79 if msg.has_key(header):
80 value = msg.get_param(param, header=header)
82 if isinstance(value, tuple):
83 new_value = recode_if_needed(value[2], value[0])
85 new_value = _decode_header(value)
86 if new_value <> value: # do not bother to touch msg if not changed
87 msg.set_param(param, new_value, header)
90 def _get_exceptions(list):
91 return [x[1:].lower() for x in list[1:] if x[0]=='-']
93 def _decode_headers_params(msg, header, decode_all_params, param_list):
95 params = msg.get_params(header=header)
97 for param, value in params:
98 if param not in param_list:
99 decode_header_param(msg, header, param)
101 for param in param_list:
102 decode_header_param(msg, header, param)
104 def _remove_headers_params(msg, header, remove_all_params, param_list):
105 if remove_all_params:
106 params = msg.get_params(header=header)
109 for param, value in params:
110 if param not in param_list:
111 msg.del_param(param, header)
114 if value is None: # No such header
116 if ';' not in value: # There are no parameters
118 del msg[header] # Delete all such headers
119 # Get the value without parameters and set it back
120 msg[header] = value.split(';')[0].strip()
122 for param in param_list:
123 msg.del_param(param, header)
125 def decode_headers(msg):
126 "Decode message headers according to global options"
128 for header_list in g.remove_headers:
129 header_list = header_list.split(',')
130 if header_list[0] == '*': # Remove all headers except listed
131 header_list = _get_exceptions(header_list)
132 for header in msg.keys():
133 if header.lower() not in header_list:
135 else: # Remove listed headers
136 for header in header_list:
139 for header_list, param_list in g.remove_headers_params:
140 header_list = header_list.split(',')
141 param_list = param_list.split(',')
142 remove_all_params = param_list[0] == '*' # Remove all params except listed
143 if remove_all_params:
144 param_list = _get_exceptions(param_list)
145 if header_list[0] == '*': # Remove for all headers except listed
146 header_list = _get_exceptions(header_list)
147 for header in msg.keys():
148 if header.lower() not in header_list:
149 _remove_headers_params(msg, header, remove_all_params, param_list)
150 else: # Decode for listed headers
151 for header in header_list:
152 _remove_headers_params(msg, header, remove_all_params, param_list)
154 for header_list in g.decode_headers:
155 header_list = header_list.split(',')
156 if header_list[0] == '*': # Decode all headers except listed
157 header_list = _get_exceptions(header_list)
158 for header in msg.keys():
159 if header.lower() not in header_list:
160 decode_header(msg, header)
161 else: # Decode listed headers
162 for header in header_list:
163 decode_header(msg, header)
165 for header_list, param_list in g.decode_header_params:
166 header_list = header_list.split(',')
167 param_list = param_list.split(',')
168 decode_all_params = param_list[0] == '*' # Decode all params except listed
169 if decode_all_params:
170 param_list = _get_exceptions(param_list)
171 if header_list[0] == '*': # Decode for all headers except listed
172 header_list = _get_exceptions(header_list)
173 for header in msg.keys():
174 if header.lower() not in header_list:
175 _decode_headers_params(msg, header, decode_all_params, param_list)
176 else: # Decode for listed headers
177 for header in header_list:
178 _decode_headers_params(msg, header, decode_all_params, param_list)
181 def set_header(msg, header, value):
184 if msg.has_key(header):
185 msg.replace_header(header, value)
190 def set_content_type(msg, newtype, charset=None):
191 msg.set_type(newtype)
194 msg.set_param("charset", charset, "Content-Type")
197 caps = None # Globally stored mailcap database; initialized only if needed
199 def decode_body(msg, s):
200 "Decode body to plain text using first copiousoutput filter from mailcap"
202 import mailcap, tempfile
206 caps = mailcap.getcaps()
208 content_type = msg.get_content_type()
209 filename = tempfile.mktemp()
212 entries = mailcap.lookup(caps, content_type, "view")
213 for entry in entries:
214 if entry.has_key('copiousoutput'):
215 if entry.has_key('test'):
216 test = mailcap.subst(entry['test'], content_type, filename)
217 if test and os.system(test) != 0:
219 command = mailcap.subst(entry["view"], content_type, filename)
225 file = open(filename, 'w')
229 pipe = os.popen(command, 'r')
234 set_content_type(msg, "text/plain")
235 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
240 def recode_charset(msg, s):
241 "Recode charset of the message to the default charset"
243 save_charset = charset = msg.get_content_charset()
244 if charset and charset.lower() <> g.default_encoding:
245 s = recode_if_needed(s, charset)
246 content_type = msg.get_content_type()
247 set_content_type(msg, content_type, g.default_encoding)
248 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, g.default_encoding, g.host_name, me)
252 def totext(msg, instring):
253 "Convert instring content to text"
255 # Decode body and recode charset
256 s = decode_body(msg, instring)
258 s = recode_charset(msg, s)
267 def _guess_extension(ctype):
269 if mimetypes is None:
272 user_mime_type = os.path.expanduser('~/.mime.types')
273 if os.path.exists(user_mime_type):
274 mimetypes._db.read(user_mime_type)
275 return mimetypes.guess_extension(ctype)
277 def _save_message(msg, outstring, save_headers=False, save_body=False):
278 for header, param in (
279 ("Content-Disposition", "filename"),
280 ("Content-Type", "name"),
282 fname = msg.get_param(param, header=header)
284 if isinstance(fname, tuple):
285 fname = fname[2] # Do not recode if it isn't recoded yet
287 for forbidden in chr(0), '/', '\\':
288 if forbidden in fname:
297 fname = str(g.save_counter) + fname
299 ext = _guess_extension(msg.get_content_type())
304 outfile = open_output_file(fname)
305 output = outfile.write
314 def decode_part(msg):
315 "Decode one part of the message"
319 # Test all mask lists and find what to do with this content type
321 ctype = msg.get_content_type()
324 mtype = msg.get_content_maintype()
326 masks.append(mtype + '/*')
330 for content_type in masks:
331 if content_type in g.totext_mask or \
332 content_type in g.decoded_binary_mask:
334 elif content_type in g.binary_mask:
338 encoding = msg["Content-Transfer-Encoding"]
339 if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
340 outstring = msg.get_payload()
341 else: # Decode from transfer ecoding to text or binary form
342 outstring = msg.get_payload(decode=1)
343 set_header(msg, "Content-Transfer-Encoding", "8bit")
344 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, g.host_name, me)
346 for content_type in masks:
347 if content_type in g.totext_mask:
348 outstring = totext(msg, outstring)
350 elif content_type in g.binary_mask or \
351 content_type in g.decoded_binary_mask:
355 elif content_type in g.ignore_mask:
357 output("\nMessage body of type %s skipped.\n" % ctype)
359 elif content_type in g.error_mask:
362 # Neither content type nor masks were listed - decode by default
363 outstring = totext(msg, outstring)
365 for content_type in masks:
366 if content_type in g.save_headers_mask:
367 _save_message(msg, outstring, save_headers=True, save_body=False)
368 elif content_type in g.save_body_mask:
369 _save_message(msg, outstring, save_headers=False, save_body=True)
370 elif content_type in g.save_message_mask:
371 _save_message(msg, outstring, save_headers=True, save_body=True)
373 for content_type in masks:
374 if content_type in g.error_mask:
375 raise ValueError, "content type %s prohibited" % ctype
377 def decode_multipart(msg):
383 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
384 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
385 if msg.preamble is not None:
389 boundary = msg.get_boundary()
391 for subpart in msg.get_payload():
394 first_subpart = False
397 output("--%s\n" % boundary)
399 # Recursively decode all parts of the subpart
400 decode_message(subpart)
403 output("\n--%s--\n" % boundary)
409 def decode_message(msg):
412 if msg.is_multipart():
413 decode_multipart(msg)
414 elif len(msg): # Simple one-part message (there are headers) - decode it
416 else: # Not a message, just text - copy it literally
417 output(msg.as_string())
420 def open_output_file(filename):
421 fullpath = os.path.abspath(os.path.join(g.destination_dir, filename))
422 full_dir = os.path.dirname(fullpath)
423 create = not os.path.isdir(full_dir)
425 os.makedirs(full_dir)
427 return open(fullpath, 'w')
430 os.removedirs(full_dir)
434 from m_lib.defenc import default_encoding
435 recode_charset = 1 # recode charset of message body
439 # A list of headers to decode
440 decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
443 # A list of headers parameters to decode
444 decode_header_params = [
445 ("Content-Type", "name"),
446 ("Content-Disposition", "filename"),
449 # A list of headers to remove
451 # A list of headers parameters to remove
452 remove_headers_params = []
454 # A list of header/value pairs to set
455 set_header_value = []
456 # A list of header/parameter/value triples to set
457 set_header_param = []
459 totext_mask = [] # A list of content-types to decode
460 binary_mask = [] # A list of content-types to pass through
461 decoded_binary_mask = [] # A list of content-types to pass through (content-transfer-decoded)
462 ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
463 error_mask = [] # Raise error if encounter one of these
466 save_headers_mask = []
468 save_message_mask = []
470 input_filename = None
471 output_filename = None
472 destination_dir = os.curdir
478 from getopt import getopt, GetoptError
481 options, arguments = getopt(sys.argv[1:],
482 'hVcCDPH:f:d:p:r:R:b:B:e:i:t:O:o:',
483 ['help', 'version', 'host=',
484 'save-headers=', 'save-body=', 'save-message=',
485 'set-header=', 'set-param='])
489 for option, value in options:
490 if option in ('-h', '--help'):
492 elif option in ('-V', '--version'):
498 elif option in ('-H', '--host'):
501 g.default_encoding = value
503 if value.startswith('*'):
504 g.decode_headers = []
505 g.decode_headers.append(value)
507 g.decode_headers = []
509 g.decode_header_params.append(value.split(':', 1))
511 g.decode_header_params = []
513 g.remove_headers.append(value)
515 g.remove_headers_params.append(value.split(':', 1))
516 elif option == '--set-header':
517 g.set_header_value.append(value.split(':', 1))
518 elif option == '--set-param':
519 header, value = value.split(':', 1)
521 param, value = value.split('=', 1)
523 param, value = value.split(':', 1)
524 g.set_header_param.append((header, param, value))
526 g.totext_mask.append(value)
528 g.binary_mask.append(value)
530 g.decoded_binary_mask.append(value)
532 g.ignore_mask.append(value)
534 g.error_mask.append(value)
535 elif option == '--save-headers':
536 g.save_headers_mask.append(value)
537 elif option == '--save-body':
538 g.save_body_mask.append(value)
539 elif option == '--save-message':
540 g.save_message_mask.append(value)
542 g.destination_dir = value
544 g.output_filename = value
551 if __name__ == "__main__":
552 arguments = get_opts()
556 g.input_filename = '-'
558 if g.output_filename:
559 outfile = open_output_file(g.output_filename)
561 g.output_filename = '-'
564 if (arguments[0] == '-'):
565 g.input_filename = '-'
568 g.input_filename = arguments[0]
569 infile = open(arguments[0], 'r')
571 if g.output_filename:
572 outfile = open_output_file(g.output_filename)
574 g.output_filename = '-'
577 if g.output_filename:
578 usage(1, 'Too many output filenames')
579 if (arguments[1] == '-'):
580 g.output_filename = '-'
583 g.output_filename = arguments[1]
584 outfile = open_output_file(g.output_filename)
586 usage(1, 'Too many arguments')
588 if (infile is sys.stdin) and sys.stdin.isatty():
589 if (outfile is sys.stdout) and sys.stdout.isatty():
591 usage(1, 'Filtering from console is forbidden')
595 g.host_name = socket.gethostname()
598 output = outfile.write
601 msg = email.message_from_file(infile)
603 for header, value in g.set_header_value:
604 set_header(msg, header, value)
606 for header, param, value in g.set_header_param:
608 msg.set_param(param, value, header)