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__))
33 Usage: %s [-h|--help] [-V|--version] [-cCDP] [-f charset] [-d header] [-p header:param] [-beit mask] [input_file [output_file]]
39 gopts.outfile.write(s)
41 def output_headers(msg):
42 unix_from = msg.get_unixfrom()
44 output(unix_from + '\n')
45 for key, value in msg.items():
46 output("%s: %s\n" % (key, value))
47 output("\n") # End of headers
50 def recode(s, charset):
51 return unicode(s, charset, "replace").encode(gopts.default_encoding, "replace")
54 def recode2(s, charset):
55 if charset and charset.lower() <> gopts.default_encoding:
56 s = recode(s, charset)
60 def _decode_header(s):
61 """Return a decoded string according to RFC 2047.
62 NOTE: This is almost the same as email.Utils.decode.
64 from types import ListType
67 L = email.Header.decode_header(s)
68 if not isinstance(L, ListType):
73 for atom, charset in L:
77 rtn.append(recode2(atom, charset))
79 del rtn[-1] # remove the last space
81 # Now that we've decoded everything, we just need to join all the parts
82 # together into the final string.
86 def decode_header(msg, header):
87 "Decode mail header (if exists) and put it back, if it was encoded"
89 if msg.has_key(header):
91 new_value = _decode_header(value)
92 if new_value <> value: # do not bother to touch msg if not changed
93 set_header(msg, header, new_value)
96 def _decode_header_param(s):
97 return recode2(s[2], s[0])
100 def decode_header_param(msg, header, param):
101 "Decode mail header's parameter (if exists) and put it back, if it was encoded"
103 if msg.has_key(header):
104 value = msg.get_param(param, header=header)
106 from types import TupleType
107 if isinstance(value, TupleType):
108 new_value = _decode_header_param(value)
110 new_value = _decode_header(value)
111 if new_value <> value: # do not bother to touch msg if not changed
112 msg.set_param(param, new_value, header)
115 def decode_headers(msg):
116 "Decode message headers according to global options"
118 for header in gopts.decode_headers:
119 decode_header(msg, header)
121 for header, param in gopts.decode_header_params:
122 decode_header_param(msg, header, param)
125 def set_header(msg, header, value):
128 if msg.has_key(header):
129 msg.replace_header(header, value)
134 def set_content_type(msg, newtype, charset=None):
135 msg.set_type(newtype)
138 msg.set_param("charset", charset, "Content-Type")
142 caps = None # Globally stored mailcap database; initialized only if needed
144 def decode_body(msg, s):
145 "Decode body to plain text using first copiousoutput filter from mailcap"
147 import mailcap, tempfile
151 caps = mailcap.getcaps()
153 content_type = msg.get_content_type()
154 filename = tempfile.mktemp()
157 entries = mailcap.lookup(caps, content_type, "view")
158 for entry in entries:
159 if entry.has_key('copiousoutput'):
160 if entry.has_key('test'):
161 test = mailcap.subst(entry['test'], content_type, filename)
162 if test and os.system(test) != 0:
164 command = mailcap.subst(entry["view"], content_type, filename)
170 file = open(filename, 'w')
174 pipe = os.popen(command, 'r')
179 set_content_type(msg, "text/plain")
180 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, host_name, command.split()[0])
185 def recode_charset(msg, s):
186 "Recode charset of the message to the default charset"
188 save_charset = charset = msg.get_content_charset()
189 if charset and charset.lower() <> gopts.default_encoding:
190 s = recode2(s, charset)
191 content_type = msg.get_content_type()
192 set_content_type(msg, content_type, gopts.default_encoding)
193 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, gopts.default_encoding, host_name, me)
197 def totext(msg, instring):
198 "Convert instring content to text"
200 if msg.is_multipart(): # Recursively decode all parts of the multipart message
201 newfile = StringIO(str(msg))
206 # Decode body and recode charset
207 s = decode_body(msg, instring)
208 if gopts.recode_charset:
209 s = recode_charset(msg, s)
215 def decode_part(msg):
216 "Decode one part of the message"
219 encoding = msg["Content-Transfer-Encoding"]
221 if encoding in (None, '', '7bit', '8bit', 'binary'):
222 outstring = str(msg.get_payload())
223 else: # Decode from transfer ecoding to text or binary form
224 outstring = str(msg.get_payload(decode=1))
225 set_header(msg, "Content-Transfer-Encoding", "8bit")
226 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, host_name, me)
228 # Test all mask lists and find what to do with this content type
230 ctype = msg.get_content_type()
233 mtype = msg.get_content_maintype()
235 masks.append(mtype + '/*')
238 for content_type in masks:
239 if content_type in gopts.totext_mask:
240 totext(msg, outstring)
242 elif content_type in gopts.binary_mask:
246 elif content_type in gopts.ignore_mask:
248 output("\nMessage body of type `%s' skipped.\n" % content_type)
250 elif content_type in gopts.error_mask:
251 raise ValueError, "content type `%s' prohibited" % content_type
253 # Neither content type nor masks were listed - decode by default
254 totext(msg, outstring)
257 def decode_file(infile):
258 "Decode the entire message"
260 msg = email.message_from_file(infile)
261 boundary = msg.get_boundary()
263 if msg.is_multipart():
267 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
268 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
270 for subpart in msg.get_payload():
271 output("\n--%s\n" % boundary)
274 output("\n--%s--\n" % boundary)
280 if msg.has_key("Content-Type"): # Simple one-part message - decode it
283 else: # Not a message, just text - copy it literally
288 from m_lib.defenc import default_encoding
289 recode_charset = 1 # recode charset of message body
291 decode_headers = ["From", "Subject"] # A list of headers to decode
292 decode_header_params = [
293 ("Content-Type", "name"),
294 ("Content-Disposition", "filename"),
295 ] # A list of headers' parameters to decode
297 totext_mask = [] # A list of content-types to decode
298 binary_mask = [] # A list to pass through
299 ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
300 error_mask = [] # Raise error if encounter one of these
302 gopts = GlobalOptions
306 from getopt import getopt, GetoptError
309 options, arguments = getopt(sys.argv[1:], 'hVcCDPf:d:p:b:e:i:t:',
314 for option, value in options:
317 elif option == '--help':
321 elif option == '--version':
324 gopts.recode_charset = 1
326 gopts.recode_charset = 0
328 gopts.default_encoding = value
330 gopts.decode_headers.append(value)
332 gopts.decode_headers = []
334 gopts.decode_header_params.append(value.split(':', 1))
336 gopts.decode_header_params = []
338 gopts.totext_mask.append(value)
340 gopts.binary_mask.append(value)
342 gopts.ignore_mask.append(value)
344 gopts.error_mask.append(value)
351 if __name__ == "__main__":
352 arguments = get_opt()
358 if (arguments[0] == '-'):
361 infile = open(arguments[0], 'r')
365 if (arguments[1] == '-'):
368 outfile = open(arguments[1], 'w')
372 gopts.outfile = outfile