1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2019 Daniel Kahn Gillmor
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
'''
This script reads a MIME message from stdin and produces a treelike
representation on it stdout.
Example:
0 dkg@alice:~$ printmimestructure < 'Maildir/cur/1269025522.M338697P12023.monkey,S=6459,W=6963:2,Sa'
└┬╴multipart/signed 6546 bytes
├─╴text/plain inline 895 bytes
└─╴application/pgp-signature inline [signature.asc] 836 bytes
0 dkg@alice:~$
If you want to number the parts, i suggest piping the output through
something like "cat -n"
'''
import sys
import email
import logging
from argparse import ArgumentParser, Namespace
from typing import Optional, Union, List, Tuple, Any
from email.charset import Charset
from email.message import Message
class MimePrinter(object):
def __init__(self, args:Namespace):
self.args = args
def print_part(self, z:Message, prefix:str, parent:Optional[Message], num:int) -> None:
ofname:Optional[str] = z.get_filename()
fname:str = '' if ofname is None else f' [{ofname}]'
ocharset:Union[Charset, str, None] = z.get_charset()
cset:str = '' if ocharset is None else f' ({ocharset})'
disp:Union[List[Tuple[str,str]], List[str], None] = z.get_params(None, header='Content-Disposition')
disposition:str = ''
if (disp is not None):
for d in disp:
if d[0] in [ 'attachment', 'inline' ]:
disposition = ' ' + d[0]
nbytes:int
if z.is_multipart():
# FIXME: it looks like we are counting chars here, not bytes:
nbytes = len(z.as_string())
else:
payload:Union[List[Message], str, bytes, None] = z.get_payload()
if not isinstance(payload, (str,bytes)):
raise TypeError(f'expected payload to be either str or bytes, got {type(payload)}')
# FIXME: it looks like we are counting chars here, not bytes:
nbytes = len(payload)
print(f'{prefix}{z.get_content_type()}{cset}{disposition}{fname} {nbytes:d} bytes')
def test(self, z:Message, prefix:str, parent:Optional[Message], num:int) -> None:
if (z.is_multipart()):
self.print_part(z, prefix+'┬╴', parent, num)
if prefix.endswith('└'):
prefix = prefix.rpartition('└')[0] + ' '
if prefix.endswith('├'):
prefix = prefix.rpartition('├')[0] + '│'
parts:Union[List[Message], str, bytes, None] = z.get_payload()
if not isinstance(parts, list):
raise TypeError(f'parts was {type(parts)}, expected List[Message]')
i = 0
while (i < len(parts)-1):
self.test(parts[i], prefix + '├', z, i+1)
i += 1
self.test(parts[i], prefix + '└', z, i+1)
# FIXME: show epilogue?
else:
self.print_part(z, prefix+'─╴', parent, num)
def main() -> None:
parser:ArgumentParser = ArgumentParser(description='Read RFC2822 MIME message from stdin and emit a tree diagram to stdout.',
epilog="Example: email-print-mime-structure < message.eml")
args:Namespace = parser.parse_args()
msg:Union[Message, str, int, Any] = email.message_from_file(sys.stdin)
if isinstance(msg, Message):
printer:MimePrinter = MimePrinter(args)
printer.test(msg, '└', None, 0)
else:
logging.error('Input was not an e-mail message')
if __name__ == '__main__':
main()
|