ยปCore Development>Code coverage>Doc/includes/email-read-alternative.py

Python code coverage for Doc/includes/email-read-alternative.py

#countcontent
1n/aimport os
2n/aimport sys
3n/aimport tempfile
4n/aimport mimetypes
5n/aimport webbrowser
6n/a
7n/a# Import the email modules we'll need
8n/afrom email import policy
9n/afrom email.parser import BytesParser
10n/a
11n/a# An imaginary module that would make this work and be safe.
12n/afrom imaginary import magic_html_parser
13n/a
14n/a# In a real program you'd get the filename from the arguments.
15n/awith open('outgoing.msg', 'rb') as fp:
16n/a msg = BytesParser(policy=policy.default).parse(fp)
17n/a
18n/a# Now the header items can be accessed as a dictionary, and any non-ASCII will
19n/a# be converted to unicode:
20n/aprint('To:', msg['to'])
21n/aprint('From:', msg['from'])
22n/aprint('Subject:', msg['subject'])
23n/a
24n/a# If we want to print a priview of the message content, we can extract whatever
25n/a# the least formatted payload is and print the first three lines. Of course,
26n/a# if the message has no plain text part printing the first three lines of html
27n/a# is probably useless, but this is just a conceptual example.
28n/asimplest = msg.get_body(preferencelist=('plain', 'html'))
29n/aprint()
30n/aprint(''.join(simplest.get_content().splitlines(keepends=True)[:3]))
31n/a
32n/aans = input("View full message?")
33n/aif ans.lower()[0] == 'n':
34n/a sys.exit()
35n/a
36n/a# We can extract the richest alternative in order to display it:
37n/arichest = msg.get_body()
38n/apartfiles = {}
39n/aif richest['content-type'].maintype == 'text':
40n/a if richest['content-type'].subtype == 'plain':
41n/a for line in richest.get_content().splitlines():
42n/a print(line)
43n/a sys.exit()
44n/a elif richest['content-type'].subtype == 'html':
45n/a body = richest
46n/a else:
47n/a print("Don't know how to display {}".format(richest.get_content_type()))
48n/a sys.exit()
49n/aelif richest['content-type'].content_type == 'multipart/related':
50n/a body = richest.get_body(preferencelist=('html'))
51n/a for part in richest.iter_attachments():
52n/a fn = part.get_filename()
53n/a if fn:
54n/a extension = os.path.splitext(part.get_filename())[1]
55n/a else:
56n/a extension = mimetypes.guess_extension(part.get_content_type())
57n/a with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as f:
58n/a f.write(part.get_content())
59n/a # again strip the <> to go from email form of cid to html form.
60n/a partfiles[part['content-id'][1:-1]] = f.name
61n/aelse:
62n/a print("Don't know how to display {}".format(richest.get_content_type()))
63n/a sys.exit()
64n/awith tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
65n/a # The magic_html_parser has to rewrite the href="cid:...." attributes to
66n/a # point to the filenames in partfiles. It also has to do a safety-sanitize
67n/a # of the html. It could be written using html.parser.
68n/a f.write(magic_html_parser(body.get_content(), partfiles))
69n/awebbrowser.open(f.name)
70n/aos.remove(f.name)
71n/afor fn in partfiles.values():
72n/a os.remove(fn)
73n/a
74n/a# Of course, there are lots of email messages that could break this simple
75n/a# minded program, but it will handle the most common ones.