Chapter 12 ■ Building and parsing e-Mail
229
message.add_related(blue_dot, 'image', 'gif', cid=cid,
filename='blue-dot.gif')
message.add_alternative(plain)
for filename in args.filename:
mime_type, encoding = mimetypes.guess_type(filename)
if encoding or (mime_type is None):
mime_type = 'application/octet-stream'
main, sub = mime_type.split('/')
if main == 'text':
with open(filename, encoding='utf-8') as f:
text = f.read()
message.add_attachment(text, sub, filename=filename)
else:
with open(filename, 'rb') as f:
data = f.read()
message.add_attachment(data, main, sub, filename=filename)
sys.stdout.buffer.write(message.as_bytes())
if name == 'main':
parser = argparse.ArgumentParser(description='Build, print a MIME email')
parser.add_argument('-i', action='store_true', help='Include GIF image')
parser.add_argument('filename', nargs='*', help='Attachment filename')
main(parser.parse_args())
There are four different ways you can call the script in Listing 12-3. In order of increasing complexity, they are:
• python3 build_mime_email.py
• python3 build_mime_email.py attachment.txt attachment.gz
• python3 build_mime_email.py -i
• python3 build_mime_email.py -i attachment.txt attachment.gz
To save space, I will only display the output of the first and last of these four command lines here, but you
should download build_mime_email.py yourself and try out the others if you want to see how the MIME standard
supports gradually increasing levels of complexity depending on the needs of the caller. Although two sample
files—attachment.txt (plain text) and attachment.gz (binary)—are included in the book’s source repository next to
the script, feel free to list any attachments on the command line that you wish. Doing so will let you see how different
binary payloads get encoded by the Python email module.
Calling build_mime_email.py without any options or attachments produces the simplest-possible MIME
structure for providing two alternative versions of an e-mail: HTML and plain text. The results of this are shown here.