2 """Decode MIME message"""
6 __author__ = "Oleg Broytman <phd@phdru.name>"
7 __copyright__ = "Copyright (C) 2001-2013 PhiloSoft Design"
8 __license__ = "GNU GPL"
15 from cStringIO import StringIO
17 from StringIO import StringIO
21 host_name = socket.gethostname()
23 me = os.path.basename(sys.argv[0])
28 Broytman mimedecode.py version %s, %s
29 """ % (__version__, __copyright__))
36 Usage: %s [-h|--help] [-V|--version] [-cCDP] [-f charset] [-d header] [-p header:param] [-beit mask] [filename]
41 def output(s, outfile = sys.stdout):
44 def output_headers(msg, outfile = sys.stdout):
45 unix_from = msg.get_unixfrom()
47 output(unix_from + os.linesep)
48 for key, value in msg.items():
49 output("%s: %s\n" % (key, value), outfile)
50 output("\n", outfile) # End of headers
53 def recode(s, charset):
54 return unicode(s, charset, "replace").encode(GlobalOptions.default_encoding, "replace")
57 def recode2(s, charset):
58 if charset and charset.lower() <> GlobalOptions.default_encoding:
59 s = recode(s, charset)
63 def _decode_header(s):
64 """Return a decoded string according to RFC 2047.
65 NOTE: This is almost the same as email.Utils.decode.
67 from types import ListType
70 L = email.Header.decode_header(s)
71 if not isinstance(L, ListType):
76 for atom, charset in L:
80 rtn.append(recode2(atom, charset))
82 del rtn[-1] # remove the last space
84 # Now that we've decoded everything, we just need to join all the parts
85 # together into the final string.
89 def decode_header(msg, header):
90 "Decode mail header (if exists) and put it back, if it was encoded"
92 if msg.has_key(header):
94 new_value = _decode_header(value)
95 if new_value <> value: # do not bother to touch msg if not changed
96 set_header(msg, header, new_value)
99 def _decode_header_param(s):
100 return recode2(s[2], s[0])
103 def decode_header_param(msg, header, param):
104 "Decode mail header's parameter (if exists) and put it back, if it was encoded"
106 if msg.has_key(header):
107 value = msg.get_param(param, header=header)
109 from types import TupleType
110 if isinstance(value, TupleType):
111 new_value = _decode_header_param(value)
113 new_value = _decode_header(value)
114 if new_value <> value: # do not bother to touch msg if not changed
115 msg.set_param(param, new_value, header)
118 def decode_headers(msg):
119 "Decode message headers according to global options"
121 for header in GlobalOptions.decode_headers:
122 decode_header(msg, header)
124 for header, param in GlobalOptions.decode_header_params:
125 decode_header_param(msg, header, param)
128 def set_header(msg, header, value):
131 if msg.has_key(header):
132 msg.replace_header(header, value)
137 def set_content_type(msg, newtype, charset=None):
138 msg.set_type(newtype)
141 msg.set_param("charset", charset, "Content-Type")
145 caps = None # Globally stored mailcap database; initialized only if needed
147 def decode_body(msg, s):
148 "Decode body to plain text using first copiousoutput filter from mailcap"
150 import mailcap, tempfile
154 caps = mailcap.getcaps()
156 content_type = msg.get_content_type()
157 filename = tempfile.mktemp()
160 entries = mailcap.lookup(caps, content_type, "view")
161 for entry in entries:
162 if entry.has_key('copiousoutput'):
163 if entry.has_key('test'):
164 test = mailcap.subst(entry['test'], content_type, filename)
165 if test and os.system(test) != 0:
167 command = mailcap.subst(entry["view"], content_type, filename)
173 file = open(filename, 'w')
177 pipe = os.popen(command, 'r')
182 set_content_type(msg, "text/plain")
183 msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, host_name, command.split()[0])
188 def recode_charset(msg, s):
189 "Recode charset of the message to the default charset"
191 save_charset = charset = msg.get_content_charset()
192 if charset and charset.lower() <> GlobalOptions.default_encoding:
193 s = recode2(s, charset)
194 content_type = msg.get_content_type()
195 set_content_type(msg, content_type, GlobalOptions.default_encoding)
196 msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, GlobalOptions.default_encoding, host_name, me)
200 def totext(msg, instring):
201 "Convert instring content to text"
203 if msg.is_multipart(): # Recursively decode all parts of the multipart message
204 newfile = StringIO(str(msg))
209 # Decode body and recode charset
210 s = decode_body(msg, instring)
211 if GlobalOptions.recode_charset:
212 s = recode_charset(msg, s)
218 def decode_part(msg):
219 "Decode one part of the message"
222 encoding = msg["Content-Transfer-Encoding"]
224 if encoding in (None, '', '7bit', '8bit', 'binary'):
225 outstring = str(msg.get_payload())
226 else: # Decode from transfer ecoding to text or binary form
227 outstring = str(msg.get_payload(decode=1))
228 set_header(msg, "Content-Transfer-Encoding", "8bit")
229 msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, host_name, me)
231 # Test all mask lists and find what to do with this content type
233 ctype = msg.get_content_type()
236 mtype = msg.get_content_maintype()
238 masks.append(mtype + '/*')
241 for content_type in masks:
242 if content_type in GlobalOptions.totext_mask:
243 totext(msg, outstring)
245 elif content_type in GlobalOptions.binary_mask:
249 elif content_type in GlobalOptions.ignore_mask:
251 output("\nMessage body of type `%s' skipped.\n" % content_type)
253 elif content_type in GlobalOptions.error_mask:
254 raise ValueError, "content type `%s' prohibited" % content_type
256 # Neither content type nor masks were listed - decode by default
257 totext(msg, outstring)
260 def decode_file(infile):
261 "Decode the entire message"
263 msg = email.message_from_file(infile)
264 boundary = msg.get_boundary()
266 if msg.is_multipart():
270 if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
271 output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
273 for subpart in msg.get_payload():
274 output("\n--%s\n" % boundary)
277 output("\n--%s--\n" % boundary)
283 if msg.has_key("Content-Type"): # Simple one-part message - decode it
286 else: # Not a message, just text - copy it literally
291 from m_lib.defenc import default_encoding
292 recode_charset = 1 # recode charset of message body
294 decode_headers = ["Subject", "From"] # A list of headers to decode
295 decode_header_params = [("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
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 GlobalOptions.recode_charset = 1
326 GlobalOptions.recode_charset = 0
328 GlobalOptions.default_encoding = value
330 GlobalOptions.decode_headers.append(value)
332 GlobalOptions.decode_headers = []
334 GlobalOptions.decode_header_params.append(value.split(':', 1))
336 GlobalOptions.decode_header_params = []
338 GlobalOptions.totext_mask.append(value)
340 GlobalOptions.binary_mask.append(value)
342 GlobalOptions.ignore_mask.append(value)
344 GlobalOptions.error_mask.append(value)
351 if __name__ == "__main__":
359 elif arguments[0] == '-':
362 infile = open(arguments[0], 'r')