Foundations of Python Network Programming

(WallPaper) #1

Chapter 12 ■ Building and parsing e-Mail


236


•    When examining a normal part, the Content-Disposition header will tell you whether it is
intended as an attachment (look for the word attachment preceding any semicolon in the
header’s value).

•    Calling the get_content() method decodes and returns the data itself from inside a MIME
part as either a text str or a binary bytes object depending on whether the main content type
is text or not.

The code in Listing 12-5 uses a recursive generator to visit every part of a multipart message. The generator’s
operation is similar to that of the build-in walk() method, except that this generator keeps up with the index of each
subpart in case it needs to be fetched later.


Listing 12-5. Visiting Every Part of a Multipart Method Manually


#!/usr/bin/env python3


Foundations of Python Network Programming, Third Edition


https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter12/display_structure.py


import argparse, email.policy, sys


def walk(part, prefix=''):
yield prefix, part
for i, subpart in enumerate(part.iter_parts()):
yield from walk(subpart, prefix + '.{}'.format(i))


def main(binary_file):
policy = email.policy.SMTP
message = email.message_from_binary_file(binary_file, policy=policy)
for prefix, part in walk(message):
line = '{} type={}'.format(prefix, part.get_content_type())
if not part.is_multipart():
content = part.get_content()
line += ' {} len={}'.format(type(content).name, len(content))
cd = part['Content-Disposition']
is_attachment = cd and cd.split(';')[0].lower() == 'attachment'
if is_attachment:
line += ' attachment'
filename = part.get_filename()
if filename is not None:
line += ' filename={!r}'.format(filename)
print(line)


if name == 'main':
parser = argparse.ArgumentParser(description='Display MIME structure')
parser.add_argument('filename', nargs='?', help='File containing an email')
args = parser.parse_args()
if args.filename is None:
main(sys.stdin.buffer)
else:
with open(args.filename, 'rb') as f:
main(f)

Free download pdf