Chapter 12 ■ Building and parsing e-Mail
230
To: Test Recipient [email protected]
From: Test Sender [email protected]
Subject: Foundations of Python Network Programming
Date: Tue, 25 Mar 2014 17:14:01 -0400
Message-ID: 20140325232008.15748.50494@guinness
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="===============1627694678=="
--===============1627694678==
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 7bit
Hello,
This is a test message from Chapter 12.
- Anonymous
--===============1627694678==
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
Hello,
This is a MIME message from Chapter 12.
- Anonymous
--===============1627694678==--
At its top level, the above e-mail follows the old standard format: headers, blank line, and body. But now the body
is suddenly more interesting. In order to carry two payloads, plain text and HTML, the headers specify a boundary
that splits the body into several smaller parts. Each part is itself in the traditional format: headers, blank line, and
body. There is only one (rather obvious) restriction on the contents of a part: a part cannot contain a copy of either its
own boundary line or the boundary line of any of the enclosing messages.
The multipart/alternative content type is one example of a whole family of multipart/* content types, all of
which follow exactly the same rules regarding the establishment of a boundary line and its use in delimiting the MIME
subparts beneath it. Its role is to carry several versions of a message, any one of which can be displayed to the user and
thereby communicate the message’s whole meaning. In this case, the user can be shown either the HTML or the plain
text, but the user will see essentially the same e-mail either way. Most clients will opt for HTML if they are capable
of displaying it. Although most e-mail clients will hide the fact than an alternative was even offered, some do offer a
button or drop-down menu that will let the user see an alternative version if they wish.
Note that the MIME-Version header only gets specified at the top level of the message, but the email module has
handled this without the sender having to know that detail of the standard.
The rules about multipart sections are as follows:
• If you call add_related() at least once, then the body you specified with set_content() will
get grouped together with all of the related content inside a single multipart/related section.
• If you call add_alternative() at least once, then a multipart/alternative container is
created to hold the original body together with the alternative part(s) you add.
• Finally, if you call add_attachment() at least once, then an outer multipart/mixed container
is generated to hold the content next to all of the attachments you add.