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 header] [-p header:param] [-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.
50 from types import ListType
53 L = email.Header.decode_header(s)
54 if not isinstance(L, ListType):
59 for atom, charset in L:
63 rtn.append(recode_if_needed(atom, charset))
65 del rtn[-1] # remove the last space
67 # Now that we've decoded everything, we just need to join all the parts
68 # together into the final string.
71 def decode_header(msg, header):
72 "Decode mail header (if exists) and put it back, if it was encoded"
74 if msg.has_key(header):
76 new_value = _decode_header(value)
77 if new_value <> value: # do not bother to touch msg if not changed
78 set_header(msg, header, new_value)
81 def _decode_header_param(s):
82 return recode_if_needed(s[2], s[0])
84 def decode_header_param(msg, header, param):
85 "Decode mail header's parameter (if exists) and put it back, if it was encoded"
87 if msg.has_key(header):
88 value = msg.get_param(param, header=header)
90 from types import TupleType
91 if isinstance(value, TupleType):
92 new_value = _decode_header_param(value)
94 new_value = _decode_header(value)
95 if new_value <> value: # do not bother to touch msg if not changed
96 msg.set_param(param, new_value, header)
99 def decode_headers(msg):
100 "Decode message headers according to global options"
102 for header in gopts.decode_headers:
103 decode_header(msg, header)
105 for header, param in gopts.decode_header_params:
106 decode_header_param(msg, header, param)
109 def set_header(msg, header, value):
112 if msg.has_key(header):
113 msg.replace_header(header, value)
118 def set_content_type(msg, newtype, charset=None):
119 msg.set_type(newtype)
122 msg.set_param("charset", charset, "Content-Type")
125 caps = None # Globally stored mailcap database; initialized only if needed
127 def decode_body(msg, s):
128 "Decode body to plain text using first copiousoutput filter from mailcap"
130 import mailcap, tempfile
134 caps = mailcap.getcaps()
136 content_type = msg.get_content_type()
137 filename = tempfile.mktemp()
140 entries = mailcap.lookup(caps, content_type, "view")
141 for entry in entries:
142 if entry.has_key('copiousoutput'):
143 if entry.has_key('test'):
144 test = mailcap.subst(entry['test'], content_type, filename)
145 if test and os.system(test) != 0:
147 command = mailcap.subst(entry["view"], content_type, filename)
153 file = open(filename, 'w')
157 pipe = os.popen(command, 'r')
162 set_content_type(msg, "text/plain")
163 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, gopts.host_name, command.split()[0])
168 def recode_charset(msg, s):
169 "Recode charset of the message to the default charset"
171 save_charset = charset = msg.get_content_charset()
172 if charset and charset.lower() <> gopts.default_encoding:
173 s = recode_if_needed(s, charset)
174 content_type = msg.get_content_type()
175 set_content_type(msg, content_type, gopts.default_encoding)
176 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, gopts.default_encoding, gopts.host_name, me)
180 def totext(msg, instring):
181 "Convert instring content to text"
183 # Decode body and recode charset
184 s = decode_body(msg, instring)
185 if gopts.recode_charset:
186 s = recode_charset(msg, s)
192 def decode_part(msg):
193 "Decode one part of the message"
196 encoding = msg["Content-Transfer-Encoding"]
198 if encoding in (None, '', '7bit', '8bit', 'binary'):
199 outstring = str(msg.get_payload())
200 else: # Decode from transfer ecoding to text or binary form
201 outstring = str(msg.get_payload(decode=1))
202 set_header(msg, "Content-Transfer-Encoding", "8bit")
203 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, gopts.host_name, me)
205 # Test all mask lists and find what to do with this content type
207 ctype = msg.get_content_type()
210 mtype = msg.get_content_maintype()
212 masks.append(mtype + '/*')
215 for content_type in masks:
216 if content_type in gopts.totext_mask:
217 totext(msg, outstring)
219 elif content_type in gopts.binary_mask:
223 elif content_type in gopts.ignore_mask:
225 output("\nMessage body of type `%s' skipped.\n" % content_type)
227 elif content_type in gopts.error_mask:
228 raise ValueError, "content type `%s' prohibited" % content_type
230 # Neither content type nor masks were listed - decode by default
231 totext(msg, outstring)
234 def decode_message(msg):
237 if msg.is_multipart():
241 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
242 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
244 boundary = msg.get_boundary()
246 for subpart in msg.get_payload():
248 output("\n--%s\n" % boundary)
250 if subpart.is_multipart(): # Recursively decode all parts of the subpart
251 decode_message(subpart)
256 output("\n--%s--\n" % boundary)
261 elif msg.has_key("Content-Type"): # Simple one-part message - decode it
264 else: # Not a message, just text - copy it literally
265 output(msg.as_string())
269 from m_lib.defenc import default_encoding
270 recode_charset = 1 # recode charset of message body
274 decode_headers = ["From", "Subject"] # A list of headers to decode
275 decode_header_params = [
276 ("Content-Type", "name"),
277 ("Content-Disposition", "filename"),
278 ] # A list of headers' parameters to decode
280 totext_mask = [] # A list of content-types to decode
281 binary_mask = [] # A list to pass through
282 ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
283 error_mask = [] # Raise error if encounter one of these
285 input_filename = None
286 output_filename = None
288 gopts = GlobalOptions
292 from getopt import getopt, GetoptError
295 options, arguments = getopt(sys.argv[1:], 'hVcCDPH:f:d:p:b:e:i:t:o:',
296 ['help', 'version', 'host'])
300 for option, value in options:
301 if option in ('-h', '--help'):
303 elif option in ('-V', '--version'):
306 gopts.recode_charset = 1
308 gopts.recode_charset = 0
309 elif option in ('-H', '--host'):
310 gopts.host_name = value
312 gopts.default_encoding = value
314 gopts.decode_headers.append(value)
316 gopts.decode_headers = []
318 gopts.decode_header_params.append(value.split(':', 1))
320 gopts.decode_header_params = []
322 gopts.totext_mask.append(value)
324 gopts.binary_mask.append(value)
326 gopts.ignore_mask.append(value)
328 gopts.error_mask.append(value)
330 gopts.output_filename = value
337 if __name__ == "__main__":
338 arguments = get_opt()
342 gopts.input_filename = '-'
344 if gopts.output_filename:
345 outfile = open(gopts.output_filename, 'w')
347 gopts.output_filename = '-'
350 if (arguments[0] == '-'):
351 gopts.input_filename = '-'
354 gopts.input_filename = arguments[0]
355 infile = open(arguments[0], 'r')
357 if gopts.output_filename:
358 outfile = open(gopts.output_filename, 'w')
360 gopts.output_filename = '-'
363 if gopts.output_filename:
364 usage(1, 'Too many output filenames')
365 if (arguments[1] == '-'):
366 gopts.output_filename = '-'
369 gopts.output_filename = arguments[1]
370 outfile = open(arguments[1], 'w')
372 usage(1, 'Too many arguments')
374 if (infile is sys.stdin) and sys.stdin.isatty():
375 if (outfile is sys.stdout) and sys.stdout.isatty():
377 usage(1, 'Filtering from console is forbidden')
379 if not gopts.host_name:
381 gopts.host_name = socket.gethostname()
383 gopts.outfile = outfile
384 output = outfile.write
387 decode_message(email.message_from_file(infile))