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 + os.linesep)
27 def output_headers(msg):
28 unix_from = msg.get_unixfrom()
30 output(unix_from + os.linesep)
31 for key, value in msg.items():
32 output("%s: %s%s" % (key, value, os.linesep))
33 output(os.linesep) # 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 outfile = open(filename, 'wb')
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 = ctype.split('/')[0]
325 masks.append(mtype + '/*')
329 for content_type in masks:
330 if content_type in g.totext_mask or \
331 content_type in g.decoded_binary_mask:
333 elif content_type in g.binary_mask:
337 encoding = msg["Content-Transfer-Encoding"]
338 if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
339 outstring = msg.get_payload()
340 else: # Decode from transfer ecoding to text or binary form
341 outstring = msg.get_payload(decode=1)
342 set_header(msg, "Content-Transfer-Encoding", "8bit")
343 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, g.host_name, me)
345 for content_type in masks:
346 if content_type in g.totext_mask:
347 outstring = totext(msg, outstring)
349 elif content_type in g.binary_mask or \
350 content_type in g.decoded_binary_mask:
354 elif content_type in g.ignore_mask:
356 output("%sMessage body of type %s skipped.%s" % (os.linesep, ctype, os.linesep))
358 elif content_type in g.error_mask:
361 # Neither content type nor masks were listed - decode by default
362 outstring = totext(msg, outstring)
364 for content_type in masks:
365 if content_type in g.save_headers_mask:
366 _save_message(msg, outstring, save_headers=True, save_body=False)
367 elif content_type in g.save_body_mask:
368 _save_message(msg, outstring, save_headers=False, save_body=True)
369 elif content_type in g.save_message_mask:
370 _save_message(msg, outstring, save_headers=True, save_body=True)
372 for content_type in masks:
373 if content_type in g.error_mask:
374 raise ValueError, "content type %s prohibited" % ctype
376 def decode_multipart(msg):
382 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
383 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
384 if msg.preamble is not None:
388 boundary = msg.get_boundary()
390 for subpart in msg.get_payload():
393 first_subpart = False
396 output("--%s%s" % (boundary, os.linesep))
398 # Recursively decode all parts of the subpart
399 decode_message(subpart)
402 output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
408 def decode_message(msg):
411 if msg.is_multipart():
412 decode_multipart(msg)
413 elif len(msg): # Simple one-part message (there are headers) - decode it
415 else: # Not a message, just text - copy it literally
416 output(msg.as_string())
419 def open_output_file(filename):
420 fullpath = os.path.abspath(os.path.join(g.destination_dir, filename))
421 full_dir = os.path.dirname(fullpath)
422 create = not os.path.isdir(full_dir)
424 os.makedirs(full_dir)
426 return open(fullpath, 'wb')
429 os.removedirs(full_dir)
433 from m_lib.defenc import default_encoding
434 recode_charset = 1 # recode charset of message body
438 # A list of headers to decode
439 decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
442 # A list of headers parameters to decode
443 decode_header_params = [
444 ("Content-Type", "name"),
445 ("Content-Disposition", "filename"),
448 # A list of headers to remove
450 # A list of headers parameters to remove
451 remove_headers_params = []
453 # A list of header/value pairs to set
454 set_header_value = []
455 # A list of header/parameter/value triples to set
456 set_header_param = []
458 totext_mask = [] # A list of content-types to decode
459 binary_mask = [] # A list of content-types to pass through
460 decoded_binary_mask = [] # A list of content-types to pass through (content-transfer-decoded)
461 ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
462 error_mask = [] # Raise error if encounter one of these
465 save_headers_mask = []
467 save_message_mask = []
469 input_filename = None
470 output_filename = None
471 destination_dir = os.curdir
477 from getopt import getopt, GetoptError
480 options, arguments = getopt(sys.argv[1:],
481 'hVcCDPH:f:d:p:r:R:b:B:e:i:t:O:o:',
482 ['help', 'version', 'host=',
483 'save-headers=', 'save-body=', 'save-message=',
484 'set-header=', 'set-param='])
488 for option, value in options:
489 if option in ('-h', '--help'):
491 elif option in ('-V', '--version'):
497 elif option in ('-H', '--host'):
500 g.default_encoding = value
502 if value.startswith('*'):
503 g.decode_headers = []
504 g.decode_headers.append(value)
506 g.decode_headers = []
508 g.decode_header_params.append(value.split(':', 1))
510 g.decode_header_params = []
512 g.remove_headers.append(value)
514 g.remove_headers_params.append(value.split(':', 1))
515 elif option == '--set-header':
516 g.set_header_value.append(value.split(':', 1))
517 elif option == '--set-param':
518 header, value = value.split(':', 1)
520 param, value = value.split('=', 1)
522 param, value = value.split(':', 1)
523 g.set_header_param.append((header, param, value))
525 g.totext_mask.append(value)
527 g.binary_mask.append(value)
529 g.decoded_binary_mask.append(value)
531 g.ignore_mask.append(value)
533 g.error_mask.append(value)
534 elif option == '--save-headers':
535 g.save_headers_mask.append(value)
536 elif option == '--save-body':
537 g.save_body_mask.append(value)
538 elif option == '--save-message':
539 g.save_message_mask.append(value)
541 g.destination_dir = value
543 g.output_filename = value
550 if __name__ == "__main__":
551 arguments = get_opts()
555 g.input_filename = '-'
557 if g.output_filename:
558 outfile = open_output_file(g.output_filename)
560 g.output_filename = '-'
563 if (arguments[0] == '-'):
564 g.input_filename = '-'
567 g.input_filename = arguments[0]
568 infile = open(arguments[0], 'r')
570 if g.output_filename:
571 outfile = open_output_file(g.output_filename)
573 g.output_filename = '-'
576 if g.output_filename:
577 usage(1, 'Too many output filenames')
578 if (arguments[1] == '-'):
579 g.output_filename = '-'
582 g.output_filename = arguments[1]
583 outfile = open_output_file(g.output_filename)
585 usage(1, 'Too many arguments')
587 if (infile is sys.stdin) and sys.stdin.isatty():
588 if (outfile is sys.stdout) and sys.stdout.isatty():
590 usage(1, 'Filtering from console is forbidden')
594 g.host_name = socket.gethostname()
597 output = outfile.write
600 msg = email.message_from_file(infile)
602 for header, value in g.set_header_value:
603 set_header(msg, header, value)
605 for header, param, value in g.set_header_param:
607 msg.set_param(param, value, header)