]> git.phdru.name Git - mimedecode.git/blob - mimedecode.py
bfee2fe65c0d0c9f001c40c6245b3d9a80c31c17
[mimedecode.git] / mimedecode.py
1 #! /usr/local/bin/python -O
2 """Decode MIME message.
3
4 Author: Oleg Broytmann <phd@phd.pp.ru>
5 Copyright: (C) 2001-2006 PhiloSoft Design
6 License: GPL
7 """
8
9 _version = "2.1.0"
10 __version__ = "$Revision$"[11:-2]
11 __date__ = "$Date$"[7:-2]
12 __revision__ = "$Id$"[5:-2]
13 __author__ = "Oleg Broytmann <phd@phd.pp.ru>"
14 __copyright__ = "Copyright (C) 2001-2006 PhiloSoft Design"
15 __license__ = "GNU GPL"
16 __docformat__ = "epytext en"
17
18
19 import sys, os
20 import email
21
22 try:
23    from cStringIO import StringIO
24 except ImportError:
25    from StringIO import StringIO
26
27
28 import socket
29 host_name = socket.gethostname()
30
31 me = os.path.basename(sys.argv[0])
32
33
34 def version(exit=1):
35    sys.stdout.write("""\
36 BroytMann mimedecode.py version %s, %s
37 """ % (_version, __copyright__))
38    if exit: sys.exit(0)
39
40
41 def usage(code=0):
42    version(0)
43    sys.stdout.write("""\
44 Usage: %s [-h|--help] [-V|--version] [-cCDP] [-f charset] [-d header] [-p header:param] [-beit mask] [filename]
45 """ % me)
46    sys.exit(code)
47
48
49 def output(s, outfile = sys.stdout):
50    outfile.write(s)
51
52 def output_headers(msg, outfile = sys.stdout):
53    unix_from = msg.get_unixfrom()
54    if unix_from:
55       output(unix_from + os.linesep)
56    for key, value in msg.items():
57       output("%s: %s\n" % (key, value), outfile)
58    output("\n", outfile) # End of headers
59
60
61 def recode(s, charset):
62    return unicode(s, charset, "replace").encode(GlobalOptions.default_charset, "replace")
63
64
65 def recode2(s, charset):
66    if charset and charset <> GlobalOptions.default_charset:
67       s = recode(s, charset)
68    return s
69
70
71 def _decode_header(s):
72    """Return a decoded string according to RFC 2047.
73    NOTE: This is almost the same as email.Utils.decode.
74    """
75    from types import ListType
76    import email.Header
77
78    L = email.Header.decode_header(s)
79    if not isinstance(L, ListType):
80       # s wasn't decoded
81       return s
82
83    rtn = []
84    for atom, charset in L:
85       if charset is None:
86          rtn.append(atom)
87       else:
88          rtn.append(recode2(atom, charset))
89       rtn.append(' ')
90    del rtn[-1] # remove the last space
91
92    # Now that we've decoded everything, we just need to join all the parts
93    # together into the final string.
94    return ''.join(rtn)
95
96
97 def decode_header(msg, header):
98    "Decode mail header (if exists) and put it back, if it was encoded"
99
100    if msg.has_key(header):
101       value = msg[header]
102       new_value = _decode_header(value)
103       if new_value <> value: # do not bother to touch msg if not changed
104          set_header(msg, header, new_value)
105
106
107 def _decode_header_param(s):
108    return recode2(s[2], s[0])
109
110
111 def decode_header_param(msg, header, param):
112    "Decode mail header's parameter (if exists) and put it back, if it was encoded"
113
114    if msg.has_key(header):
115       value = msg.get_param(param, header=header)
116       if value:
117          from types import TupleType
118          if isinstance(value, TupleType):
119             new_value = _decode_header_param(value)
120          else:
121             new_value = _decode_header(value)
122          if new_value <> value: # do not bother to touch msg if not changed
123             msg.set_param(param, new_value, header)
124
125
126 def decode_headers(msg):
127    "Decode message headers according to global options"
128
129    for header in GlobalOptions.decode_headers:
130       decode_header(msg, header)
131
132    for header, param in GlobalOptions.decode_header_params:
133       decode_header_param(msg, header, param)
134
135
136 def set_header(msg, header, value):
137    "Replace header"
138
139    if msg.has_key(header):
140       msg.replace_header(header, value)
141    else:
142       msg[header] = value
143
144
145 def set_content_type(msg, newtype, charset=None):
146    msg.set_type(newtype)
147
148    if charset:
149       msg.set_param("charset", charset, "Content-Type")
150
151
152
153 caps = None # Globally stored mailcap database; initialized only if needed
154
155 def decode_body(msg, s):
156    "Decode body to plain text using first copiousoutput filter from mailcap"
157
158    import mailcap, tempfile
159
160    global caps
161    if caps is None:
162       caps = mailcap.getcaps()
163
164    content_type = msg.get_content_type()
165    filename = tempfile.mktemp()
166    command = None
167
168    entries = mailcap.lookup(caps, content_type, "view")
169    for entry in entries:
170       if entry.has_key('copiousoutput'):
171          if entry.has_key('test'):
172             test = mailcap.subst(entry['test'], content_type, filename)
173             if test and os.system(test) != 0:
174                continue
175          command = mailcap.subst(entry["view"], content_type, filename)
176          break
177
178    if not command:
179       return s
180
181    file = open(filename, 'w')
182    file.write(s)
183    file.close()
184
185    pipe = os.popen(command, 'r')
186    s = pipe.read()
187    pipe.close()
188    os.remove(filename)
189
190    set_content_type(msg, "text/plain")
191    msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, host_name, command.split()[0])
192
193    return s
194
195
196 def recode_charset(msg, s):
197    "Recode charset of the message to the default charset"
198
199    save_charset = charset = msg.get_content_charset()
200    if charset and charset <> GlobalOptions.default_charset:
201       s = recode2(s, charset)
202       content_type = msg.get_content_type()
203       set_content_type(msg, content_type, GlobalOptions.default_charset)
204       msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, GlobalOptions.default_charset, host_name, me)
205    return s
206
207
208 def totext(msg, instring):
209    "Convert instring content to text"
210
211    if msg.is_multipart(): # Recursively decode all parts of the multipart message
212       newfile = StringIO(str(msg))
213       newfile.seek(0)
214       decode_file(newfile)
215       return
216
217    # Decode body and recode charset
218    s = decode_body(msg, instring)
219    if GlobalOptions.recode_charset:
220       s = recode_charset(msg, s)
221
222    output_headers(msg)
223    output(s)
224
225
226 def decode_part(msg):
227    "Decode one part of the message"
228
229    decode_headers(msg)
230    encoding = msg["Content-Transfer-Encoding"]
231
232    if encoding in (None, '', '7bit', '8bit', 'binary'):
233       outstring = str(msg.get_payload())
234    else: # Decode from transfer ecoding to text or binary form
235       outstring = str(msg.get_payload(decode=1))
236       set_header(msg, "Content-Transfer-Encoding", "8bit")
237       msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, host_name, me)
238
239    # Test all mask lists and find what to do with this content type
240    masks = []
241    ctype = msg.get_content_type()
242    if ctype:
243       masks.append(ctype)
244    mtype = msg.get_content_maintype()
245    if mtype:
246       masks.append(mtype + '/*')
247    masks.append('*/*')
248
249    for content_type in masks:
250       if content_type in GlobalOptions.totext_mask:
251          totext(msg, outstring)
252          return
253       elif content_type in GlobalOptions.binary_mask:
254          output_headers(msg)
255          output(outstring)
256          return
257       elif content_type in GlobalOptions.ignore_mask:
258          output_headers(msg)
259          output("\nMessage body of type `%s' skipped.\n" % content_type)
260          return
261       elif content_type in GlobalOptions.error_mask:
262          raise ValueError, "content type `%s' prohibited" % content_type
263
264    # Neither content type nor masks were listed - decode by default
265    totext(msg, outstring)
266
267
268 def decode_file(infile):
269    "Decode the entire message"
270
271    msg = email.message_from_file(infile)
272    boundary = msg.get_boundary()
273
274    if msg.is_multipart():
275       decode_headers(msg)
276       output_headers(msg)
277
278       if msg.preamble: # Preserve the first part, it is probably not a RFC822-message
279          output(msg.preamble) # Usually it is just a few lines of text (MIME warning)
280
281       for subpart in msg.get_payload():
282          output("\n--%s\n" % boundary)
283          decode_part(subpart)
284
285       output("\n--%s--\n" % boundary)
286
287       if msg.epilogue:
288          output(msg.epilogue)
289
290    else:
291       if msg.has_key("Content-Type"): # Simple one-part message - decode it
292          decode_part(msg)
293
294       else: # Not a message, just text - copy it literally
295          output(str(msg))
296
297
298 class GlobalOptions:
299    default_charset = sys.getdefaultencoding()
300    recode_charset = 1 # recode charset of message body
301
302    decode_headers = ["Subject", "From"] # A list of headers to decode
303    decode_header_params = [("Content-Type", "name"),
304       ("Content-Disposition", "filename")
305    ] # A list of headers' parameters to decode
306
307    totext_mask = [] # A list of content-types to decode
308    binary_mask = [] # A list to pass through
309    ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
310    error_mask = []  # Raise error if encounter one of these
311
312
313 def init():
314    from getopt import getopt, GetoptError
315
316    try:
317       options, arguments = getopt(sys.argv[1:], 'hVcCDPf:d:p:b:e:i:t:',
318          ['help', 'version'])
319    except GetoptError:
320       usage(1)
321
322    for option, value in options:
323       if option == '-h':
324          usage()
325       elif option == '--help':
326          usage()
327       elif option == '-V':
328          version()
329       elif option == '--version':
330          version()
331       elif option == '-c':
332          GlobalOptions.recode_charset = 1
333       elif option == '-C':
334          GlobalOptions.recode_charset = 0
335       elif option == '-f':
336          GlobalOptions.default_charset = value
337       elif option == '-d':
338          GlobalOptions.decode_headers.append(value)
339       elif option == '-D':
340          GlobalOptions.decode_headers = []
341       elif option == '-p':
342          GlobalOptions.decode_header_params.append(value.split(':', 1))
343       elif option == '-P':
344          GlobalOptions.decode_header_params = []
345       elif option == '-t':
346          GlobalOptions.totext_mask.append(value)
347       elif option == '-b':
348          GlobalOptions.binary_mask.append(value)
349       elif option == '-i':
350          GlobalOptions.ignore_mask.append(value)
351       elif option == '-e':
352          GlobalOptions.error_mask.append(value)
353       else:
354          usage(1)
355
356    return arguments
357
358
359 if __name__ == "__main__":
360    arguments = init()
361
362    if len(arguments) == 0:
363       infile = sys.stdin
364    elif len(arguments) <> 1:
365       usage(1)
366    elif arguments[0] == '-':
367       infile = sys.stdin
368    else:
369       infile = open(arguments[0], 'r')
370
371    decode_file(infile)