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(s):
78 return recode_if_needed(s[2], s[0])
80 def decode_header_param(msg, header, param):
81 "Decode mail header's parameter (if exists) and put it back, if it was encoded"
83 if msg.has_key(header):
84 value = msg.get_param(param, header=header)
86 if isinstance(value, tuple):
87 new_value = _decode_header_param(value)
89 new_value = _decode_header(value)
90 if new_value <> value: # do not bother to touch msg if not changed
91 msg.set_param(param, new_value, header)
94 def _get_exceptions(list):
95 return [x[1:].lower() for x in list[1:] if x[0]=='-']
97 def _decode_headers_params(msg, header, decode_all_params, param_list):
99 params = msg.get_params(header=header)
101 for param, value in params:
102 if param not in param_list:
103 decode_header_param(msg, header, param)
105 for param in param_list:
106 decode_header_param(msg, header, param)
108 def _remove_headers_params(msg, header, remove_all_params, param_list):
109 if remove_all_params:
110 params = msg.get_params(header=header)
113 for param, value in params:
114 if param not in param_list:
115 msg.del_param(param, header)
118 if value is None: # No such header
120 if ';' not in value: # There are no parameters
122 del msg[header] # Delete all such headers
123 # Get the value without parameters and set it back
124 msg[header] = value.split(';')[0].strip()
126 for param in param_list:
127 msg.del_param(param, header)
129 def decode_headers(msg):
130 "Decode message headers according to global options"
132 for header_list in g.remove_headers:
133 header_list = header_list.split(',')
134 if header_list[0] == '*': # Remove all headers except listed
135 header_list = _get_exceptions(header_list)
136 for header in msg.keys():
137 if header.lower() not in header_list:
139 else: # Remove listed headers
140 for header in header_list:
143 for header_list, param_list in g.remove_headers_params:
144 header_list = header_list.split(',')
145 param_list = param_list.split(',')
146 remove_all_params = param_list[0] == '*' # Remove all params except listed
147 if remove_all_params:
148 param_list = _get_exceptions(param_list)
149 if header_list[0] == '*': # Remove for all headers except listed
150 header_list = _get_exceptions(header_list)
151 for header in msg.keys():
152 if header.lower() not in header_list:
153 _remove_headers_params(msg, header, remove_all_params, param_list)
154 else: # Decode for listed headers
155 for header in header_list:
156 _remove_headers_params(msg, header, remove_all_params, param_list)
158 for header_list in g.decode_headers:
159 header_list = header_list.split(',')
160 if header_list[0] == '*': # Decode all headers except listed
161 header_list = _get_exceptions(header_list)
162 for header in msg.keys():
163 if header.lower() not in header_list:
164 decode_header(msg, header)
165 else: # Decode listed headers
166 for header in header_list:
167 decode_header(msg, header)
169 for header_list, param_list in g.decode_header_params:
170 header_list = header_list.split(',')
171 param_list = param_list.split(',')
172 decode_all_params = param_list[0] == '*' # Decode all params except listed
173 if decode_all_params:
174 param_list = _get_exceptions(param_list)
175 if header_list[0] == '*': # Decode for all headers except listed
176 header_list = _get_exceptions(header_list)
177 for header in msg.keys():
178 if header.lower() not in header_list:
179 _decode_headers_params(msg, header, decode_all_params, param_list)
180 else: # Decode for listed headers
181 for header in header_list:
182 _decode_headers_params(msg, header, decode_all_params, param_list)
185 def set_header(msg, header, value):
188 if msg.has_key(header):
189 msg.replace_header(header, value)
194 def set_content_type(msg, newtype, charset=None):
195 msg.set_type(newtype)
198 msg.set_param("charset", charset, "Content-Type")
201 caps = None # Globally stored mailcap database; initialized only if needed
203 def decode_body(msg, s):
204 "Decode body to plain text using first copiousoutput filter from mailcap"
206 import mailcap, tempfile
210 caps = mailcap.getcaps()
212 content_type = msg.get_content_type()
213 filename = tempfile.mktemp()
216 entries = mailcap.lookup(caps, content_type, "view")
217 for entry in entries:
218 if entry.has_key('copiousoutput'):
219 if entry.has_key('test'):
220 test = mailcap.subst(entry['test'], content_type, filename)
221 if test and os.system(test) != 0:
223 command = mailcap.subst(entry["view"], content_type, filename)
229 file = open(filename, 'w')
233 pipe = os.popen(command, 'r')
238 set_content_type(msg, "text/plain")
239 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
244 def recode_charset(msg, s):
245 "Recode charset of the message to the default charset"
247 save_charset = charset = msg.get_content_charset()
248 if charset and charset.lower() <> g.default_encoding:
249 s = recode_if_needed(s, charset)
250 content_type = msg.get_content_type()
251 set_content_type(msg, content_type, g.default_encoding)
252 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, g.default_encoding, g.host_name, me)
256 def totext(msg, instring):
257 "Convert instring content to text"
259 # Decode body and recode charset
260 s = decode_body(msg, instring)
262 s = recode_charset(msg, s)
269 def _save_message(msg, outstring, save_headers=False, save_body=False):
270 for header, param in (
271 ("Content-Disposition", "filename"),
272 ("Content-Type", "name"),
274 fname = msg.get_param(param, header=header)
281 fname = str(g.save_counter) + fname
285 outfile = open(os.path.join(g.destination_dir, fname), 'w')
286 output = outfile.write
295 def decode_part(msg):
296 "Decode one part of the message"
300 # Test all mask lists and find what to do with this content type
302 ctype = msg.get_content_type()
305 mtype = msg.get_content_maintype()
307 masks.append(mtype + '/*')
311 for content_type in masks:
312 if content_type in g.totext_mask or \
313 content_type in g.decoded_binary_mask:
315 elif content_type in g.binary_mask:
319 encoding = msg["Content-Transfer-Encoding"]
320 if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
321 outstring = msg.get_payload()
322 else: # Decode from transfer ecoding to text or binary form
323 outstring = msg.get_payload(decode=1)
324 set_header(msg, "Content-Transfer-Encoding", "8bit")
325 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, g.host_name, me)
327 for content_type in masks:
328 if content_type in g.totext_mask:
329 outstring = totext(msg, outstring)
331 elif content_type in g.binary_mask or \
332 content_type in g.decoded_binary_mask:
336 elif content_type in g.ignore_mask:
338 output("\nMessage body of type %s skipped.\n" % ctype)
340 elif content_type in g.error_mask:
343 # Neither content type nor masks were listed - decode by default
344 outstring = totext(msg, outstring)
346 for content_type in masks:
347 if content_type in g.save_headers_mask:
348 _save_message(msg, outstring, save_headers=True, save_body=False)
349 elif content_type in g.save_body_mask:
350 _save_message(msg, outstring, save_headers=False, save_body=True)
351 elif content_type in g.save_message_mask:
352 _save_message(msg, outstring, save_headers=True, save_body=True)
354 for content_type in masks:
355 if content_type in g.error_mask:
356 raise ValueError, "content type %s prohibited" % ctype
358 def decode_multipart(msg):
364 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
365 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
366 if msg.preamble is not None:
370 boundary = msg.get_boundary()
372 for subpart in msg.get_payload():
375 first_subpart = False
378 output("--%s\n" % boundary)
380 # Recursively decode all parts of the subpart
381 decode_message(subpart)
384 output("\n--%s--\n" % boundary)
390 def decode_message(msg):
393 if msg.is_multipart():
394 decode_multipart(msg)
395 elif len(msg): # Simple one-part message (there are headers) - decode it
397 else: # Not a message, just text - copy it literally
398 output(msg.as_string())
402 from m_lib.defenc import default_encoding
403 recode_charset = 1 # recode charset of message body
407 # A list of headers to decode
408 decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
411 # A list of headers parameters to decode
412 decode_header_params = [
413 ("Content-Type", "name"),
414 ("Content-Disposition", "filename"),
417 # A list of headers to remove
419 # A list of headers parameters to remove
420 remove_headers_params = []
422 # A list of header/value pairs to set
423 set_header_value = []
424 # A list of header/parameter/value triples to set
425 set_header_param = []
427 totext_mask = [] # A list of content-types to decode
428 binary_mask = [] # A list of content-types to pass through
429 decoded_binary_mask = [] # A list of content-types to pass through (content-transfer-decoded)
430 ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
431 error_mask = [] # Raise error if encounter one of these
434 save_headers_mask = []
436 save_message_mask = []
438 input_filename = None
439 output_filename = None
440 destination_dir = os.curdir
446 from getopt import getopt, GetoptError
449 options, arguments = getopt(sys.argv[1:],
450 'hVcCDPH:f:d:p:r:R:b:B:e:i:t:O:o:',
451 ['help', 'version', 'host=',
452 'save-headers=', 'save-body=', 'save-message=',
453 'set-header=', 'set-param='])
457 for option, value in options:
458 if option in ('-h', '--help'):
460 elif option in ('-V', '--version'):
466 elif option in ('-H', '--host'):
469 g.default_encoding = value
471 if value.startswith('*'):
472 g.decode_headers = []
473 g.decode_headers.append(value)
475 g.decode_headers = []
477 g.decode_header_params.append(value.split(':', 1))
479 g.decode_header_params = []
481 g.remove_headers.append(value)
483 g.remove_headers_params.append(value.split(':', 1))
484 elif option == '--set-header':
485 g.set_header_value.append(value.split(':', 1))
486 elif option == '--set-param':
487 header, value = value.split(':', 1)
489 param, value = value.split('=', 1)
491 param, value = value.split(':', 1)
492 g.set_header_param.append((header, param, value))
494 g.totext_mask.append(value)
496 g.binary_mask.append(value)
498 g.decoded_binary_mask.append(value)
500 g.ignore_mask.append(value)
502 g.error_mask.append(value)
503 elif option == '--save-headers':
504 g.save_headers_mask.append(value)
505 elif option == '--save-body':
506 g.save_body_mask.append(value)
507 elif option == '--save-message':
508 g.save_message_mask.append(value)
510 g.destination_dir = value
512 g.output_filename = value
519 if __name__ == "__main__":
520 arguments = get_opts()
524 g.input_filename = '-'
526 if g.output_filename:
527 outfile = open(os.path.join(g.destination_dir, g.output_filename), 'w')
529 g.output_filename = '-'
532 if (arguments[0] == '-'):
533 g.input_filename = '-'
536 g.input_filename = arguments[0]
537 infile = open(arguments[0], 'r')
539 if g.output_filename:
540 outfile = open(os.path.join(g.destination_dir, g.output_filename), 'w')
542 g.output_filename = '-'
545 if g.output_filename:
546 usage(1, 'Too many output filenames')
547 if (arguments[1] == '-'):
548 g.output_filename = '-'
551 g.output_filename = arguments[1]
552 outfile = open(os.path.join(g.destination_dir, g.output_filename), 'w')
554 usage(1, 'Too many arguments')
556 if (infile is sys.stdin) and sys.stdin.isatty():
557 if (outfile is sys.stdout) and sys.stdout.isatty():
559 usage(1, 'Filtering from console is forbidden')
563 g.host_name = socket.gethostname()
566 output = outfile.write
568 msg = email.message_from_file(infile)
570 for header, value in g.set_header_value:
573 for header, param, value in g.set_header_param:
575 msg.set_param(param, value, header)