2 """Decode MIME message"""
4 from mimedecode_version import __version__, __author__, __copyright__, __license__
10 from cStringIO import StringIO
12 from StringIO import StringIO
14 me = os.path.basename(sys.argv[0])
19 Broytman mimedecode.py version %s, %s
20 """ % (__version__, __copyright__))
23 def usage(code=0, errormsg=''):
26 Usage: %s [-h|--help] [-V|--version] [-cCDP] [-H|--host=hostname] [-f charset] [-d header] [-p header:param] [-beit mask] [-o output_file] [input_file [output_file]]
29 sys.stderr.write(errormsg + '\n')
33 def output_headers(msg):
34 unix_from = msg.get_unixfrom()
36 output(unix_from + '\n')
37 for key, value in msg.items():
38 output("%s: %s\n" % (key, value))
39 output("\n") # End of headers
42 def recode(s, charset):
43 return unicode(s, charset, "replace").encode(gopts.default_encoding, "replace")
45 def recode_if_needed(s, charset):
46 if charset and charset.lower() <> gopts.default_encoding:
47 s = recode(s, charset)
51 def _decode_header(s):
52 """Return a decoded string according to RFC 2047.
53 NOTE: This is almost the same as email.Utils.decode.
55 from types import ListType
58 L = email.Header.decode_header(s)
59 if not isinstance(L, ListType):
64 for atom, charset in L:
68 rtn.append(recode_if_needed(atom, charset))
70 del rtn[-1] # remove the last space
72 # Now that we've decoded everything, we just need to join all the parts
73 # together into the final string.
76 def decode_header(msg, header):
77 "Decode mail header (if exists) and put it back, if it was encoded"
79 if msg.has_key(header):
81 new_value = _decode_header(value)
82 if new_value <> value: # do not bother to touch msg if not changed
83 set_header(msg, header, new_value)
86 def _decode_header_param(s):
87 return recode_if_needed(s[2], s[0])
89 def decode_header_param(msg, header, param):
90 "Decode mail header's parameter (if exists) and put it back, if it was encoded"
92 if msg.has_key(header):
93 value = msg.get_param(param, header=header)
95 from types import TupleType
96 if isinstance(value, TupleType):
97 new_value = _decode_header_param(value)
99 new_value = _decode_header(value)
100 if new_value <> value: # do not bother to touch msg if not changed
101 msg.set_param(param, new_value, header)
104 def decode_headers(msg):
105 "Decode message headers according to global options"
107 for header in gopts.decode_headers:
108 decode_header(msg, header)
110 for header, param in gopts.decode_header_params:
111 decode_header_param(msg, header, param)
114 def set_header(msg, header, value):
117 if msg.has_key(header):
118 msg.replace_header(header, value)
123 def set_content_type(msg, newtype, charset=None):
124 msg.set_type(newtype)
127 msg.set_param("charset", charset, "Content-Type")
130 caps = None # Globally stored mailcap database; initialized only if needed
132 def decode_body(msg, s):
133 "Decode body to plain text using first copiousoutput filter from mailcap"
135 import mailcap, tempfile
139 caps = mailcap.getcaps()
141 content_type = msg.get_content_type()
142 filename = tempfile.mktemp()
145 entries = mailcap.lookup(caps, content_type, "view")
146 for entry in entries:
147 if entry.has_key('copiousoutput'):
148 if entry.has_key('test'):
149 test = mailcap.subst(entry['test'], content_type, filename)
150 if test and os.system(test) != 0:
152 command = mailcap.subst(entry["view"], content_type, filename)
158 file = open(filename, 'w')
162 pipe = os.popen(command, 'r')
167 set_content_type(msg, "text/plain")
168 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, gopts.host_name, command.split()[0])
173 def recode_charset(msg, s):
174 "Recode charset of the message to the default charset"
176 save_charset = charset = msg.get_content_charset()
177 if charset and charset.lower() <> gopts.default_encoding:
178 s = recode_if_needed(s, charset)
179 content_type = msg.get_content_type()
180 set_content_type(msg, content_type, gopts.default_encoding)
181 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, gopts.default_encoding, gopts.host_name, me)
185 def totext(msg, instring):
186 "Convert instring content to text"
188 if msg.is_multipart(): # Recursively decode all parts of the multipart message
189 newfile = StringIO(msg.as_string())
194 # Decode body and recode charset
195 s = decode_body(msg, instring)
196 if gopts.recode_charset:
197 s = recode_charset(msg, s)
203 def decode_part(msg):
204 "Decode one part of the message"
207 encoding = msg["Content-Transfer-Encoding"]
209 if encoding in (None, '', '7bit', '8bit', 'binary'):
210 outstring = str(msg.get_payload())
211 else: # Decode from transfer ecoding to text or binary form
212 outstring = str(msg.get_payload(decode=1))
213 set_header(msg, "Content-Transfer-Encoding", "8bit")
214 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, gopts.host_name, me)
216 # Test all mask lists and find what to do with this content type
218 ctype = msg.get_content_type()
221 mtype = msg.get_content_maintype()
223 masks.append(mtype + '/*')
226 for content_type in masks:
227 if content_type in gopts.totext_mask:
228 totext(msg, outstring)
230 elif content_type in gopts.binary_mask:
234 elif content_type in gopts.ignore_mask:
236 output("\nMessage body of type `%s' skipped.\n" % content_type)
238 elif content_type in gopts.error_mask:
239 raise ValueError, "content type `%s' prohibited" % content_type
241 # Neither content type nor masks were listed - decode by default
242 totext(msg, outstring)
245 def decode_file(infile):
246 "Decode the entire message"
248 msg = email.message_from_file(infile)
250 if msg.is_multipart():
254 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
255 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
257 boundary = msg.get_boundary()
259 for subpart in msg.get_payload():
260 output("\n--%s\n" % boundary)
263 output("\n--%s--\n" % boundary)
269 if msg.has_key("Content-Type"): # Simple one-part message - decode it
272 else: # Not a message, just text - copy it literally
273 output(msg.as_string())
277 from m_lib.defenc import default_encoding
278 recode_charset = 1 # recode charset of message body
282 decode_headers = ["From", "Subject"] # A list of headers to decode
283 decode_header_params = [
284 ("Content-Type", "name"),
285 ("Content-Disposition", "filename"),
286 ] # A list of headers' parameters to decode
288 totext_mask = [] # A list of content-types to decode
289 binary_mask = [] # A list to pass through
290 ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
291 error_mask = [] # Raise error if encounter one of these
293 input_filename = None
294 output_filename = None
296 gopts = GlobalOptions
300 from getopt import getopt, GetoptError
303 options, arguments = getopt(sys.argv[1:], 'hVcCDPH:f:d:p:b:e:i:t:o:',
304 ['help', 'version', 'host'])
308 for option, value in options:
309 if option in ('-h', '--help'):
311 elif option in ('-V', '--version'):
314 gopts.recode_charset = 1
316 gopts.recode_charset = 0
317 elif option in ('-H', '--host'):
318 gopts.host_name = value
320 gopts.default_encoding = value
322 gopts.decode_headers.append(value)
324 gopts.decode_headers = []
326 gopts.decode_header_params.append(value.split(':', 1))
328 gopts.decode_header_params = []
330 gopts.totext_mask.append(value)
332 gopts.binary_mask.append(value)
334 gopts.ignore_mask.append(value)
336 gopts.error_mask.append(value)
338 gopts.output_filename = value
345 if __name__ == "__main__":
346 arguments = get_opt()
350 gopts.input_filename = '-'
352 if gopts.output_filename:
353 outfile = open(gopts.output_filename, 'w')
355 gopts.output_filename = '-'
358 if (arguments[0] == '-'):
359 gopts.input_filename = '-'
362 gopts.input_filename = arguments[0]
363 infile = open(arguments[0], 'r')
365 if gopts.output_filename:
366 outfile = open(gopts.output_filename, 'w')
368 gopts.output_filename = '-'
371 if gopts.output_filename:
372 usage(1, 'Too many output filenames')
373 if (arguments[1] == '-'):
374 gopts.output_filename = '-'
377 gopts.output_filename = arguments[1]
378 outfile = open(arguments[1], 'w')
380 usage(1, 'Too many arguments')
382 if (infile is sys.stdin) and sys.stdin.isatty():
383 if (outfile is sys.stdout) and sys.stdout.isatty():
385 usage(1, 'Filtering from console is forbidden')
387 if not gopts.host_name:
389 gopts.host_name = socket.gethostname()
391 gopts.outfile = outfile
392 output = outfile.write