2 """Decode MIME message"""
5 from mimedecode_version import __version__, \
6 __author__, __copyright__, __license__
7 if sys.version_info[0] >= 3:
8 # Replace email.message._formatparam with _formatparam from Python 2.7
9 # to avoid re-encoding non-ascii params.
12 me = os.path.basename(sys.argv[0])
17 Broytman mimedecode.py version %s, %s
18 """ % (__version__, __copyright__))
21 def usage(code=0, errormsg=''):
24 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]]
27 sys.stderr.write(errormsg + os.linesep)
31 def output_headers(msg):
32 unix_from = msg.get_unixfrom()
36 for key, value in msg.items():
39 value = value.split(';', 1)
43 output(_decode_header(value[1], strip=False))
45 output(os.linesep) # End of headers
48 def recode_if_needed(s, charset):
49 if bytes is str: # Python2
50 if isinstance(s, bytes) and \
51 charset and charset.lower() != g.default_encoding:
52 s = s.decode(charset, "replace").\
53 encode(g.default_encoding, "replace")
55 if isinstance(s, bytes):
56 s = s.decode(charset, "replace")
60 def _decode_header(s, strip=True):
61 """Return a decoded string according to RFC 2047.
62 NOTE: This is almost the same as email.Utils.decode.
66 L = email.header.decode_header(s)
67 if not isinstance(L, list):
72 for atom, charset in L:
73 atom = recode_if_needed(atom, charset or g.default_encoding)
78 # Now that we've decoded everything, we just need to join all the parts
79 # together into the final string.
82 def decode_header(msg, header):
83 "Decode mail header (if exists) and put it back, if it was encoded"
87 new_value = _decode_header(value)
88 if new_value != value: # do not bother to touch msg if not changed
89 set_header(msg, header, new_value)
92 def decode_header_param(msg, header, param):
93 "Decode mail header's parameter (if exists) and put it back, if it was encoded"
96 value = msg.get_param(param, header=header)
98 if isinstance(value, tuple):
99 new_value = recode_if_needed(value[2], value[0])
101 new_value = _decode_header(value)
102 if new_value != value: # do not bother to touch msg if not changed
103 msg.set_param(param, new_value, header)
106 def _get_exceptions(list):
107 return [x[1:].lower() for x in list[1:] if x[0]=='-']
109 def _decode_headers_params(msg, header, decode_all_params, param_list):
110 if decode_all_params:
111 params = msg.get_params(header=header)
113 for param, value in params:
114 if param not in param_list:
115 decode_header_param(msg, header, param)
117 for param in param_list:
118 decode_header_param(msg, header, param)
120 def _remove_headers_params(msg, header, remove_all_params, param_list):
121 if remove_all_params:
122 params = msg.get_params(header=header)
125 for param, value in params:
126 if param not in param_list:
127 msg.del_param(param, header)
130 if value is None: # No such header
132 if ';' not in value: # There are no parameters
134 del msg[header] # Delete all such headers
135 # Get the value without parameters and set it back
136 msg[header] = value.split(';')[0].strip()
138 for param in param_list:
139 msg.del_param(param, header)
141 def decode_headers(msg):
142 "Decode message headers according to global options"
144 for header_list in g.remove_headers:
145 header_list = header_list.split(',')
146 if header_list[0] == '*': # Remove 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:
151 else: # Remove listed headers
152 for header in header_list:
155 for header_list, param_list in g.remove_headers_params:
156 header_list = header_list.split(',')
157 param_list = param_list.split(',')
158 remove_all_params = param_list[0] == '*' # Remove all params except listed
159 if remove_all_params:
160 param_list = _get_exceptions(param_list)
161 if header_list[0] == '*': # Remove for all headers except listed
162 header_list = _get_exceptions(header_list)
163 for header in msg.keys():
164 if header.lower() not in header_list:
165 _remove_headers_params(msg, header, remove_all_params, param_list)
166 else: # Decode for listed headers
167 for header in header_list:
168 _remove_headers_params(msg, header, remove_all_params, param_list)
170 for header_list in g.decode_headers:
171 header_list = header_list.split(',')
172 if header_list[0] == '*': # Decode 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_header(msg, header)
177 else: # Decode listed headers
178 for header in header_list:
179 decode_header(msg, header)
181 for header_list, param_list in g.decode_header_params:
182 header_list = header_list.split(',')
183 param_list = param_list.split(',')
184 decode_all_params = param_list[0] == '*' # Decode all params except listed
185 if decode_all_params:
186 param_list = _get_exceptions(param_list)
187 if header_list[0] == '*': # Decode for all headers except listed
188 header_list = _get_exceptions(header_list)
189 for header in msg.keys():
190 if header.lower() not in header_list:
191 _decode_headers_params(msg, header, decode_all_params, param_list)
192 else: # Decode for listed headers
193 for header in header_list:
194 _decode_headers_params(msg, header, decode_all_params, param_list)
197 def set_header(msg, header, value):
201 msg.replace_header(header, value)
206 def set_content_type(msg, newtype, charset=None):
207 msg.set_type(newtype)
210 msg.set_param("charset", charset, "Content-Type")
213 caps = None # Globally stored mailcap database; initialized only if needed
215 def decode_body(msg, s):
216 "Decode body to plain text using first copiousoutput filter from mailcap"
218 import mailcap, tempfile
222 caps = mailcap.getcaps()
224 content_type = msg.get_content_type()
225 if content_type.startswith('text/'):
226 charset = msg.get_content_charset()
229 filename = tempfile.mktemp()
232 entries = mailcap.lookup(caps, content_type, "view")
233 for entry in entries:
234 if 'copiousoutput' in entry:
236 test = mailcap.subst(entry['test'], content_type, filename)
237 if test and os.system(test) != 0:
239 command = mailcap.subst(entry["view"], content_type, filename)
245 outfile = open(filename, 'wb')
246 if charset and bytes is not str and isinstance(s, bytes): # Python3
247 s = s.decode(charset, "replace")
248 if not isinstance(s, bytes):
249 s = s.encode(g.default_encoding, "replace")
253 pipe = os.popen(command, 'r')
255 if pipe.close() is None: # result=0, Ok
259 set_content_type(msg, "text/plain")
261 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
263 msg["X-MIME-Autoconverted"] = "failed conversion from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
268 def recode_charset(msg, s):
269 "Recode charset of the message to the default charset"
271 save_charset = charset = msg.get_content_charset()
272 if charset and charset.lower() != g.default_encoding:
273 s = recode_if_needed(s, charset)
274 content_type = msg.get_content_type()
275 set_content_type(msg, content_type, g.default_encoding)
276 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, g.default_encoding, g.host_name, me)
280 def totext(msg, instring):
281 "Convert instring content to text"
283 # Decode body and recode charset
284 s = decode_body(msg, instring)
286 s = recode_charset(msg, s)
295 def _guess_extension(ctype):
297 if mimetypes is None:
300 user_mime_type = os.path.expanduser('~/.mime.types')
301 if os.path.exists(user_mime_type):
302 mimetypes._db.read(user_mime_type)
303 return mimetypes.guess_extension(ctype)
305 def _save_message(msg, outstring, save_headers=False, save_body=False):
306 for header, param in (
307 ("Content-Disposition", "filename"),
308 ("Content-Type", "name"),
310 fname = msg.get_param(param, header=header)
312 if isinstance(fname, tuple):
313 fname = fname[2] # Do not recode if it isn't recoded yet
315 for forbidden in chr(0), '/', '\\':
316 if forbidden in fname:
325 fname = str(g.save_counter) + fname
327 ext = _guess_extension(msg.get_content_type())
332 outfile = open_output_file(fname)
333 def _output_bytes(s):
334 if not isinstance(s, bytes):
335 s = s.encode(g.default_encoding, "replace")
337 output = _output_bytes
346 def decode_part(msg):
347 "Decode one part of the message"
351 # Test all mask lists and find what to do with this content type
353 ctype = msg.get_content_type()
356 mtype = ctype.split('/')[0]
357 masks.append(mtype + '/*')
361 for content_type in masks:
362 if content_type in g.totext_mask or \
363 content_type in g.decoded_binary_mask:
365 elif content_type in g.binary_mask:
368 elif content_type in g.fully_ignore_mask:
371 encoding = msg["Content-Transfer-Encoding"]
372 if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
373 outstring = msg.get_payload()
374 else: # Decode from transfer ecoding to text or binary form
375 outstring = msg.get_payload(decode=1)
376 set_header(msg, "Content-Transfer-Encoding", "8bit")
377 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, g.host_name, me)
379 for content_type in masks:
380 if content_type in g.totext_mask:
381 outstring = totext(msg, outstring)
383 elif content_type in g.binary_mask or \
384 content_type in g.decoded_binary_mask:
388 elif content_type in g.ignore_mask:
390 output("%sMessage body of type %s skipped.%s" % (os.linesep, ctype, os.linesep))
392 elif content_type in g.error_mask:
395 # Neither content type nor masks were listed - decode by default
396 outstring = totext(msg, outstring)
398 for content_type in masks:
399 if content_type in g.save_headers_mask:
400 _save_message(msg, outstring, save_headers=True, save_body=False)
401 if content_type in g.save_body_mask:
402 _save_message(msg, outstring, save_headers=False, save_body=True)
403 if content_type in g.save_message_mask:
404 _save_message(msg, outstring, save_headers=True, save_body=True)
406 for content_type in masks:
407 if content_type in g.error_mask:
408 raise ValueError("content type %s prohibited" % ctype)
410 def decode_multipart(msg):
414 boundary = msg.get_boundary()
417 ctype = msg.get_content_type()
420 mtype = ctype.split('/')[0]
421 masks.append(mtype + '/*')
424 for content_type in masks:
425 if content_type in g.fully_ignore_mask:
427 elif content_type in g.ignore_mask:
429 output("%sMessage body of type %s skipped.%s" % (os.linesep, ctype, os.linesep))
431 output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
434 for content_type in masks:
435 if content_type in g.save_body_mask or \
436 content_type in g.save_message_mask:
439 for subpart in msg.get_payload():
441 first_subpart = False
443 _out_l.append(os.linesep)
444 _out_l.append("--%s%s" % (boundary, os.linesep))
445 _out_l.append(subpart.as_string())
446 _out_l.append("%s--%s--%s" % (os.linesep, boundary, os.linesep))
447 outstring = ''.join(_out_l)
452 for content_type in masks:
453 if content_type in g.save_headers_mask:
454 _save_message(msg, outstring, save_headers=True, save_body=False)
455 if content_type in g.save_body_mask:
456 _save_message(msg, outstring, save_headers=False, save_body=True)
457 if content_type in g.save_message_mask:
458 _save_message(msg, outstring, save_headers=True, save_body=True)
460 for content_type in masks:
461 if content_type in g.error_mask:
462 raise ValueError("content type %s prohibited" % ctype)
466 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
467 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
468 if msg.preamble is not None:
472 for subpart in msg.get_payload():
475 first_subpart = False
478 output("--%s%s" % (boundary, os.linesep))
480 # Recursively decode all parts of the subpart
481 decode_message(subpart)
484 output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
490 def decode_message(msg):
493 if msg.is_multipart():
494 decode_multipart(msg)
495 elif len(msg): # Simple one-part message (there are headers) - decode it
497 else: # Not a message, just text - copy it literally
498 output(msg.as_string())
501 def open_output_file(filename):
502 fullpath = os.path.abspath(os.path.join(g.destination_dir, filename))
503 full_dir = os.path.dirname(fullpath)
504 create = not os.path.isdir(full_dir)
506 os.makedirs(full_dir)
508 return open(fullpath, 'wb')
511 os.removedirs(full_dir)
515 from m_lib.defenc import default_encoding
516 recode_charset = 1 # recode charset of message body
520 # A list of headers to decode
521 decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
524 # A list of headers parameters to decode
525 decode_header_params = [
526 ("Content-Type", "name"),
527 ("Content-Disposition", "filename"),
530 # A list of headers to remove
532 # A list of headers parameters to remove
533 remove_headers_params = []
535 # A list of header/value pairs to set
536 set_header_value = []
537 # A list of header/parameter/value triples to set
538 set_header_param = []
540 totext_mask = [] # A list of content-types to decode
541 binary_mask = [] # A list of content-types to pass through
542 decoded_binary_mask = [] # A list of content-types to pass through (content-transfer-decoded)
543 ignore_mask = [] # Ignore (do not decode and do not include into output) but output a warning instead of the body
544 fully_ignore_mask = [] # Completely ignore - no headers, no body, no warning
545 error_mask = [] # Raise error if encounter one of these
548 save_headers_mask = []
550 save_message_mask = []
552 input_filename = None
553 output_filename = None
554 destination_dir = os.curdir
560 from getopt import getopt, GetoptError
563 options, arguments = getopt(sys.argv[1:],
564 'hVcCDPH:f:d:p:r:R:b:B:e:I:i:t:O:o:',
565 ['help', 'version', 'host=',
566 'save-headers=', 'save-body=', 'save-message=',
567 'set-header=', 'set-param='])
571 for option, value in options:
572 if option in ('-h', '--help'):
574 elif option in ('-V', '--version'):
580 elif option in ('-H', '--host'):
583 g.default_encoding = value
585 if value.startswith('*'):
586 g.decode_headers = []
587 g.decode_headers.append(value)
589 g.decode_headers = []
591 g.decode_header_params.append(value.split(':', 1))
593 g.decode_header_params = []
595 g.remove_headers.append(value)
597 g.remove_headers_params.append(value.split(':', 1))
598 elif option == '--set-header':
599 g.set_header_value.append(value.split(':', 1))
600 elif option == '--set-param':
601 header, value = value.split(':', 1)
603 param, value = value.split('=', 1)
605 param, value = value.split(':', 1)
606 g.set_header_param.append((header, param, value))
608 g.totext_mask.append(value)
610 g.binary_mask.append(value)
612 g.decoded_binary_mask.append(value)
614 g.fully_ignore_mask.append(value)
616 g.ignore_mask.append(value)
618 g.error_mask.append(value)
619 elif option == '--save-headers':
620 g.save_headers_mask.append(value)
621 elif option == '--save-body':
622 g.save_body_mask.append(value)
623 elif option == '--save-message':
624 g.save_message_mask.append(value)
626 g.destination_dir = value
628 g.output_filename = value
635 if __name__ == "__main__":
636 arguments = get_opts()
640 g.input_filename = '-'
642 if g.output_filename:
643 outfile = open_output_file(g.output_filename)
645 g.output_filename = '-'
648 if (arguments[0] == '-'):
649 g.input_filename = '-'
652 g.input_filename = arguments[0]
653 infile = open(arguments[0], 'r')
655 if g.output_filename:
656 outfile = open_output_file(g.output_filename)
658 g.output_filename = '-'
661 if g.output_filename:
662 usage(1, 'Too many output filenames')
663 if (arguments[1] == '-'):
664 g.output_filename = '-'
667 g.output_filename = arguments[1]
668 outfile = open_output_file(g.output_filename)
670 usage(1, 'Too many arguments')
672 if (infile is sys.stdin) and sys.stdin.isatty():
673 if (outfile is sys.stdout) and sys.stdout.isatty():
675 usage(1, 'Filtering from console is forbidden')
679 g.host_name = socket.gethostname()
682 if hasattr(outfile, 'buffer'):
684 if not isinstance(s, bytes):
685 s = s.encode(g.default_encoding, "replace")
686 outfile.buffer.write(s)
687 output = output_bytes
689 output = outfile.write
692 msg = email.message_from_file(infile)
694 for header, value in g.set_header_value:
695 set_header(msg, header, value)
697 for header, param, value in g.set_header_param:
699 msg.set_param(param, value, header)