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