Chapter 12 ■ Building and parsing e-Mail
232
--===============0086939546==
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="attachment.txt"
MIME-Version: 1.0
This is a test
--===============0086939546==
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="attachment.gz"
MIME-Version: 1.0
H4sIAP3o2D8AAwvJyCxWAKJEhZLU4hIuAIwtwPoPAAAA
--===============0086939546==--
This e-mail is concentric, with three levels of multipart content inside one another! As before, you can see that
all of the details have been handled for us. Each level has its own randomly generated boundary that does not conflict
with the boundary of either of the other levels. The proper kind of multipart container has been chosen in each case
for the kind of content that is included inside it.
Finally, proper encodings have been specified. Plain text has been permitted to travel literally inside the body of
the e-mail, while Base64 encoding has been used for binary data-like images that are not 7-bit safe. Note that in both
of these generation scripts, the e-mail object was asked to render itself explicitly as bytes, instead of asking for text that
would then have to be encoded before being saved or transmitted.
Adding Content
All four of the methods used to add content in Listing 12-3 share the same calling convention. Consult the Python
documentation to learn every possible combination that is supported in the particular version of Python 3 that you are
using. Here are some common combinations for the methods set_content(), add_related(), add_alternative(),
or add_attachment():
• method('string data of type str')
method('string data of type str', subtype='html')
These create parts that are some flavor of text. The content type will be text/plain unless
you provide a custom subtype—the second example call, for instance, results in a content
type of text/html.
• method(b'raw binary payload of type bytes', type='image', subtype='jpeg')
If you provide raw binary data, then Python will not try to guess what the type should be.
You have to provide both the MIME type and subtype yourself, which will be combined
with a slash in the output. Note that Listing 12-3 uses a mechanism outside the email
module itself, the mimetypes module, to try to guess an appropriate type for each
attachment file you specify on the command line.