]> git.cworth.org Git - notmuch/blob - devel/printmimestructure
devel: make printmimestructure py3 compatible
[notmuch] / devel / printmimestructure
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # Author: Daniel Kahn Gillmor <dkg@fifthhorseman.net>
5 # License: GPLv3+
6
7 # This script reads a MIME message from stdin and produces a treelike
8 # representation on it stdout.
9
10 # Example:
11 #
12 # 0 dkg@alice:~$ printmimestructure < 'Maildir/cur/1269025522.M338697P12023.monkey,S=6459,W=6963:2,Sa'
13 # └┬╴multipart/signed 6546 bytes
14 #  ├─╴text/plain inline 895 bytes
15 #  └─╴application/pgp-signature inline [signature.asc] 836 bytes
16 # 0 dkg@alice:~$
17
18
19 # If you want to number the parts, i suggest piping the output through
20 # something like "cat -n"
21
22 from __future__ import print_function
23
24 import email
25 import sys
26
27 def test(z, prefix=''):
28     fname = '' if z.get_filename() is None else ' [' + z.get_filename() + ']'
29     cset = '' if z.get_charset() is None else ' (' + z.get_charset() + ')'
30     disp = z.get_params(None, header='Content-Disposition')
31     if (disp is None):
32         disposition = ''
33     else:
34         disposition = ''
35         for d in disp:
36             if d[0] in [ 'attachment', 'inline' ]:
37                 disposition = ' ' + d[0]
38     if (z.is_multipart()):
39         print(prefix + '┬╴' + z.get_content_type() + cset + disposition + fname, z.as_string().__len__().__str__() + ' bytes')
40         if prefix.endswith('└'):
41             prefix = prefix.rpartition('└')[0] + ' '
42         if prefix.endswith('├'):
43             prefix = prefix.rpartition('├')[0] + '│'
44         parts = z.get_payload()
45         i = 0
46         while (i < parts.__len__()-1):
47             test(parts[i], prefix + '├')
48             i += 1
49         test(parts[i], prefix + '└')
50         # FIXME: show epilogue?
51     else:
52         print(prefix + '─╴'+ z.get_content_type() + cset + disposition + fname, z.get_payload().__len__().__str__(), 'bytes')
53
54 test(email.message_from_file(sys.stdin), '└')