2 """Decode MIME message"""
8 from mimedecode_version import __version__, \
9 __author__, __copyright__, __license__
11 if sys.version_info[0] >= 3:
12 # Replace email.message._formatparam with _formatparam from Python 2.7
13 # to avoid re-encoding non-ascii params.
16 me = os.path.basename(sys.argv[0])
21 Broytman mimedecode.py version %s, %s
22 """ % (__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]]
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 (if exists) and put it back, if it was encoded"
102 value = msg.get_param(param, header=header)
104 if isinstance(value, tuple):
105 new_value = recode_if_needed(value[2], value[0])
107 new_value = _decode_header(value)
108 if new_value != value: # do not bother to touch msg if not changed
109 msg.set_param(param, new_value, header)
112 def _get_exceptions(list):
113 return [x[1:].lower() for x in list[1:] if x[0] == '-']
116 def _decode_headers_params(msg, header, decode_all_params, param_list):
117 if decode_all_params:
118 params = msg.get_params(header=header)
120 for param, value in params:
121 if param not in param_list:
122 decode_header_param(msg, header, param)
124 for param in param_list:
125 decode_header_param(msg, header, param)
128 def _remove_headers_params(msg, header, remove_all_params, param_list):
129 if remove_all_params:
130 params = msg.get_params(header=header)
133 for param, value in params:
134 if param not in param_list:
135 msg.del_param(param, header)
138 if value is None: # No such header
140 if ';' not in value: # There are no parameters
142 del msg[header] # Delete all such headers
143 # Get the value without parameters and set it back
144 msg[header] = value.split(';')[0].strip()
146 for param in param_list:
147 msg.del_param(param, header)
150 def decode_headers(msg):
151 "Decode message headers according to global options"
153 for header_list in g.remove_headers:
154 header_list = header_list.split(',')
155 if header_list[0] == '*': # Remove all headers except listed
156 header_list = _get_exceptions(header_list)
157 for header in msg.keys():
158 if header.lower() not in header_list:
160 else: # Remove listed headers
161 for header in header_list:
164 for header_list, param_list in g.remove_headers_params:
165 header_list = header_list.split(',')
166 param_list = param_list.split(',')
167 remove_all_params = param_list[0] == '*' # Remove all params except listed
168 if remove_all_params:
169 param_list = _get_exceptions(param_list)
170 if header_list[0] == '*': # Remove for all headers except listed
171 header_list = _get_exceptions(header_list)
172 for header in msg.keys():
173 if header.lower() not in header_list:
174 _remove_headers_params(msg, header, remove_all_params, param_list)
175 else: # Decode for listed headers
176 for header in header_list:
177 _remove_headers_params(msg, header, remove_all_params, param_list)
179 for header_list in g.decode_headers:
180 header_list = header_list.split(',')
181 if header_list[0] == '*': # Decode all headers except listed
182 header_list = _get_exceptions(header_list)
183 for header in msg.keys():
184 if header.lower() not in header_list:
185 decode_header(msg, header)
186 else: # Decode listed headers
187 for header in header_list:
188 decode_header(msg, header)
190 for header_list, param_list in g.decode_header_params:
191 header_list = header_list.split(',')
192 param_list = param_list.split(',')
193 decode_all_params = param_list[0] == '*' # Decode all params except listed
194 if decode_all_params:
195 param_list = _get_exceptions(param_list)
196 if header_list[0] == '*': # Decode for all headers except listed
197 header_list = _get_exceptions(header_list)
198 for header in msg.keys():
199 if header.lower() not in header_list:
200 _decode_headers_params(msg, header, decode_all_params, param_list)
201 else: # Decode for listed headers
202 for header in header_list:
203 _decode_headers_params(msg, header, decode_all_params, param_list)
206 def set_header(msg, header, value):
210 msg.replace_header(header, value)
215 def set_content_type(msg, newtype, charset=None):
216 msg.set_type(newtype)
219 msg.set_param("charset", charset, "Content-Type")
222 caps = None # Globally stored mailcap database; initialized only if needed
225 def decode_body(msg, s):
226 "Decode body to plain text using first copiousoutput filter from mailcap"
233 caps = mailcap.getcaps()
235 content_type = msg.get_content_type()
236 if content_type.startswith('text/'):
237 charset = msg.get_content_charset()
240 filename = tempfile.mktemp()
243 entries = mailcap.lookup(caps, content_type, "view")
244 for entry in entries:
245 if 'copiousoutput' in entry:
247 test = mailcap.subst(entry['test'], content_type, filename)
248 if test and os.system(test) != 0:
250 command = mailcap.subst(entry["view"], content_type, filename)
256 outfile = open(filename, 'wb')
257 if charset and bytes is not str and isinstance(s, bytes): # Python3
258 s = s.decode(charset, "replace")
259 if not isinstance(s, bytes):
260 s = s.encode(g.default_encoding, "replace")
264 pipe = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
265 new_s = pipe.stdout.read()
267 if pipe.wait() == 0: # result=0, Ok
269 if bytes is not str and isinstance(s, bytes): # Python3
270 s = s.decode(g.default_encoding, "replace")
271 if charset and not isinstance(s, bytes):
272 s = s.encode(charset, "replace")
273 set_content_type(msg, "text/plain")
274 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
276 msg["X-MIME-Autoconverted"] = "failed conversion from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
282 def recode_charset(msg, s):
283 "Recode charset of the message to the default charset"
285 save_charset = charset = msg.get_content_charset()
286 if charset and charset.lower() != g.default_encoding:
287 s = recode_if_needed(s, charset)
288 content_type = msg.get_content_type()
289 set_content_type(msg, content_type, g.default_encoding)
290 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, g.default_encoding, g.host_name, me)
294 def totext(msg, instring):
295 "Convert instring content to text"
297 # Decode body and recode charset
298 s = decode_body(msg, instring)
300 s = recode_charset(msg, s)
310 def _guess_extension(ctype):
312 if mimetypes is None:
315 user_mime_type = os.path.expanduser('~/.mime.types')
316 if os.path.exists(user_mime_type):
317 mimetypes._db.read(user_mime_type)
318 return mimetypes.guess_extension(ctype)
321 def _save_message(msg, outstring, save_headers=False, save_body=False):
322 for header, param in (
323 ("Content-Disposition", "filename"),
324 ("Content-Type", "name"),
326 fname = msg.get_param(param, header=header)
328 if isinstance(fname, tuple):
329 fname = fname[2] # Do not recode if it isn't recoded yet
331 for forbidden in chr(0), '/', '\\':
332 if forbidden in fname:
341 fname = str(g.save_counter) + fname
343 ext = _guess_extension(msg.get_content_type())
348 outfile = open_output_file(fname)
350 def _output_bytes(s):
351 if not isinstance(s, bytes):
352 s = s.encode(g.default_encoding, "replace")
355 output = _output_bytes
364 def decode_part(msg):
365 "Decode one part of the message"
369 # Test all mask lists and find what to do with this content type
371 ctype = msg.get_content_type()
374 mtype = ctype.split('/')[0]
375 masks.append(mtype + '/*')
379 for content_type in masks:
380 if content_type in g.totext_mask or \
381 content_type in g.decoded_binary_mask:
383 elif content_type in g.binary_mask:
386 elif content_type in g.fully_ignore_mask:
389 encoding = msg["Content-Transfer-Encoding"]
390 if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
391 outstring = msg.get_payload()
392 else: # Decode from transfer ecoding to text or binary form
393 outstring = msg.get_payload(decode=1)
394 set_header(msg, "Content-Transfer-Encoding", "8bit")
395 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, g.host_name, me)
397 for content_type in masks:
398 if content_type in g.totext_mask:
399 outstring = totext(msg, outstring)
401 elif content_type in g.binary_mask or \
402 content_type in g.decoded_binary_mask:
406 elif content_type in g.ignore_mask:
408 output("%sMessage body of type %s skipped.%s" % (os.linesep, ctype, os.linesep))
410 elif content_type in g.error_mask:
413 # Neither content type nor masks were listed - decode by default
414 outstring = totext(msg, outstring)
416 for content_type in masks:
417 if content_type in g.save_headers_mask:
418 _save_message(msg, outstring, save_headers=True, save_body=False)
419 if content_type in g.save_body_mask:
420 _save_message(msg, outstring, save_headers=False, save_body=True)
421 if content_type in g.save_message_mask:
422 _save_message(msg, outstring, save_headers=True, save_body=True)
424 for content_type in masks:
425 if content_type in g.error_mask:
426 raise ValueError("content type %s prohibited" % ctype)
429 def decode_multipart(msg):
433 boundary = msg.get_boundary()
436 ctype = msg.get_content_type()
439 mtype = ctype.split('/')[0]
440 masks.append(mtype + '/*')
443 for content_type in masks:
444 if content_type in g.fully_ignore_mask:
446 elif content_type in g.ignore_mask:
448 output("%sMessage body of type %s skipped.%s" % (os.linesep, ctype, os.linesep))
450 output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
453 for content_type in masks:
454 if content_type in g.save_body_mask or \
455 content_type in g.save_message_mask:
458 for subpart in msg.get_payload():
460 first_subpart = False
462 _out_l.append(os.linesep)
463 _out_l.append("--%s%s" % (boundary, os.linesep))
464 _out_l.append(subpart.as_string())
465 _out_l.append("%s--%s--%s" % (os.linesep, boundary, os.linesep))
466 outstring = ''.join(_out_l)
471 for content_type in masks:
472 if content_type in g.save_headers_mask:
473 _save_message(msg, outstring, save_headers=True, save_body=False)
474 if content_type in g.save_body_mask:
475 _save_message(msg, outstring, save_headers=False, save_body=True)
476 if content_type in g.save_message_mask:
477 _save_message(msg, outstring, save_headers=True, save_body=True)
479 for content_type in masks:
480 if content_type in g.error_mask:
481 raise ValueError("content type %s prohibited" % ctype)
485 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
486 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
487 if msg.preamble is not None:
491 for subpart in msg.get_payload():
494 first_subpart = False
497 output("--%s%s" % (boundary, os.linesep))
499 # Recursively decode all parts of the subpart
500 decode_message(subpart)
503 output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
509 def decode_message(msg):
512 if msg.is_multipart():
513 decode_multipart(msg)
514 elif len(msg): # Simple one-part message (there are headers) - decode it
516 else: # Not a message, just text - copy it literally
517 output(msg.as_string())
520 def open_output_file(filename):
521 fullpath = os.path.abspath(os.path.join(g.destination_dir, filename))
522 full_dir = os.path.dirname(fullpath)
523 create = not os.path.isdir(full_dir)
525 os.makedirs(full_dir)
527 return open(fullpath, 'wb')
530 os.removedirs(full_dir)
534 from m_lib.defenc import default_encoding
535 recode_charset = 1 # recode charset of message body
539 # A list of headers to decode
540 decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
543 # A list of headers parameters to decode
544 decode_header_params = [
545 ("Content-Type", "name"),
546 ("Content-Disposition", "filename"),
549 # A list of headers to remove
551 # A list of headers parameters to remove
552 remove_headers_params = []
554 # A list of header/value pairs to set
555 set_header_value = []
556 # A list of header/parameter/value triples to set
557 set_header_param = []
559 totext_mask = [] # A list of content-types to decode
560 binary_mask = [] # A list of content-types to pass through
561 decoded_binary_mask = [] # A list of content-types to pass through (content-transfer-decoded)
562 ignore_mask = [] # Ignore (do not decode and do not include into output) but output a warning instead of the body
563 fully_ignore_mask = [] # Completely ignore - no headers, no body, no warning
564 error_mask = [] # Raise error if encounter one of these
567 save_headers_mask = []
569 save_message_mask = []
571 input_filename = None
572 output_filename = None
573 destination_dir = os.curdir
580 from getopt import getopt, GetoptError
583 options, arguments = getopt(
585 'hVcCDPH:f:d:p:r:R:b:B:e:I:i:t:O:o:',
586 ['help', 'version', 'host=',
587 'save-headers=', 'save-body=', 'save-message=',
588 'set-header=', 'set-param='])
592 for option, value in options:
593 if option in ('-h', '--help'):
595 elif option in ('-V', '--version'):
601 elif option in ('-H', '--host'):
604 g.default_encoding = value
606 if value.startswith('*'):
607 g.decode_headers = []
608 g.decode_headers.append(value)
610 g.decode_headers = []
612 g.decode_header_params.append(value.split(':', 1))
614 g.decode_header_params = []
616 g.remove_headers.append(value)
618 g.remove_headers_params.append(value.split(':', 1))
619 elif option == '--set-header':
620 g.set_header_value.append(value.split(':', 1))
621 elif option == '--set-param':
622 header, value = value.split(':', 1)
624 param, value = value.split('=', 1)
626 param, value = value.split(':', 1)
627 g.set_header_param.append((header, param, value))
629 g.totext_mask.append(value)
631 g.binary_mask.append(value)
633 g.decoded_binary_mask.append(value)
635 g.fully_ignore_mask.append(value)
637 g.ignore_mask.append(value)
639 g.error_mask.append(value)
640 elif option == '--save-headers':
641 g.save_headers_mask.append(value)
642 elif option == '--save-body':
643 g.save_body_mask.append(value)
644 elif option == '--save-message':
645 g.save_message_mask.append(value)
647 g.destination_dir = value
649 g.output_filename = value
656 if __name__ == "__main__":
657 arguments = get_opts()
661 g.input_filename = '-'
663 if g.output_filename:
664 outfile = open_output_file(g.output_filename)
666 g.output_filename = '-'
669 if (arguments[0] == '-'):
670 g.input_filename = '-'
673 g.input_filename = arguments[0]
674 infile = open(arguments[0], 'r')
676 if g.output_filename:
677 outfile = open_output_file(g.output_filename)
679 g.output_filename = '-'
682 if g.output_filename:
683 usage(1, 'Too many output filenames')
684 if (arguments[1] == '-'):
685 g.output_filename = '-'
688 g.output_filename = arguments[1]
689 outfile = open_output_file(g.output_filename)
691 usage(1, 'Too many arguments')
693 if (infile is sys.stdin) and sys.stdin.isatty():
694 if (outfile is sys.stdout) and sys.stdout.isatty():
696 usage(1, 'Filtering from console is forbidden')
700 g.host_name = socket.gethostname()
703 if hasattr(outfile, 'buffer'):
705 if not isinstance(s, bytes):
706 s = s.encode(g.default_encoding, "replace")
707 outfile.buffer.write(s)
708 output = output_bytes
710 output = outfile.write
713 msg = email.message_from_file(infile)
715 for header, value in g.set_header_value:
716 set_header(msg, header, value)
718 for header, param, value in g.set_header_param:
720 msg.set_param(param, value, header)