]> git.notmuchmail.org Git - notmuch/blob - devel/printmimestructure
update NEWS for 0.29.2
[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 print_part(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         nbytes = len(z.as_string())
40     else:
41         nbytes = len(z.get_payload())
42
43     print('{}{}{}{}{} {:d} bytes'.format(
44         prefix,
45         z.get_content_type(),
46         cset,
47         disposition,
48         fname,
49         nbytes,
50     ))
51
52 def test(z, prefix=''):
53     if (z.is_multipart()):
54         print_part(z, prefix+'┬╴')
55         if prefix.endswith('└'):
56             prefix = prefix.rpartition('└')[0] + ' '
57         if prefix.endswith('├'):
58             prefix = prefix.rpartition('├')[0] + '│'
59         parts = z.get_payload()
60         i = 0
61         while (i < parts.__len__()-1):
62             test(parts[i], prefix + '├')
63             i += 1
64         test(parts[i], prefix + '└')
65         # FIXME: show epilogue?
66     else:
67         print_part(z, prefix+'─╴')
68
69 test(email.message_from_file(sys.stdin), '└')