2 """Decode MIME message"""
4 from mimedecode_version import __version__, __author__, __copyright__, __license__
9 me = os.path.basename(sys.argv[0])
14 Broytman mimedecode.py version %s, %s
15 """ % (__version__, __copyright__))
18 def usage(code=0, errormsg=''):
21 Usage: %s [-h|--help] [-V|--version] [-cCDP] [-H|--host=hostname] [-f charset] [-d header1[,header2,header3...]] [-p header:param] [-r header] [-R header:param] [--remove-params=header] [-beit mask] [-o output_file] [input_file [output_file]]
24 sys.stderr.write(errormsg + '\n')
28 def output_headers(msg):
29 unix_from = msg.get_unixfrom()
31 output(unix_from + '\n')
32 for key, value in msg.items():
33 output("%s: %s\n" % (key, value))
34 output("\n") # End of headers
37 def recode(s, charset):
38 return unicode(s, charset, "replace").encode(gopts.default_encoding, "replace")
40 def recode_if_needed(s, charset):
41 if charset and charset.lower() <> gopts.default_encoding:
42 s = recode(s, charset)
46 def _decode_header(s):
47 """Return a decoded string according to RFC 2047.
48 NOTE: This is almost the same as email.Utils.decode.
52 L = email.Header.decode_header(s)
53 if not isinstance(L, list):
58 for atom, charset in L:
62 rtn.append(recode_if_needed(atom, charset))
64 del rtn[-1] # remove the last space
66 # Now that we've decoded everything, we just need to join all the parts
67 # together into the final string.
70 def decode_header(msg, header):
71 "Decode mail header (if exists) and put it back, if it was encoded"
73 if msg.has_key(header):
75 new_value = _decode_header(value)
76 if new_value <> value: # do not bother to touch msg if not changed
77 set_header(msg, header, new_value)
80 def _decode_header_param(s):
81 return recode_if_needed(s[2], s[0])
83 def decode_header_param(msg, header, param):
84 "Decode mail header's parameter (if exists) and put it back, if it was encoded"
86 if msg.has_key(header):
87 value = msg.get_param(param, header=header)
89 if isinstance(value, tuple):
90 new_value = _decode_header_param(value)
92 new_value = _decode_header(value)
93 if new_value <> value: # do not bother to touch msg if not changed
94 msg.set_param(param, new_value, header)
97 def decode_headers(msg):
98 "Decode message headers according to global options"
100 for header in gopts.remove_headers:
103 for header in gopts.remove_all_params:
105 if value is None: # No such header
107 if ';' not in value: # There are no parameters
109 del msg[header] # Delete all such headers
110 # Get the value without parameters and set it back
111 msg[header] = value.split(';')[0].strip()
113 for header, param in gopts.remove_header_params:
114 msg.del_param(param, header)
116 for header_list in gopts.decode_headers:
117 for header in header_list.split(','):
118 decode_header(msg, header)
120 for header, param in gopts.decode_header_params:
121 decode_header_param(msg, header, param)
124 def set_header(msg, header, value):
127 if msg.has_key(header):
128 msg.replace_header(header, value)
133 def set_content_type(msg, newtype, charset=None):
134 msg.set_type(newtype)
137 msg.set_param("charset", charset, "Content-Type")
140 caps = None # Globally stored mailcap database; initialized only if needed
142 def decode_body(msg, s):
143 "Decode body to plain text using first copiousoutput filter from mailcap"
145 import mailcap, tempfile
149 caps = mailcap.getcaps()
151 content_type = msg.get_content_type()
152 filename = tempfile.mktemp()
155 entries = mailcap.lookup(caps, content_type, "view")
156 for entry in entries:
157 if entry.has_key('copiousoutput'):
158 if entry.has_key('test'):
159 test = mailcap.subst(entry['test'], content_type, filename)
160 if test and os.system(test) != 0:
162 command = mailcap.subst(entry["view"], content_type, filename)
168 file = open(filename, 'w')
172 pipe = os.popen(command, 'r')
177 set_content_type(msg, "text/plain")
178 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, gopts.host_name, command.split()[0])
183 def recode_charset(msg, s):
184 "Recode charset of the message to the default charset"
186 save_charset = charset = msg.get_content_charset()
187 if charset and charset.lower() <> gopts.default_encoding:
188 s = recode_if_needed(s, charset)
189 content_type = msg.get_content_type()
190 set_content_type(msg, content_type, gopts.default_encoding)
191 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, gopts.default_encoding, gopts.host_name, me)
195 def totext(msg, instring):
196 "Convert instring content to text"
198 # Decode body and recode charset
199 s = decode_body(msg, instring)
200 if gopts.recode_charset:
201 s = recode_charset(msg, s)
207 def decode_part(msg):
208 "Decode one part of the message"
211 encoding = msg["Content-Transfer-Encoding"]
213 if encoding in (None, '', '7bit', '8bit', 'binary'):
214 outstring = str(msg.get_payload())
215 else: # Decode from transfer ecoding to text or binary form
216 outstring = str(msg.get_payload(decode=1))
217 set_header(msg, "Content-Transfer-Encoding", "8bit")
218 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, gopts.host_name, me)
220 # Test all mask lists and find what to do with this content type
222 ctype = msg.get_content_type()
225 mtype = msg.get_content_maintype()
227 masks.append(mtype + '/*')
230 for content_type in masks:
231 if content_type in gopts.totext_mask:
232 totext(msg, outstring)
234 elif content_type in gopts.binary_mask:
238 elif content_type in gopts.ignore_mask:
240 output("\nMessage body of type `%s' skipped.\n" % content_type)
242 elif content_type in gopts.error_mask:
243 raise ValueError, "content type `%s' prohibited" % content_type
245 # Neither content type nor masks were listed - decode by default
246 totext(msg, outstring)
249 def decode_multipart(msg):
255 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
256 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
258 boundary = msg.get_boundary()
260 for subpart in msg.get_payload():
262 output("\n--%s\n" % boundary)
264 # Recursively decode all parts of the subpart
265 decode_message(subpart)
268 output("\n--%s--\n" % boundary)
274 def decode_message(msg):
277 if msg.is_multipart():
278 decode_multipart(msg)
279 elif len(msg): # Simple one-part message (there are headers) - decode it
281 else: # Not a message, just text - copy it literally
282 output(msg.as_string())
286 from m_lib.defenc import default_encoding
287 recode_charset = 1 # recode charset of message body
291 # A list of headers to decode
292 decode_headers = ["From", "To", "Cc", "Reply-To", "Mail-Followup-To",
295 # A list of headers parameters to decode
296 decode_header_params = [
297 ("Content-Type", "name"),
298 ("Content-Disposition", "filename"),
301 # A list of headers to remove
303 # A list of headers parameters to remove
304 remove_header_params = []
305 # A list of headers to be stripped of all parameters
306 remove_all_params = []
308 totext_mask = [] # A list of content-types to decode
309 binary_mask = [] # A list to pass through
310 ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
311 error_mask = [] # Raise error if encounter one of these
313 input_filename = None
314 output_filename = None
316 gopts = GlobalOptions
320 from getopt import getopt, GetoptError
323 options, arguments = getopt(sys.argv[1:],
324 'hVcCDPH:f:d:p:r:R:b:e:i:t:o:',
325 ['help', 'version', 'host=', 'remove-params='])
329 for option, value in options:
330 if option in ('-h', '--help'):
332 elif option in ('-V', '--version'):
335 gopts.recode_charset = 1
337 gopts.recode_charset = 0
338 elif option in ('-H', '--host'):
339 gopts.host_name = value
341 gopts.default_encoding = value
343 gopts.decode_headers.append(value)
345 gopts.decode_headers = []
347 gopts.decode_header_params.append(value.split(':', 1))
349 gopts.decode_header_params = []
351 gopts.remove_headers.append(value)
353 gopts.remove_header_params.append(value.split(':', 1))
354 elif option == '--remove-params':
355 gopts.remove_all_params.append(value)
357 gopts.totext_mask.append(value)
359 gopts.binary_mask.append(value)
361 gopts.ignore_mask.append(value)
363 gopts.error_mask.append(value)
365 gopts.output_filename = value
372 if __name__ == "__main__":
373 arguments = get_opt()
377 gopts.input_filename = '-'
379 if gopts.output_filename:
380 outfile = open(gopts.output_filename, 'w')
382 gopts.output_filename = '-'
385 if (arguments[0] == '-'):
386 gopts.input_filename = '-'
389 gopts.input_filename = arguments[0]
390 infile = open(arguments[0], 'r')
392 if gopts.output_filename:
393 outfile = open(gopts.output_filename, 'w')
395 gopts.output_filename = '-'
398 if gopts.output_filename:
399 usage(1, 'Too many output filenames')
400 if (arguments[1] == '-'):
401 gopts.output_filename = '-'
404 gopts.output_filename = arguments[1]
405 outfile = open(arguments[1], 'w')
407 usage(1, 'Too many arguments')
409 if (infile is sys.stdin) and sys.stdin.isatty():
410 if (outfile is sys.stdout) and sys.stdout.isatty():
412 usage(1, 'Filtering from console is forbidden')
414 if not gopts.host_name:
416 gopts.host_name = socket.gethostname()
418 gopts.outfile = outfile
419 output = outfile.write
422 decode_message(email.message_from_file(infile))