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