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