2 """Decode MIME message"""
5 from mimedecode_version import __version__, \
6 __author__, __copyright__, __license__
8 me = os.path.basename(sys.argv[0])
13 Broytman mimedecode.py version %s, %s
14 """ % (__version__, __copyright__))
17 def usage(code=0, errormsg=''):
20 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]]
23 sys.stderr.write(errormsg + os.linesep)
27 def output_headers(msg):
28 unix_from = msg.get_unixfrom()
32 for key, value in msg.items():
35 value = value.split(';', 1)
39 output(_decode_header(value[1], strip=False))
41 output(os.linesep) # End of headers
44 def recode_if_needed(s, charset):
45 if bytes is str: # Python2
46 if isinstance(s, bytes) and \
47 charset and charset.lower() != g.default_encoding:
48 s = s.decode(charset, "replace").\
49 encode(g.default_encoding, "replace")
51 if isinstance(s, bytes):
52 s = s.decode(charset, "replace")
56 def _decode_header(s, strip=True):
57 """Return a decoded string according to RFC 2047.
58 NOTE: This is almost the same as email.Utils.decode.
62 L = email.header.decode_header(s)
63 if not isinstance(L, list):
68 for atom, charset in L:
69 atom = recode_if_needed(atom, charset or g.default_encoding)
74 # Now that we've decoded everything, we just need to join all the parts
75 # together into the final string.
78 def decode_header(msg, header):
79 "Decode mail header (if exists) and put it back, if it was encoded"
83 new_value = _decode_header(value)
84 if new_value != value: # do not bother to touch msg if not changed
85 set_header(msg, header, new_value)
88 def decode_header_param(msg, header, param):
89 "Decode mail header's parameter (if exists) and put it back, if it was encoded"
92 value = msg.get_param(param, header=header)
94 if isinstance(value, tuple):
95 new_value = recode_if_needed(value[2], value[0])
97 new_value = _decode_header(value)
98 if new_value != value: # do not bother to touch msg if not changed
99 msg.set_param(param, new_value, header)
102 def _get_exceptions(list):
103 return [x[1:].lower() for x in list[1:] if x[0]=='-']
105 def _decode_headers_params(msg, header, decode_all_params, param_list):
106 if decode_all_params:
107 params = msg.get_params(header=header)
109 for param, value in params:
110 if param not in param_list:
111 decode_header_param(msg, header, param)
113 for param in param_list:
114 decode_header_param(msg, header, param)
116 def _remove_headers_params(msg, header, remove_all_params, param_list):
117 if remove_all_params:
118 params = msg.get_params(header=header)
121 for param, value in params:
122 if param not in param_list:
123 msg.del_param(param, header)
126 if value is None: # No such header
128 if ';' not in value: # There are no parameters
130 del msg[header] # Delete all such headers
131 # Get the value without parameters and set it back
132 msg[header] = value.split(';')[0].strip()
134 for param in param_list:
135 msg.del_param(param, header)
137 def decode_headers(msg):
138 "Decode message headers according to global options"
140 for header_list in g.remove_headers:
141 header_list = header_list.split(',')
142 if header_list[0] == '*': # Remove all headers except listed
143 header_list = _get_exceptions(header_list)
144 for header in msg.keys():
145 if header.lower() not in header_list:
147 else: # Remove listed headers
148 for header in header_list:
151 for header_list, param_list in g.remove_headers_params:
152 header_list = header_list.split(',')
153 param_list = param_list.split(',')
154 remove_all_params = param_list[0] == '*' # Remove all params except listed
155 if remove_all_params:
156 param_list = _get_exceptions(param_list)
157 if header_list[0] == '*': # Remove for all headers except listed
158 header_list = _get_exceptions(header_list)
159 for header in msg.keys():
160 if header.lower() not in header_list:
161 _remove_headers_params(msg, header, remove_all_params, param_list)
162 else: # Decode for listed headers
163 for header in header_list:
164 _remove_headers_params(msg, header, remove_all_params, param_list)
166 for header_list in g.decode_headers:
167 header_list = header_list.split(',')
168 if header_list[0] == '*': # Decode all headers except listed
169 header_list = _get_exceptions(header_list)
170 for header in msg.keys():
171 if header.lower() not in header_list:
172 decode_header(msg, header)
173 else: # Decode listed headers
174 for header in header_list:
175 decode_header(msg, header)
177 for header_list, param_list in g.decode_header_params:
178 header_list = header_list.split(',')
179 param_list = param_list.split(',')
180 decode_all_params = param_list[0] == '*' # Decode all params except listed
181 if decode_all_params:
182 param_list = _get_exceptions(param_list)
183 if header_list[0] == '*': # Decode for all headers except listed
184 header_list = _get_exceptions(header_list)
185 for header in msg.keys():
186 if header.lower() not in header_list:
187 _decode_headers_params(msg, header, decode_all_params, param_list)
188 else: # Decode for listed headers
189 for header in header_list:
190 _decode_headers_params(msg, header, decode_all_params, param_list)
193 def set_header(msg, header, value):
197 msg.replace_header(header, value)
202 def set_content_type(msg, newtype, charset=None):
203 msg.set_type(newtype)
206 msg.set_param("charset", charset, "Content-Type")
209 caps = None # Globally stored mailcap database; initialized only if needed
211 def decode_body(msg, s):
212 "Decode body to plain text using first copiousoutput filter from mailcap"
214 import mailcap, tempfile
218 caps = mailcap.getcaps()
220 content_type = msg.get_content_type()
221 if content_type.startswith('text/'):
222 charset = msg.get_content_charset()
225 filename = tempfile.mktemp()
228 entries = mailcap.lookup(caps, content_type, "view")
229 for entry in entries:
230 if 'copiousoutput' in entry:
232 test = mailcap.subst(entry['test'], content_type, filename)
233 if test and os.system(test) != 0:
235 command = mailcap.subst(entry["view"], content_type, filename)
241 outfile = open(filename, 'wb')
242 if charset and isinstance(s, bytes):
243 s = s.decode(charset, "replace")
244 if not isinstance(s, bytes):
245 s = s.encode(g.default_encoding, "replace")
249 pipe = os.popen(command, 'r')
251 if pipe.close() is None: # result=0, Ok
255 set_content_type(msg, "text/plain")
257 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
259 msg["X-MIME-Autoconverted"] = "failed conversion from %s to text/plain by %s id %s" % (content_type, g.host_name, command.split()[0])
264 def recode_charset(msg, s):
265 "Recode charset of the message to the default charset"
267 save_charset = charset = msg.get_content_charset()
268 if charset and charset.lower() != g.default_encoding:
269 s = recode_if_needed(s, charset)
270 content_type = msg.get_content_type()
271 set_content_type(msg, content_type, g.default_encoding)
272 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, g.default_encoding, g.host_name, me)
276 def totext(msg, instring):
277 "Convert instring content to text"
279 # Decode body and recode charset
280 s = decode_body(msg, instring)
282 s = recode_charset(msg, s)
291 def _guess_extension(ctype):
293 if mimetypes is None:
296 user_mime_type = os.path.expanduser('~/.mime.types')
297 if os.path.exists(user_mime_type):
298 mimetypes._db.read(user_mime_type)
299 return mimetypes.guess_extension(ctype)
301 def _save_message(msg, outstring, save_headers=False, save_body=False):
302 for header, param in (
303 ("Content-Disposition", "filename"),
304 ("Content-Type", "name"),
306 fname = msg.get_param(param, header=header)
308 if isinstance(fname, tuple):
309 fname = fname[2] # Do not recode if it isn't recoded yet
311 for forbidden in chr(0), '/', '\\':
312 if forbidden in fname:
321 fname = str(g.save_counter) + fname
323 ext = _guess_extension(msg.get_content_type())
328 outfile = open_output_file(fname)
329 def _output_bytes(s):
330 if not isinstance(s, bytes):
331 s = s.encode(g.default_encoding, "replace")
333 output = _output_bytes
342 def decode_part(msg):
343 "Decode one part of the message"
347 # Test all mask lists and find what to do with this content type
349 ctype = msg.get_content_type()
352 mtype = ctype.split('/')[0]
353 masks.append(mtype + '/*')
357 for content_type in masks:
358 if content_type in g.totext_mask or \
359 content_type in g.decoded_binary_mask:
361 elif content_type in g.binary_mask:
364 elif content_type in g.fully_ignore_mask:
367 encoding = msg["Content-Transfer-Encoding"]
368 if left_binary or encoding in (None, '', '7bit', '8bit', 'binary'):
369 outstring = msg.get_payload()
370 else: # Decode from transfer ecoding to text or binary form
371 outstring = msg.get_payload(decode=1)
372 set_header(msg, "Content-Transfer-Encoding", "8bit")
373 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, g.host_name, me)
375 for content_type in masks:
376 if content_type in g.totext_mask:
377 outstring = totext(msg, outstring)
379 elif content_type in g.binary_mask or \
380 content_type in g.decoded_binary_mask:
384 elif content_type in g.ignore_mask:
386 output("%sMessage body of type %s skipped.%s" % (os.linesep, ctype, os.linesep))
388 elif content_type in g.error_mask:
391 # Neither content type nor masks were listed - decode by default
392 outstring = totext(msg, outstring)
394 for content_type in masks:
395 if content_type in g.save_headers_mask:
396 _save_message(msg, outstring, save_headers=True, save_body=False)
397 if content_type in g.save_body_mask:
398 _save_message(msg, outstring, save_headers=False, save_body=True)
399 if content_type in g.save_message_mask:
400 _save_message(msg, outstring, save_headers=True, save_body=True)
402 for content_type in masks:
403 if content_type in g.error_mask:
404 raise ValueError("content type %s prohibited" % ctype)
406 def decode_multipart(msg):
410 boundary = msg.get_boundary()
413 ctype = msg.get_content_type()
416 mtype = ctype.split('/')[0]
417 masks.append(mtype + '/*')
420 for content_type in masks:
421 if content_type in g.fully_ignore_mask:
423 elif content_type in g.ignore_mask:
425 output("%sMessage body of type %s skipped.%s" % (os.linesep, ctype, os.linesep))
427 output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
430 for content_type in masks:
431 if content_type in g.save_body_mask or \
432 content_type in g.save_message_mask:
435 for subpart in msg.get_payload():
437 first_subpart = False
439 _out_l.append(os.linesep)
440 _out_l.append("--%s%s" % (boundary, os.linesep))
441 _out_l.append(subpart.as_string())
442 _out_l.append("%s--%s--%s" % (os.linesep, boundary, os.linesep))
443 outstring = ''.join(_out_l)
448 for content_type in masks:
449 if content_type in g.save_headers_mask:
450 _save_message(msg, outstring, save_headers=True, save_body=False)
451 if content_type in g.save_body_mask:
452 _save_message(msg, outstring, save_headers=False, save_body=True)
453 if content_type in g.save_message_mask:
454 _save_message(msg, outstring, save_headers=True, save_body=True)
456 for content_type in masks:
457 if content_type in g.error_mask:
458 raise ValueError("content type %s prohibited" % ctype)
462 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
463 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
464 if msg.preamble is not None:
468 for subpart in msg.get_payload():
471 first_subpart = False
474 output("--%s%s" % (boundary, os.linesep))
476 # Recursively decode all parts of the subpart
477 decode_message(subpart)
480 output("%s--%s--%s" % (os.linesep, boundary, os.linesep))
486 def decode_message(msg):
489 if msg.is_multipart():
490 decode_multipart(msg)
491 elif len(msg): # Simple one-part message (there are headers) - decode it
493 else: # Not a message, just text - copy it literally
494 output(msg.as_string())
497 def open_output_file(filename):
498 fullpath = os.path.abspath(os.path.join(g.destination_dir, filename))
499 full_dir = os.path.dirname(fullpath)
500 create = not os.path.isdir(full_dir)
502 os.makedirs(full_dir)
504 return open(fullpath, 'wb')
507 os.removedirs(full_dir)
511 from m_lib.defenc import default_encoding
512 recode_charset = 1 # recode charset of message body
516 # A list of headers to decode
517 decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
520 # A list of headers parameters to decode
521 decode_header_params = [
522 ("Content-Type", "name"),
523 ("Content-Disposition", "filename"),
526 # A list of headers to remove
528 # A list of headers parameters to remove
529 remove_headers_params = []
531 # A list of header/value pairs to set
532 set_header_value = []
533 # A list of header/parameter/value triples to set
534 set_header_param = []
536 totext_mask = [] # A list of content-types to decode
537 binary_mask = [] # A list of content-types to pass through
538 decoded_binary_mask = [] # A list of content-types to pass through (content-transfer-decoded)
539 ignore_mask = [] # Ignore (do not decode and do not include into output) but output a warning instead of the body
540 fully_ignore_mask = [] # Completely ignore - no headers, no body, no warning
541 error_mask = [] # Raise error if encounter one of these
544 save_headers_mask = []
546 save_message_mask = []
548 input_filename = None
549 output_filename = None
550 destination_dir = os.curdir
556 from getopt import getopt, GetoptError
559 options, arguments = getopt(sys.argv[1:],
560 'hVcCDPH:f:d:p:r:R:b:B:e:I:i:t:O:o:',
561 ['help', 'version', 'host=',
562 'save-headers=', 'save-body=', 'save-message=',
563 'set-header=', 'set-param='])
567 for option, value in options:
568 if option in ('-h', '--help'):
570 elif option in ('-V', '--version'):
576 elif option in ('-H', '--host'):
579 g.default_encoding = value
581 if value.startswith('*'):
582 g.decode_headers = []
583 g.decode_headers.append(value)
585 g.decode_headers = []
587 g.decode_header_params.append(value.split(':', 1))
589 g.decode_header_params = []
591 g.remove_headers.append(value)
593 g.remove_headers_params.append(value.split(':', 1))
594 elif option == '--set-header':
595 g.set_header_value.append(value.split(':', 1))
596 elif option == '--set-param':
597 header, value = value.split(':', 1)
599 param, value = value.split('=', 1)
601 param, value = value.split(':', 1)
602 g.set_header_param.append((header, param, value))
604 g.totext_mask.append(value)
606 g.binary_mask.append(value)
608 g.decoded_binary_mask.append(value)
610 g.fully_ignore_mask.append(value)
612 g.ignore_mask.append(value)
614 g.error_mask.append(value)
615 elif option == '--save-headers':
616 g.save_headers_mask.append(value)
617 elif option == '--save-body':
618 g.save_body_mask.append(value)
619 elif option == '--save-message':
620 g.save_message_mask.append(value)
622 g.destination_dir = value
624 g.output_filename = value
631 if __name__ == "__main__":
632 arguments = get_opts()
636 g.input_filename = '-'
638 if g.output_filename:
639 outfile = open_output_file(g.output_filename)
641 g.output_filename = '-'
644 if (arguments[0] == '-'):
645 g.input_filename = '-'
648 g.input_filename = arguments[0]
649 infile = open(arguments[0], 'r')
651 if g.output_filename:
652 outfile = open_output_file(g.output_filename)
654 g.output_filename = '-'
657 if g.output_filename:
658 usage(1, 'Too many output filenames')
659 if (arguments[1] == '-'):
660 g.output_filename = '-'
663 g.output_filename = arguments[1]
664 outfile = open_output_file(g.output_filename)
666 usage(1, 'Too many arguments')
668 if (infile is sys.stdin) and sys.stdin.isatty():
669 if (outfile is sys.stdout) and sys.stdout.isatty():
671 usage(1, 'Filtering from console is forbidden')
675 g.host_name = socket.gethostname()
678 if hasattr(outfile, 'buffer'):
680 if not isinstance(s, bytes):
681 s = s.encode(g.default_encoding, "replace")
682 outfile.buffer.write(s)
683 output = output_bytes
685 output = outfile.write
688 msg = email.message_from_file(infile)
690 for header, value in g.set_header_value:
691 set_header(msg, header, value)
693 for header, param, value in g.set_header_param:
695 msg.set_param(param, value, header)