2 """Decode MIME message"""
8 from mimedecode_version import __version__, __copyright__
10 if sys.version_info[0] >= 3:
11 # Replace email.message._formatparam with _formatparam from Python 2.7
12 # to avoid re-encoding non-ascii params.
13 import formatparam_27 # noqa: F401: Imported for its side effect
15 me = os.path.basename(sys.argv[0])
20 Broytman mimedecode.py version %s, %s
21 """ % (__version__, __copyright__))
26 def usage(code=0, errormsg=''):
29 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]]
30 """ % me) # noqa: E501
32 sys.stderr.write(errormsg + os.linesep)
36 def output_headers(msg):
37 unix_from = msg.get_unixfrom()
41 for key, value in msg.items():
44 value = value.split(';', 1)
48 output(_decode_header(value[1], strip=False))
50 output(os.linesep) # End of headers
53 def recode_if_needed(s, charset):
54 if bytes is str: # Python2
55 if isinstance(s, bytes) and \
56 charset and charset.lower() != g.default_encoding:
57 s = s.decode(charset, "replace").\
58 encode(g.default_encoding, "replace")
60 if isinstance(s, bytes):
61 s = s.decode(charset, "replace")
65 def _decode_header(s, strip=True):
66 """Return a decoded string according to RFC 2047.
67 NOTE: This is almost the same as email.Utils.decode.
71 L = email.header.decode_header(s)
72 if not isinstance(L, list):
77 for atom, charset in L:
78 atom = recode_if_needed(atom, charset or g.default_encoding)
83 # Now that we've decoded everything, we just need to join all the parts
84 # together into the final string.
88 def decode_header(msg, header):
89 "Decode mail header (if exists) and put it back, if it was encoded"
93 new_value = _decode_header(value)
94 if new_value != value: # do not bother to touch msg if not changed
95 set_header(msg, header, new_value)
98 def decode_header_param(msg, header, param):
99 """Decode mail header's parameter
101 Decode mail header's parameter (if exists)
102 and put it back if it was encoded.
105 value = msg.get_param(param, header=header)
107 if isinstance(value, tuple):
108 new_value = recode_if_needed(value[2], value[0])
110 new_value = _decode_header(value)
111 if new_value != value: # do not bother to touch msg if not changed
112 msg.set_param(param, new_value, header)
115 def _get_exceptions(list):
116 return [x[1:].lower() for x in list[1:] if x[0] == '-']
119 def _decode_headers_params(msg, header, decode_all_params, param_list):
120 if decode_all_params:
121 params = msg.get_params(header=header)
123 for param, value in params:
124 if param not in param_list:
125 decode_header_param(msg, header, param)
127 for param in param_list:
128 decode_header_param(msg, header, param)
131 def _remove_headers_params(msg, header, remove_all_params, param_list):
132 if remove_all_params:
133 params = msg.get_params(header=header)
136 for param, value in params:
137 if param not in param_list:
138 msg.del_param(param, header)
141 if value is None: # No such header
143 if ';' not in value: # There are no parameters
145 del msg[header] # Delete all such headers
146 # Get the value without parameters and set it back
147 msg[header] = value.split(';')[0].strip()
149 for param in param_list:
150 msg.del_param(param, header)
153 def decode_headers(msg):
154 "Decode message headers according to global options"
156 for header_list in g.remove_headers:
157 header_list = header_list.split(',')
158 if header_list[0] == '*': # Remove all headers except listed
159 header_list = _get_exceptions(header_list)
160 for header in msg.keys():
161 if header.lower() not in header_list:
163 else: # Remove listed headers
164 for header in header_list:
167 for header_list, param_list in g.remove_headers_params:
168 header_list = header_list.split(',')
169 param_list = param_list.split(',')
170 # Remove all params except listed.
171 remove_all_params = param_list[0] == '*'
172 if remove_all_params:
173 param_list = _get_exceptions(param_list)
174 if header_list[0] == '*': # Remove for all headers except listed
175 header_list = _get_exceptions(header_list)
176 for header in msg.keys():
177 if header.lower() not in header_list:
178 _remove_headers_params(
179 msg, header, remove_all_params, param_list)
180 else: # Decode for listed headers
181 for header in header_list:
182 _remove_headers_params(
183 msg, header, remove_all_params, param_list)
185 for header_list in g.decode_headers:
186 header_list = header_list.split(',')
187 if header_list[0] == '*': # Decode 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_header(msg, header)
192 else: # Decode listed headers
193 for header in header_list:
194 decode_header(msg, header)
196 for header_list, param_list in g.decode_header_params:
197 header_list = header_list.split(',')
198 param_list = param_list.split(',')
199 # Decode all params except listed.
200 decode_all_params = param_list[0] == '*'
201 if decode_all_params:
202 param_list = _get_exceptions(param_list)
203 if header_list[0] == '*': # Decode for all headers except listed
204 header_list = _get_exceptions(header_list)
205 for header in msg.keys():
206 if header.lower() not in header_list:
207 _decode_headers_params(
208 msg, header, decode_all_params, param_list)
209 else: # Decode for listed headers
210 for header in header_list:
211 _decode_headers_params(
212 msg, header, decode_all_params, param_list)
215 def set_header(msg, header, value):
219 msg.replace_header(header, value)
224 def set_content_type(msg, newtype, charset=None):
225 msg.set_type(newtype)
228 msg.set_param("charset", charset, "Content-Type")
231 caps = None # Globally stored mailcap database; initialized only if needed
234 def decode_body(msg, s):
235 "Decode body to plain text using first copiousoutput filter from mailcap"
242 caps = mailcap.getcaps()
244 content_type = msg.get_content_type()
245 if content_type.startswith('text/'):
246 charset = msg.get_content_charset()
249 filename = tempfile.mktemp()
252 entries = mailcap.lookup(caps, content_type, "view")
253 for entry in entries:
254 if 'copiousoutput' in entry:
256 test = mailcap.subst(entry['test'], content_type, filename)
257 if test and os.system(test) != 0:
259 command = mailcap.subst(entry["view"], content_type, filename)
265 outfile = open(filename, 'wb')
266 if charset and bytes is not str and isinstance(s, bytes): # Python3
267 s = s.decode(charset, "replace")
268 if not isinstance(s, bytes):
269 s = s.encode(g.default_encoding, "replace")
273 pipe = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
274 new_s = pipe.stdout.read()
276 if pipe.wait() == 0: # result=0, Ok
278 if bytes is not str and isinstance(s, bytes): # Python3
279 s = s.decode(g.default_encoding, "replace")
280 if charset and not isinstance(s, bytes):
281 s = s.encode(charset, "replace")
282 set_content_type(msg, "text/plain")
283 msg["X-MIME-Autoconverted"] = \
284 "from %s to text/plain by %s id %s" \
285 % (content_type, g.host_name, command.split()[0])
287 msg["X-MIME-Autoconverted"] = \
288 "failed conversion from %s to text/plain by %s id %s" \
289 % (content_type, g.host_name, command.split()[0])
295 def recode_charset(msg, s):
296 "Recode charset of the message to the default charset"
298 save_charset = charset = msg.get_content_charset()
299 if charset and charset.lower() != g.default_encoding:
300 s = recode_if_needed(s, charset)
301 content_type = msg.get_content_type()
302 set_content_type(msg, content_type, g.default_encoding)
303 msg["X-MIME-Autoconverted"] = \
304 "from %s to %s by %s id %s" \
305 % (save_charset, g.default_encoding, g.host_name, me)
309 def totext(msg, instring):
310 "Convert instring content to text"
312 # Decode body and recode charset
313 s = decode_body(msg, instring)
315 s = recode_charset(msg, s)
325 def _guess_extension(ctype):
327 if mimetypes is None:
330 user_mime_type = os.path.expanduser('~/.mime.types')
331 if os.path.exists(user_mime_type):
332 mimetypes._db.read(user_mime_type)
333 return mimetypes.guess_extension(ctype)
336 def _save_message(msg, outstring, save_headers=False, save_body=False):
337 for header, param in (
338 ("Content-Disposition", "filename"),
339 ("Content-Type", "name"),
341 fname = msg.get_param(param, header=header)
343 if isinstance(fname, tuple):
344 fname = fname[2] # Do not recode if it isn't recoded yet
346 for forbidden in chr(0), '/', '\\':
347 if forbidden in fname:
356 fname = str(g.save_counter) + fname
358 ext = _guess_extension(msg.get_content_type())
364 outfile = open_output_file(fname)
366 def _output_bytes(s):
367 if not isinstance(s, bytes):
368 s = s.encode(g.default_encoding, "replace")
371 output = _output_bytes
380 def decode_part(msg):
381 "Decode one part of the message"
385 # Test all mask lists and find what to do with this content type
387 ctype = msg.get_content_type()
390 mtype = ctype.split('/')[0]
391 masks.append(mtype + '/*')
395 for content_type in masks:
396 if content_type in g.totext_mask or \
397 content_type in g.decoded_binary_mask:
399 elif content_type in g.binary_mask:
402 elif content_type in g.fully_ignore_mask:
405 encoding = msg["Content-Transfer-Encoding"]
406 if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
407 outstring = msg.get_payload()
408 else: # Decode from transfer ecoding to text or binary form
409 outstring = msg.get_payload(decode=1)
410 set_header(msg, "Content-Transfer-Encoding", "8bit")
411 msg["X-MIME-Autoconverted"] = \
412 "from %s to 8bit by %s id %s" % (encoding, g.host_name, me)
414 for content_type in masks:
415 if content_type in g.totext_mask:
416 outstring = totext(msg, outstring)
418 elif content_type in g.binary_mask or \
419 content_type in g.decoded_binary_mask:
423 elif content_type in g.ignore_mask:
425 output("%sMessage body of type %s skipped.%s"
426 % (os.linesep, ctype, os.linesep))
428 elif content_type in g.error_mask:
431 # Neither content type nor masks were listed - decode by default
432 outstring = totext(msg, outstring)
434 for content_type in masks:
435 if content_type in g.save_headers_mask:
436 _save_message(msg, outstring, save_headers=True, save_body=False)
437 if content_type in g.save_body_mask:
438 _save_message(msg, outstring, save_headers=False, save_body=True)
439 if content_type in g.save_message_mask:
440 _save_message(msg, outstring, save_headers=True, save_body=True)
442 for content_type in masks:
443 if content_type in g.error_mask:
444 raise ValueError("content type %s prohibited" % ctype)
447 def decode_multipart(msg):
451 boundary = msg.get_boundary()
454 ctype = msg.get_content_type()
457 mtype = ctype.split('/')[0]
458 masks.append(mtype + '/*')
461 for content_type in masks:
462 if content_type in g.fully_ignore_mask:
464 elif content_type in g.ignore_mask:
466 output("%sMessage body of type %s skipped.%s"
467 % (os.linesep, ctype, os.linesep))
469 output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
472 for content_type in masks:
473 if content_type in g.save_body_mask or \
474 content_type in g.save_message_mask:
477 for subpart in msg.get_payload():
479 first_subpart = False
481 _out_l.append(os.linesep)
482 _out_l.append("--%s%s" % (boundary, os.linesep))
483 _out_l.append(subpart.as_string())
484 _out_l.append("%s--%s--%s" % (os.linesep, boundary, os.linesep))
485 outstring = ''.join(_out_l)
490 for content_type in masks:
491 if content_type in g.save_headers_mask:
492 _save_message(msg, outstring, save_headers=True, save_body=False)
493 if content_type in g.save_body_mask:
494 _save_message(msg, outstring, save_headers=False, save_body=True)
495 if content_type in g.save_message_mask:
496 _save_message(msg, outstring, save_headers=True, save_body=True)
498 for content_type in masks:
499 if content_type in g.error_mask:
500 raise ValueError("content type %s prohibited" % ctype)
504 # Preserve the first part, it is probably not a RFC822-message.
506 # Usually it is just a few lines of text (MIME warning).
508 if msg.preamble is not None:
512 for subpart in msg.get_payload():
515 first_subpart = False
518 output("--%s%s" % (boundary, os.linesep))
520 # Recursively decode all parts of the subpart
521 decode_message(subpart)
524 output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
530 def decode_message(msg):
533 if msg.is_multipart():
534 decode_multipart(msg)
535 elif len(msg): # Simple one-part message (there are headers) - decode it
537 else: # Not a message, just text - copy it literally
538 output(msg.as_string())
541 def open_output_file(filename):
542 fullpath = os.path.abspath(os.path.join(g.destination_dir, filename))
543 full_dir = os.path.dirname(fullpath)
544 create = not os.path.isdir(full_dir)
546 os.makedirs(full_dir)
548 return open(fullpath, 'wb')
551 os.removedirs(full_dir)
555 from m_lib.defenc import default_encoding
556 recode_charset = 1 # recode charset of message body
560 # A list of headers to decode
561 decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
564 # A list of headers parameters to decode
565 decode_header_params = [
566 ("Content-Type", "name"),
567 ("Content-Disposition", "filename"),
570 # A list of headers to remove
572 # A list of headers parameters to remove
573 remove_headers_params = []
575 # A list of header/value pairs to set
576 set_header_value = []
577 # A list of header/parameter/value triples to set
578 set_header_param = []
580 totext_mask = [] # A list of content-types to decode
581 binary_mask = [] # A list of content-types to pass through
582 # A list of content-types to pass through (content-transfer-decoded).
583 decoded_binary_mask = []
584 # Ignore (do not decode and do not include into output)
585 # but output a warning instead of the body.
587 # Completely ignore - no headers, no body, no warning.
588 fully_ignore_mask = []
589 error_mask = [] # Raise error if encounter one of these
592 save_headers_mask = []
594 save_message_mask = []
596 input_filename = None
597 output_filename = None
598 destination_dir = os.curdir
605 from getopt import getopt, GetoptError
608 options, arguments = getopt(
610 'hVcCDPH:f:d:p:r:R:b:B:e:I:i:t:O:o:',
611 ['help', 'version', 'host=',
612 'save-headers=', 'save-body=', 'save-message=',
613 'set-header=', 'set-param='])
617 for option, value in options:
618 if option in ('-h', '--help'):
620 elif option in ('-V', '--version'):
626 elif option in ('-H', '--host'):
629 g.default_encoding = value
631 if value.startswith('*'):
632 g.decode_headers = []
633 g.decode_headers.append(value)
635 g.decode_headers = []
637 g.decode_header_params.append(value.split(':', 1))
639 g.decode_header_params = []
641 g.remove_headers.append(value)
643 g.remove_headers_params.append(value.split(':', 1))
644 elif option == '--set-header':
645 g.set_header_value.append(value.split(':', 1))
646 elif option == '--set-param':
647 header, value = value.split(':', 1)
649 param, value = value.split('=', 1)
651 param, value = value.split(':', 1)
652 g.set_header_param.append((header, param, value))
654 g.totext_mask.append(value)
656 g.binary_mask.append(value)
658 g.decoded_binary_mask.append(value)
660 g.fully_ignore_mask.append(value)
662 g.ignore_mask.append(value)
664 g.error_mask.append(value)
665 elif option == '--save-headers':
666 g.save_headers_mask.append(value)
667 elif option == '--save-body':
668 g.save_body_mask.append(value)
669 elif option == '--save-message':
670 g.save_message_mask.append(value)
672 g.destination_dir = value
674 g.output_filename = value
681 if __name__ == "__main__":
682 arguments = get_opts()
686 g.input_filename = '-'
688 if g.output_filename:
689 outfile = open_output_file(g.output_filename)
691 g.output_filename = '-'
694 if (arguments[0] == '-'):
695 g.input_filename = '-'
698 g.input_filename = arguments[0]
699 infile = open(arguments[0], 'r')
701 if g.output_filename:
702 outfile = open_output_file(g.output_filename)
704 g.output_filename = '-'
707 if g.output_filename:
708 usage(1, 'Too many output filenames')
709 if (arguments[1] == '-'):
710 g.output_filename = '-'
713 g.output_filename = arguments[1]
714 outfile = open_output_file(g.output_filename)
716 usage(1, 'Too many arguments')
718 if (infile is sys.stdin) and sys.stdin.isatty():
719 if (outfile is sys.stdout) and sys.stdout.isatty():
721 usage(1, 'Filtering from console is forbidden')
725 g.host_name = socket.gethostname()
728 if hasattr(outfile, 'buffer'):
730 if not isinstance(s, bytes):
731 s = s.encode(g.default_encoding, "replace")
732 outfile.buffer.write(s)
733 output = output_bytes
735 output = outfile.write
738 msg = email.message_from_file(infile)
740 for header, value in g.set_header_value:
741 set_header(msg, header, value)
743 for header, param, value in g.set_header_param:
745 msg.set_param(param, value, header)