2 """Decode MIME message"""
5 from mimedecode_version import __version__, __author__, __copyright__, __license__
12 from cStringIO import StringIO
14 from StringIO import StringIO
18 host_name = socket.gethostname()
20 me = os.path.basename(sys.argv[0])
25 Broytman mimedecode.py version %s, %s
26 """ % (__version__, __copyright__))
30 def usage(code=0, errormsg=''):
33 Usage: %s [-h|--help] [-V|--version] [-cCDP] [-f charset] [-d header] [-p header:param] [-beit mask] [-o output_file] [input_file [output_file]]
36 sys.stderr.write(errormsg + '\n')
41 gopts.outfile.write(s)
43 def output_headers(msg):
44 unix_from = msg.get_unixfrom()
46 output(unix_from + '\n')
47 for key, value in msg.items():
48 output("%s: %s\n" % (key, value))
49 output("\n") # End of headers
52 def recode(s, charset):
53 return unicode(s, charset, "replace").encode(gopts.default_encoding, "replace")
56 def recode2(s, charset):
57 if charset and charset.lower() <> gopts.default_encoding:
58 s = recode(s, charset)
62 def _decode_header(s):
63 """Return a decoded string according to RFC 2047.
64 NOTE: This is almost the same as email.Utils.decode.
66 from types import ListType
69 L = email.Header.decode_header(s)
70 if not isinstance(L, ListType):
75 for atom, charset in L:
79 rtn.append(recode2(atom, charset))
81 del rtn[-1] # remove the last space
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"
91 if msg.has_key(header):
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(s):
99 return recode2(s[2], s[0])
102 def decode_header_param(msg, header, param):
103 "Decode mail header's parameter (if exists) and put it back, if it was encoded"
105 if msg.has_key(header):
106 value = msg.get_param(param, header=header)
108 from types import TupleType
109 if isinstance(value, TupleType):
110 new_value = _decode_header_param(value)
112 new_value = _decode_header(value)
113 if new_value <> value: # do not bother to touch msg if not changed
114 msg.set_param(param, new_value, header)
117 def decode_headers(msg):
118 "Decode message headers according to global options"
120 for header in gopts.decode_headers:
121 decode_header(msg, header)
123 for header, param in gopts.decode_header_params:
124 decode_header_param(msg, header, param)
127 def set_header(msg, header, value):
130 if msg.has_key(header):
131 msg.replace_header(header, value)
136 def set_content_type(msg, newtype, charset=None):
137 msg.set_type(newtype)
140 msg.set_param("charset", charset, "Content-Type")
144 caps = None # Globally stored mailcap database; initialized only if needed
146 def decode_body(msg, s):
147 "Decode body to plain text using first copiousoutput filter from mailcap"
149 import mailcap, tempfile
153 caps = mailcap.getcaps()
155 content_type = msg.get_content_type()
156 filename = tempfile.mktemp()
159 entries = mailcap.lookup(caps, content_type, "view")
160 for entry in entries:
161 if entry.has_key('copiousoutput'):
162 if entry.has_key('test'):
163 test = mailcap.subst(entry['test'], content_type, filename)
164 if test and os.system(test) != 0:
166 command = mailcap.subst(entry["view"], content_type, filename)
172 file = open(filename, 'w')
176 pipe = os.popen(command, 'r')
181 set_content_type(msg, "text/plain")
182 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, host_name, command.split()[0])
187 def recode_charset(msg, s):
188 "Recode charset of the message to the default charset"
190 save_charset = charset = msg.get_content_charset()
191 if charset and charset.lower() <> gopts.default_encoding:
192 s = recode2(s, charset)
193 content_type = msg.get_content_type()
194 set_content_type(msg, content_type, gopts.default_encoding)
195 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, gopts.default_encoding, host_name, me)
199 def totext(msg, instring):
200 "Convert instring content to text"
202 if msg.is_multipart(): # Recursively decode all parts of the multipart message
203 newfile = StringIO(str(msg))
208 # Decode body and recode charset
209 s = decode_body(msg, instring)
210 if gopts.recode_charset:
211 s = recode_charset(msg, s)
217 def decode_part(msg):
218 "Decode one part of the message"
221 encoding = msg["Content-Transfer-Encoding"]
223 if encoding in (None, '', '7bit', '8bit', 'binary'):
224 outstring = str(msg.get_payload())
225 else: # Decode from transfer ecoding to text or binary form
226 outstring = str(msg.get_payload(decode=1))
227 set_header(msg, "Content-Transfer-Encoding", "8bit")
228 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, host_name, me)
230 # Test all mask lists and find what to do with this content type
232 ctype = msg.get_content_type()
235 mtype = msg.get_content_maintype()
237 masks.append(mtype + '/*')
240 for content_type in masks:
241 if content_type in gopts.totext_mask:
242 totext(msg, outstring)
244 elif content_type in gopts.binary_mask:
248 elif content_type in gopts.ignore_mask:
250 output("\nMessage body of type `%s' skipped.\n" % content_type)
252 elif content_type in gopts.error_mask:
253 raise ValueError, "content type `%s' prohibited" % content_type
255 # Neither content type nor masks were listed - decode by default
256 totext(msg, outstring)
259 def decode_file(infile):
260 "Decode the entire message"
262 msg = email.message_from_file(infile)
263 boundary = msg.get_boundary()
265 if msg.is_multipart():
269 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
270 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
272 for subpart in msg.get_payload():
273 output("\n--%s\n" % boundary)
276 output("\n--%s--\n" % boundary)
282 if msg.has_key("Content-Type"): # Simple one-part message - decode it
285 else: # Not a message, just text - copy it literally
290 from m_lib.defenc import default_encoding
291 recode_charset = 1 # recode charset of message body
293 decode_headers = ["From", "Subject"] # A list of headers to decode
294 decode_header_params = [
295 ("Content-Type", "name"),
296 ("Content-Disposition", "filename"),
297 ] # A list of headers' parameters to decode
299 totext_mask = [] # A list of content-types to decode
300 binary_mask = [] # A list to pass through
301 ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
302 error_mask = [] # Raise error if encounter one of these
304 input_filename = None
305 output_filename = None
307 gopts = GlobalOptions
311 from getopt import getopt, GetoptError
314 options, arguments = getopt(sys.argv[1:], 'hVcCDPf:d:p:b:e:i:t:o:',
319 for option, value in options:
322 elif option == '--help':
326 elif option == '--version':
329 gopts.recode_charset = 1
331 gopts.recode_charset = 0
333 gopts.default_encoding = value
335 gopts.decode_headers.append(value)
337 gopts.decode_headers = []
339 gopts.decode_header_params.append(value.split(':', 1))
341 gopts.decode_header_params = []
343 gopts.totext_mask.append(value)
345 gopts.binary_mask.append(value)
347 gopts.ignore_mask.append(value)
349 gopts.error_mask.append(value)
351 gopts.output_filename = value
358 if __name__ == "__main__":
359 arguments = get_opt()
363 gopts.input_filename = '-'
364 gopts.output_filename = '-'
368 if (arguments[0] == '-'):
369 gopts.input_filename = '-'
372 gopts.input_filename = arguments[0]
373 infile = open(arguments[0], 'r')
375 if gopts.output_filename:
376 outfile = open(gopts.output_filename, 'w')
378 gopts.output_filename = '-'
381 if gopts.output_filename:
382 usage(1, 'Too many output filenames')
383 if (arguments[1] == '-'):
384 gopts.output_filename = '-'
387 gopts.output_filename = arguments[1]
388 outfile = open(arguments[1], 'w')
390 usage(1, 'Too many arguments')
392 if (infile is sys.stdin) and (outfile is sys.stdout) and \
393 sys.stdin.isatty() and sys.stdout.isatty():
394 usage(1, 'Filtering from console to console is forbidden')
396 gopts.outfile = outfile