1 #! /usr/local/bin/python -O
2 """Decode MIME message.
4 Author: Oleg Broytmann <phd@phd.pp.ru>
5 Copyright: (C) 2001-2002 PhiloSoft Design
10 __copyright__ = "Copyright (C) 2001-2002 PhiloSoft Design"
17 from cStringIO import StringIO
19 from StringIO import StringIO
23 host_name = socket.gethostname()
25 me = os.path.basename(sys.argv[0])
30 BroytMann mimedecode.py version %s, %s
31 """ % (__version__, __copyright__))
38 Usage: %s [-h|--help] [-V|--version] [-cCDP] [-f charset] [-d header] [-p header:param] [-beit mask] [filename]
43 def output(s, outfile = sys.stdout):
46 def output_headers(msg, outfile = sys.stdout):
47 unix_from = msg.get_unixfrom()
49 output(unix_from + os.linesep)
50 for key, value in msg.items():
51 output("%s: %s\n" % (key, value), outfile)
52 output("\n", outfile) # End of headers
55 def recode(s, charset):
56 return unicode(s, charset, "replace").encode(GlobalOptions.default_charset, "replace")
59 def recode2(s, charset):
60 if charset and charset <> GlobalOptions.default_charset:
61 s = recode(s, charset)
65 def _decode_header(s):
66 """Return a decoded string according to RFC 2047.
67 NOTE: This is almost the same as email.Utils.decode.
69 from types import ListType
72 L = email.Header.decode_header(s)
73 if not isinstance(L, ListType):
78 for atom, charset in L:
82 rtn.append(recode2(atom, charset))
84 del rtn[-1] # remove the last space
86 # Now that we've decoded everything, we just need to join all the parts
87 # together into the final string.
91 def decode_header(msg, header):
92 "Decode mail header (if exists) and put it back, if it was encoded"
94 if msg.has_key(header):
96 new_value = _decode_header(value)
97 if new_value <> value: # do not bother to touch msg if not changed
98 set_header(msg, header, new_value)
101 def _decode_header_param(s):
102 return recode2(s[2], s[0])
105 def decode_header_param(msg, header, param):
106 "Decode mail header's parameter (if exists) and put it back, if it was encoded"
108 if msg.has_key(header):
109 value = msg.get_param(param, header=header)
111 from types import TupleType
112 if isinstance(value, TupleType):
113 new_value = _decode_header_param(value)
115 new_value = _decode_header(value)
116 if new_value <> value: # do not bother to touch msg if not changed
117 msg.set_param(param, new_value, header)
120 def decode_headers(msg):
121 "Decode message headers according to global options"
123 for header in GlobalOptions.decode_headers:
124 decode_header(msg, header)
126 for header, param in GlobalOptions.decode_header_params:
127 decode_header_param(msg, header, param)
130 def set_header(msg, header, value):
133 if msg.has_key(header):
134 msg.replace_header(header, value)
139 def set_content_type(msg, newtype, charset=None):
140 msg.set_type(newtype)
143 msg.set_param("charset", charset, "Content-Type")
147 caps = None # Globally stored mailcap database; initialized only if needed
149 def decode_body(msg, s):
150 "Decode body to plain text using first copiousoutput filter from mailcap"
152 import mailcap, tempfile
156 caps = mailcap.getcaps()
158 content_type = msg.get_content_type()
159 filename = tempfile.mktemp()
162 entries = mailcap.lookup(caps, content_type, "view")
163 for entry in entries:
164 if entry.has_key('copiousoutput'):
165 if entry.has_key('test'):
166 test = mailcap.subst(entry['test'], content_type, filename)
167 if test and os.system(test) != 0:
169 command = mailcap.subst(entry["view"], content_type, filename)
175 file = open(filename, 'w')
179 pipe = os.popen(command, 'r')
184 set_content_type(msg, "text/plain")
185 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, host_name, command.split()[0])
190 def recode_charset(msg, s):
191 "Recode charset of the message to the default charset"
193 save_charset = charset = msg.get_content_charset()
194 if charset and charset <> GlobalOptions.default_charset:
195 s = recode2(s, charset)
196 content_type = msg.get_content_type()
197 set_content_type(msg, content_type, GlobalOptions.default_charset)
198 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, GlobalOptions.default_charset, host_name, me)
202 def totext(msg, instring):
203 "Convert instring content to text"
205 if msg.is_multipart(): # Recursively decode all parts of the multipart message
206 newfile = StringIO(str(msg))
211 # Decode body and recode charset
212 s = decode_body(msg, instring)
213 if GlobalOptions.recode_charset:
214 s = recode_charset(msg, s)
220 def decode_part(msg):
221 "Decode one part of the message"
224 encoding = msg["Content-Transfer-Encoding"]
226 if encoding in (None, '', '7bit', '8bit', 'binary'):
227 outstring = str(msg.get_payload())
228 else: # Decode from transfer ecoding to text or binary form
229 outstring = str(msg.get_payload(decode=1))
230 set_header(msg, "Content-Transfer-Encoding", "8bit")
231 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, host_name, me)
233 # Test all mask lists and find what to do with this content type
235 ctype = msg.get_content_type()
238 mtype = msg.get_content_maintype()
240 masks.append(mtype + '/*')
243 for content_type in masks:
244 if content_type in GlobalOptions.totext_mask:
245 totext(msg, outstring)
247 elif content_type in GlobalOptions.binary_mask:
251 elif content_type in GlobalOptions.ignore_mask:
253 output("\nMessage body of type `%s' skipped.\n" % content_type)
255 elif content_type in GlobalOptions.error_mask:
256 raise ValueError, "content type `%s' prohibited" % content_type
258 # Neither content type nor masks were listed - decode by default
259 totext(msg, outstring)
262 def decode_file(infile):
263 "Decode the entire message"
265 msg = email.message_from_file(infile)
266 boundary = msg.get_boundary()
268 if msg.is_multipart():
272 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
273 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
275 for subpart in msg.get_payload():
276 output("\n--%s\n" % boundary)
279 output("\n--%s--\n" % boundary)
285 if msg.has_key("Content-Type"): # Simple one-part message - decode it
288 else: # Not a message, just text - copy it literally
293 default_charset = sys.getdefaultencoding()
294 recode_charset = 1 # recode charset of message body
296 decode_headers = ["Subject", "From"] # A list of headers to decode
297 decode_header_params = [("Content-Type", "name"),
298 ("Content-Disposition", "filename")
299 ] # A list of headers' parameters to decode
301 totext_mask = [] # A list of content-types to decode
302 binary_mask = [] # A list to pass through
303 ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
304 error_mask = [] # Raise error if encounter one of these
308 from getopt import getopt, GetoptError
311 options, arguments = getopt(sys.argv[1:], 'hVcCDPf:d:p:b:e:i:t:',
316 for option, value in options:
319 elif option == '--help':
323 elif option == '--version':
326 GlobalOptions.recode_charset = 1
328 GlobalOptions.recode_charset = 0
330 GlobalOptions.default_charset = value
332 GlobalOptions.decode_headers.append(value)
334 GlobalOptions.decode_headers = []
336 GlobalOptions.decode_header_params.append(value.split(':', 1))
338 GlobalOptions.decode_header_params = []
340 GlobalOptions.totext_mask.append(value)
342 GlobalOptions.binary_mask.append(value)
344 GlobalOptions.ignore_mask.append(value)
346 GlobalOptions.error_mask.append(value)
353 if __name__ == "__main__":
356 if len(arguments) == 0:
358 elif len(arguments) <> 1:
360 elif arguments[0] == '-':
363 infile = open(arguments[0], 'r')