2 """Decode MIME message"""
6 from mimedecode_version import __version__, \
7 __author__, __copyright__, __license__
8 if sys.version_info[0] >= 3:
9 # Replace email.message._formatparam with _formatparam from Python 2.7
10 # to avoid re-encoding non-ascii params.
13 me = os.path.basename(sys.argv[0])
18 Broytman mimedecode.py version %s, %s
19 """ % (__version__, __copyright__))
22 def usage(code=0, errormsg=''):
25 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]]
28 sys.stderr.write(errormsg + os.linesep)
32 def output_headers(msg):
33 unix_from = msg.get_unixfrom()
37 for key, value in msg.items():
40 value = value.split(';', 1)
44 output(_decode_header(value[1], strip=False))
46 output(os.linesep) # End of headers
49 def recode_if_needed(s, charset):
50 if bytes is str: # Python2
51 if isinstance(s, bytes) and \
52 charset and charset.lower() != g.default_encoding:
53 s = s.decode(charset, "replace").\
54 encode(g.default_encoding, "replace")
56 if isinstance(s, bytes):
57 s = s.decode(charset, "replace")
61 def _decode_header(s, strip=True):
62 """Return a decoded string according to RFC 2047.
63 NOTE: This is almost the same as email.Utils.decode.
67 L = email.header.decode_header(s)
68 if not isinstance(L, list):
73 for atom, charset in L:
74 atom = recode_if_needed(atom, charset or g.default_encoding)
79 # Now that we've decoded everything, we just need to join all the parts
80 # together into the final string.
83 def decode_header(msg, header):
84 "Decode mail header (if exists) and put it back, if it was encoded"
88 new_value = _decode_header(value)
89 if new_value != value: # do not bother to touch msg if not changed
90 set_header(msg, header, new_value)
93 def decode_header_param(msg, header, param):
94 "Decode mail header's parameter (if exists) and put it back, if it was encoded"
97 value = msg.get_param(param, header=header)
99 if isinstance(value, tuple):
100 new_value = recode_if_needed(value[2], value[0])
102 new_value = _decode_header(value)
103 if new_value != value: # do not bother to touch msg if not changed
104 msg.set_param(param, new_value, header)
107 def _get_exceptions(list):
108 return [x[1:].lower() for x in list[1:] if x[0]=='-']
110 def _decode_headers_params(msg, header, decode_all_params, param_list):
111 if decode_all_params:
112 params = msg.get_params(header=header)
114 for param, value in params:
115 if param not in param_list:
116 decode_header_param(msg, header, param)
118 for param in param_list:
119 decode_header_param(msg, header, param)
121 def _remove_headers_params(msg, header, remove_all_params, param_list):
122 if remove_all_params:
123 params = msg.get_params(header=header)
126 for param, value in params:
127 if param not in param_list:
128 msg.del_param(param, header)
131 if value is None: # No such header
133 if ';' not in value: # There are no parameters
135 del msg[header] # Delete all such headers
136 # Get the value without parameters and set it back
137 msg[header] = value.split(';')[0].strip()
139 for param in param_list:
140 msg.del_param(param, header)
142 def decode_headers(msg):
143 "Decode message headers according to global options"
145 for header_list in g.remove_headers:
146 header_list = header_list.split(',')
147 if header_list[0] == '*': # Remove all headers except listed
148 header_list = _get_exceptions(header_list)
149 for header in msg.keys():
150 if header.lower() not in header_list:
152 else: # Remove listed headers
153 for header in header_list:
156 for header_list, param_list in g.remove_headers_params:
157 header_list = header_list.split(',')
158 param_list = param_list.split(',')
159 remove_all_params = param_list[0] == '*' # Remove all params except listed
160 if remove_all_params:
161 param_list = _get_exceptions(param_list)
162 if header_list[0] == '*': # Remove for all headers except listed
163 header_list = _get_exceptions(header_list)
164 for header in msg.keys():
165 if header.lower() not in header_list:
166 _remove_headers_params(msg, header, remove_all_params, param_list)
167 else: # Decode for listed headers
168 for header in header_list:
169 _remove_headers_params(msg, header, remove_all_params, param_list)
171 for header_list in g.decode_headers:
172 header_list = header_list.split(',')
173 if header_list[0] == '*': # Decode all headers except listed
174 header_list = _get_exceptions(header_list)
175 for header in msg.keys():
176 if header.lower() not in header_list:
177 decode_header(msg, header)
178 else: # Decode listed headers
179 for header in header_list:
180 decode_header(msg, header)
182 for header_list, param_list in g.decode_header_params:
183 header_list = header_list.split(',')
184 param_list = param_list.split(',')
185 decode_all_params = param_list[0] == '*' # Decode all params except listed
186 if decode_all_params:
187 param_list = _get_exceptions(param_list)
188 if header_list[0] == '*': # Decode for all headers except listed
189 header_list = _get_exceptions(header_list)
190 for header in msg.keys():
191 if header.lower() not in header_list:
192 _decode_headers_params(msg, header, decode_all_params, param_list)
193 else: # Decode for listed headers
194 for header in header_list:
195 _decode_headers_params(msg, header, decode_all_params, param_list)
198 def set_header(msg, header, value):
202 msg.replace_header(header, value)
207 def set_content_type(msg, newtype, charset=None):
208 msg.set_type(newtype)
211 msg.set_param("charset", charset, "Content-Type")
214 caps = None # Globally stored mailcap database; initialized only if needed
216 def decode_body(msg, s):
217 "Decode body to plain text using first copiousoutput filter from mailcap"
219 import mailcap, tempfile
223 caps = mailcap.getcaps()
225 content_type = msg.get_content_type()
226 if content_type.startswith('text/'):
227 charset = msg.get_content_charset()
230 filename = tempfile.mktemp()
233 entries = mailcap.lookup(caps, content_type, "view")
234 for entry in entries:
235 if 'copiousoutput' in entry:
237 test = mailcap.subst(entry['test'], content_type, filename)
238 if test and os.system(test) != 0:
240 command = mailcap.subst(entry["view"], content_type, filename)
246 outfile = open(filename, 'wb')
247 if charset and bytes is not str and isinstance(s, bytes): # Python3
248 s = s.decode(charset, "replace")
249 if not isinstance(s, bytes):
250 s = s.encode(g.default_encoding, "replace")
254 pipe = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
255 new_s = pipe.stdout.read()
257 if pipe.wait() == 0: # result=0, Ok
259 if bytes is not str and isinstance(s, bytes): # Python3
260 s = s.decode(g.default_encoding, "replace")
261 if charset and not isinstance(s, bytes):
262 s = s.encode(charset, "replace")
263 set_content_type(msg, "text/plain")
264 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
266 msg["X-MIME-Autoconverted"] = "failed conversion from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
272 def recode_charset(msg, s):
273 "Recode charset of the message to the default charset"
275 save_charset = charset = msg.get_content_charset()
276 if charset and charset.lower() != g.default_encoding:
277 s = recode_if_needed(s, charset)
278 content_type = msg.get_content_type()
279 set_content_type(msg, content_type, g.default_encoding)
280 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, g.default_encoding, g.host_name, me)
284 def totext(msg, instring):
285 "Convert instring content to text"
287 # Decode body and recode charset
288 s = decode_body(msg, instring)
290 s = recode_charset(msg, s)
299 def _guess_extension(ctype):
301 if mimetypes is None:
304 user_mime_type = os.path.expanduser('~/.mime.types')
305 if os.path.exists(user_mime_type):
306 mimetypes._db.read(user_mime_type)
307 return mimetypes.guess_extension(ctype)
309 def _save_message(msg, outstring, save_headers=False, save_body=False):
310 for header, param in (
311 ("Content-Disposition", "filename"),
312 ("Content-Type", "name"),
314 fname = msg.get_param(param, header=header)
316 if isinstance(fname, tuple):
317 fname = fname[2] # Do not recode if it isn't recoded yet
319 for forbidden in chr(0), '/', '\\':
320 if forbidden in fname:
329 fname = str(g.save_counter) + fname
331 ext = _guess_extension(msg.get_content_type())
336 outfile = open_output_file(fname)
337 def _output_bytes(s):
338 if not isinstance(s, bytes):
339 s = s.encode(g.default_encoding, "replace")
341 output = _output_bytes
350 def decode_part(msg):
351 "Decode one part of the message"
355 # Test all mask lists and find what to do with this content type
357 ctype = msg.get_content_type()
360 mtype = ctype.split('/')[0]
361 masks.append(mtype + '/*')
365 for content_type in masks:
366 if content_type in g.totext_mask or \
367 content_type in g.decoded_binary_mask:
369 elif content_type in g.binary_mask:
372 elif content_type in g.fully_ignore_mask:
375 encoding = msg["Content-Transfer-Encoding"]
376 if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
377 outstring = msg.get_payload()
378 else: # Decode from transfer ecoding to text or binary form
379 outstring = msg.get_payload(decode=1)
380 set_header(msg, "Content-Transfer-Encoding", "8bit")
381 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, g.host_name, me)
383 for content_type in masks:
384 if content_type in g.totext_mask:
385 outstring = totext(msg, outstring)
387 elif content_type in g.binary_mask or \
388 content_type in g.decoded_binary_mask:
392 elif content_type in g.ignore_mask:
394 output("%sMessage body of type %s skipped.%s" % (os.linesep, ctype, os.linesep))
396 elif content_type in g.error_mask:
399 # Neither content type nor masks were listed - decode by default
400 outstring = totext(msg, outstring)
402 for content_type in masks:
403 if content_type in g.save_headers_mask:
404 _save_message(msg, outstring, save_headers=True, save_body=False)
405 if content_type in g.save_body_mask:
406 _save_message(msg, outstring, save_headers=False, save_body=True)
407 if content_type in g.save_message_mask:
408 _save_message(msg, outstring, save_headers=True, save_body=True)
410 for content_type in masks:
411 if content_type in g.error_mask:
412 raise ValueError("content type %s prohibited" % ctype)
414 def decode_multipart(msg):
418 boundary = msg.get_boundary()
421 ctype = msg.get_content_type()
424 mtype = ctype.split('/')[0]
425 masks.append(mtype + '/*')
428 for content_type in masks:
429 if content_type in g.fully_ignore_mask:
431 elif content_type in g.ignore_mask:
433 output("%sMessage body of type %s skipped.%s" % (os.linesep, ctype, os.linesep))
435 output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
438 for content_type in masks:
439 if content_type in g.save_body_mask or \
440 content_type in g.save_message_mask:
443 for subpart in msg.get_payload():
445 first_subpart = False
447 _out_l.append(os.linesep)
448 _out_l.append("--%s%s" % (boundary, os.linesep))
449 _out_l.append(subpart.as_string())
450 _out_l.append("%s--%s--%s" % (os.linesep, boundary, os.linesep))
451 outstring = ''.join(_out_l)
456 for content_type in masks:
457 if content_type in g.save_headers_mask:
458 _save_message(msg, outstring, save_headers=True, save_body=False)
459 if content_type in g.save_body_mask:
460 _save_message(msg, outstring, save_headers=False, save_body=True)
461 if content_type in g.save_message_mask:
462 _save_message(msg, outstring, save_headers=True, save_body=True)
464 for content_type in masks:
465 if content_type in g.error_mask:
466 raise ValueError("content type %s prohibited" % ctype)
470 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
471 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
472 if msg.preamble is not None:
476 for subpart in msg.get_payload():
479 first_subpart = False
482 output("--%s%s" % (boundary, os.linesep))
484 # Recursively decode all parts of the subpart
485 decode_message(subpart)
488 output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
494 def decode_message(msg):
497 if msg.is_multipart():
498 decode_multipart(msg)
499 elif len(msg): # Simple one-part message (there are headers) - decode it
501 else: # Not a message, just text - copy it literally
502 output(msg.as_string())
505 def open_output_file(filename):
506 fullpath = os.path.abspath(os.path.join(g.destination_dir, filename))
507 full_dir = os.path.dirname(fullpath)
508 create = not os.path.isdir(full_dir)
510 os.makedirs(full_dir)
512 return open(fullpath, 'wb')
515 os.removedirs(full_dir)
519 from m_lib.defenc import default_encoding
520 recode_charset = 1 # recode charset of message body
524 # A list of headers to decode
525 decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
528 # A list of headers parameters to decode
529 decode_header_params = [
530 ("Content-Type", "name"),
531 ("Content-Disposition", "filename"),
534 # A list of headers to remove
536 # A list of headers parameters to remove
537 remove_headers_params = []
539 # A list of header/value pairs to set
540 set_header_value = []
541 # A list of header/parameter/value triples to set
542 set_header_param = []
544 totext_mask = [] # A list of content-types to decode
545 binary_mask = [] # A list of content-types to pass through
546 decoded_binary_mask = [] # A list of content-types to pass through (content-transfer-decoded)
547 ignore_mask = [] # Ignore (do not decode and do not include into output) but output a warning instead of the body
548 fully_ignore_mask = [] # Completely ignore - no headers, no body, no warning
549 error_mask = [] # Raise error if encounter one of these
552 save_headers_mask = []
554 save_message_mask = []
556 input_filename = None
557 output_filename = None
558 destination_dir = os.curdir
564 from getopt import getopt, GetoptError
567 options, arguments = getopt(
569 'hVcCDPH:f:d:p:r:R:b:B:e:I:i:t:O:o:',
570 ['help', 'version', 'host=',
571 'save-headers=', 'save-body=', 'save-message=',
572 'set-header=', 'set-param='])
576 for option, value in options:
577 if option in ('-h', '--help'):
579 elif option in ('-V', '--version'):
585 elif option in ('-H', '--host'):
588 g.default_encoding = value
590 if value.startswith('*'):
591 g.decode_headers = []
592 g.decode_headers.append(value)
594 g.decode_headers = []
596 g.decode_header_params.append(value.split(':', 1))
598 g.decode_header_params = []
600 g.remove_headers.append(value)
602 g.remove_headers_params.append(value.split(':', 1))
603 elif option == '--set-header':
604 g.set_header_value.append(value.split(':', 1))
605 elif option == '--set-param':
606 header, value = value.split(':', 1)
608 param, value = value.split('=', 1)
610 param, value = value.split(':', 1)
611 g.set_header_param.append((header, param, value))
613 g.totext_mask.append(value)
615 g.binary_mask.append(value)
617 g.decoded_binary_mask.append(value)
619 g.fully_ignore_mask.append(value)
621 g.ignore_mask.append(value)
623 g.error_mask.append(value)
624 elif option == '--save-headers':
625 g.save_headers_mask.append(value)
626 elif option == '--save-body':
627 g.save_body_mask.append(value)
628 elif option == '--save-message':
629 g.save_message_mask.append(value)
631 g.destination_dir = value
633 g.output_filename = value
640 if __name__ == "__main__":
641 arguments = get_opts()
645 g.input_filename = '-'
647 if g.output_filename:
648 outfile = open_output_file(g.output_filename)
650 g.output_filename = '-'
653 if (arguments[0] == '-'):
654 g.input_filename = '-'
657 g.input_filename = arguments[0]
658 infile = open(arguments[0], 'r')
660 if g.output_filename:
661 outfile = open_output_file(g.output_filename)
663 g.output_filename = '-'
666 if g.output_filename:
667 usage(1, 'Too many output filenames')
668 if (arguments[1] == '-'):
669 g.output_filename = '-'
672 g.output_filename = arguments[1]
673 outfile = open_output_file(g.output_filename)
675 usage(1, 'Too many arguments')
677 if (infile is sys.stdin) and sys.stdin.isatty():
678 if (outfile is sys.stdout) and sys.stdout.isatty():
680 usage(1, 'Filtering from console is forbidden')
684 g.host_name = socket.gethostname()
687 if hasattr(outfile, 'buffer'):
689 if not isinstance(s, bytes):
690 s = s.encode(g.default_encoding, "replace")
691 outfile.buffer.write(s)
692 output = output_bytes
694 output = outfile.write
697 msg = email.message_from_file(infile)
699 for header, value in g.set_header_value:
700 set_header(msg, header, value)
702 for header, param, value in g.set_header_param:
704 msg.set_param(param, value, header)