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
261 set_content_type(msg, "text/plain")
263 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
265 msg["X-MIME-Autoconverted"] = "failed conversion from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
270 def recode_charset(msg, s):
271 "Recode charset of the message to the default charset"
273 save_charset = charset = msg.get_content_charset()
274 if charset and charset.lower() != g.default_encoding:
275 s = recode_if_needed(s, charset)
276 content_type = msg.get_content_type()
277 set_content_type(msg, content_type, g.default_encoding)
278 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, g.default_encoding, g.host_name, me)
282 def totext(msg, instring):
283 "Convert instring content to text"
285 # Decode body and recode charset
286 s = decode_body(msg, instring)
288 s = recode_charset(msg, s)
297 def _guess_extension(ctype):
299 if mimetypes is None:
302 user_mime_type = os.path.expanduser('~/.mime.types')
303 if os.path.exists(user_mime_type):
304 mimetypes._db.read(user_mime_type)
305 return mimetypes.guess_extension(ctype)
307 def _save_message(msg, outstring, save_headers=False, save_body=False):
308 for header, param in (
309 ("Content-Disposition", "filename"),
310 ("Content-Type", "name"),
312 fname = msg.get_param(param, header=header)
314 if isinstance(fname, tuple):
315 fname = fname[2] # Do not recode if it isn't recoded yet
317 for forbidden in chr(0), '/', '\\':
318 if forbidden in fname:
327 fname = str(g.save_counter) + fname
329 ext = _guess_extension(msg.get_content_type())
334 outfile = open_output_file(fname)
335 def _output_bytes(s):
336 if not isinstance(s, bytes):
337 s = s.encode(g.default_encoding, "replace")
339 output = _output_bytes
348 def decode_part(msg):
349 "Decode one part of the message"
353 # Test all mask lists and find what to do with this content type
355 ctype = msg.get_content_type()
358 mtype = ctype.split('/')[0]
359 masks.append(mtype + '/*')
363 for content_type in masks:
364 if content_type in g.totext_mask or \
365 content_type in g.decoded_binary_mask:
367 elif content_type in g.binary_mask:
370 elif content_type in g.fully_ignore_mask:
373 encoding = msg["Content-Transfer-Encoding"]
374 if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
375 outstring = msg.get_payload()
376 else: # Decode from transfer ecoding to text or binary form
377 outstring = msg.get_payload(decode=1)
378 set_header(msg, "Content-Transfer-Encoding", "8bit")
379 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, g.host_name, me)
381 for content_type in masks:
382 if content_type in g.totext_mask:
383 outstring = totext(msg, outstring)
385 elif content_type in g.binary_mask or \
386 content_type in g.decoded_binary_mask:
390 elif content_type in g.ignore_mask:
392 output("%sMessage body of type %s skipped.%s" % (os.linesep, ctype, os.linesep))
394 elif content_type in g.error_mask:
397 # Neither content type nor masks were listed - decode by default
398 outstring = totext(msg, outstring)
400 for content_type in masks:
401 if content_type in g.save_headers_mask:
402 _save_message(msg, outstring, save_headers=True, save_body=False)
403 if content_type in g.save_body_mask:
404 _save_message(msg, outstring, save_headers=False, save_body=True)
405 if content_type in g.save_message_mask:
406 _save_message(msg, outstring, save_headers=True, save_body=True)
408 for content_type in masks:
409 if content_type in g.error_mask:
410 raise ValueError("content type %s prohibited" % ctype)
412 def decode_multipart(msg):
416 boundary = msg.get_boundary()
419 ctype = msg.get_content_type()
422 mtype = ctype.split('/')[0]
423 masks.append(mtype + '/*')
426 for content_type in masks:
427 if content_type in g.fully_ignore_mask:
429 elif content_type in g.ignore_mask:
431 output("%sMessage body of type %s skipped.%s" % (os.linesep, ctype, os.linesep))
433 output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
436 for content_type in masks:
437 if content_type in g.save_body_mask or \
438 content_type in g.save_message_mask:
441 for subpart in msg.get_payload():
443 first_subpart = False
445 _out_l.append(os.linesep)
446 _out_l.append("--%s%s" % (boundary, os.linesep))
447 _out_l.append(subpart.as_string())
448 _out_l.append("%s--%s--%s" % (os.linesep, boundary, os.linesep))
449 outstring = ''.join(_out_l)
454 for content_type in masks:
455 if content_type in g.save_headers_mask:
456 _save_message(msg, outstring, save_headers=True, save_body=False)
457 if content_type in g.save_body_mask:
458 _save_message(msg, outstring, save_headers=False, save_body=True)
459 if content_type in g.save_message_mask:
460 _save_message(msg, outstring, save_headers=True, save_body=True)
462 for content_type in masks:
463 if content_type in g.error_mask:
464 raise ValueError("content type %s prohibited" % ctype)
468 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
469 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
470 if msg.preamble is not None:
474 for subpart in msg.get_payload():
477 first_subpart = False
480 output("--%s%s" % (boundary, os.linesep))
482 # Recursively decode all parts of the subpart
483 decode_message(subpart)
486 output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
492 def decode_message(msg):
495 if msg.is_multipart():
496 decode_multipart(msg)
497 elif len(msg): # Simple one-part message (there are headers) - decode it
499 else: # Not a message, just text - copy it literally
500 output(msg.as_string())
503 def open_output_file(filename):
504 fullpath = os.path.abspath(os.path.join(g.destination_dir, filename))
505 full_dir = os.path.dirname(fullpath)
506 create = not os.path.isdir(full_dir)
508 os.makedirs(full_dir)
510 return open(fullpath, 'wb')
513 os.removedirs(full_dir)
517 from m_lib.defenc import default_encoding
518 recode_charset = 1 # recode charset of message body
522 # A list of headers to decode
523 decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
526 # A list of headers parameters to decode
527 decode_header_params = [
528 ("Content-Type", "name"),
529 ("Content-Disposition", "filename"),
532 # A list of headers to remove
534 # A list of headers parameters to remove
535 remove_headers_params = []
537 # A list of header/value pairs to set
538 set_header_value = []
539 # A list of header/parameter/value triples to set
540 set_header_param = []
542 totext_mask = [] # A list of content-types to decode
543 binary_mask = [] # A list of content-types to pass through
544 decoded_binary_mask = [] # A list of content-types to pass through (content-transfer-decoded)
545 ignore_mask = [] # Ignore (do not decode and do not include into output) but output a warning instead of the body
546 fully_ignore_mask = [] # Completely ignore - no headers, no body, no warning
547 error_mask = [] # Raise error if encounter one of these
550 save_headers_mask = []
552 save_message_mask = []
554 input_filename = None
555 output_filename = None
556 destination_dir = os.curdir
562 from getopt import getopt, GetoptError
565 options, arguments = getopt(sys.argv[1:],
566 'hVcCDPH:f:d:p:r:R:b:B:e:I:i:t:O:o:',
567 ['help', 'version', 'host=',
568 'save-headers=', 'save-body=', 'save-message=',
569 'set-header=', 'set-param='])
573 for option, value in options:
574 if option in ('-h', '--help'):
576 elif option in ('-V', '--version'):
582 elif option in ('-H', '--host'):
585 g.default_encoding = value
587 if value.startswith('*'):
588 g.decode_headers = []
589 g.decode_headers.append(value)
591 g.decode_headers = []
593 g.decode_header_params.append(value.split(':', 1))
595 g.decode_header_params = []
597 g.remove_headers.append(value)
599 g.remove_headers_params.append(value.split(':', 1))
600 elif option == '--set-header':
601 g.set_header_value.append(value.split(':', 1))
602 elif option == '--set-param':
603 header, value = value.split(':', 1)
605 param, value = value.split('=', 1)
607 param, value = value.split(':', 1)
608 g.set_header_param.append((header, param, value))
610 g.totext_mask.append(value)
612 g.binary_mask.append(value)
614 g.decoded_binary_mask.append(value)
616 g.fully_ignore_mask.append(value)
618 g.ignore_mask.append(value)
620 g.error_mask.append(value)
621 elif option == '--save-headers':
622 g.save_headers_mask.append(value)
623 elif option == '--save-body':
624 g.save_body_mask.append(value)
625 elif option == '--save-message':
626 g.save_message_mask.append(value)
628 g.destination_dir = value
630 g.output_filename = value
637 if __name__ == "__main__":
638 arguments = get_opts()
642 g.input_filename = '-'
644 if g.output_filename:
645 outfile = open_output_file(g.output_filename)
647 g.output_filename = '-'
650 if (arguments[0] == '-'):
651 g.input_filename = '-'
654 g.input_filename = arguments[0]
655 infile = open(arguments[0], 'r')
657 if g.output_filename:
658 outfile = open_output_file(g.output_filename)
660 g.output_filename = '-'
663 if g.output_filename:
664 usage(1, 'Too many output filenames')
665 if (arguments[1] == '-'):
666 g.output_filename = '-'
669 g.output_filename = arguments[1]
670 outfile = open_output_file(g.output_filename)
672 usage(1, 'Too many arguments')
674 if (infile is sys.stdin) and sys.stdin.isatty():
675 if (outfile is sys.stdout) and sys.stdout.isatty():
677 usage(1, 'Filtering from console is forbidden')
681 g.host_name = socket.gethostname()
684 if hasattr(outfile, 'buffer'):
686 if not isinstance(s, bytes):
687 s = s.encode(g.default_encoding, "replace")
688 outfile.buffer.write(s)
689 output = output_bytes
691 output = outfile.write
694 msg = email.message_from_file(infile)
696 for header, value in g.set_header_value:
697 set_header(msg, header, value)
699 for header, param, value in g.set_header_param:
701 msg.set_param(param, value, header)