Enhanced emails

The emails we've been looking at so far have been only simple text. Modern email usage often demands fancier formatted emails.

We can control the content type of an email using the Content-Type header. This is very similar to the content type header used by HTTP, which we covered in Chapter 7, Building a Simple Web Server.

If the content type header is missing, a content type of text/plain is assumed by default. Therefore, the Content-Type header in the following email is redundant:

From: Alice Doe <alice@example.net>
To: Bob Doe <bob@example.com>
Subject: Re: The Cake
Date: Fri, 03 May 2019 02:31:20 +0000
Content-Type: text/plain

Hi Bob,

Do NOT forget to bring the cake!

Best,
Alice

If you want formatting support in your email, which is common today, you should use a text/html content type. In the following email, HTML is used to add emphasis:

From: Alice Doe <alice@example.net>
To: Bob Doe <bob@example.com>
Subject: Re: The Cake
Date: Fri, 03 May 2019 02:31:20 +0000
Content-Type: text/html

Hi Bob,<br>
<br>
Do <strong>NOT</strong> forget to bring the cake!<br>
<br>
Best,<br>
Alice<br>

Not all email clients support HTML emails. For this reason, it may be useful to encode your message as both plaintext and HTML. The following email uses this technique:

From: Alice Doe <alice@example.net>
To: Bob Doe <bob@example.com>
Subject: Re: The Cake
Date: Fri, 03 May 2019 02:31:20 +0000
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="SEPARATOR"

This is a message with multiple parts in MIME format.
--SEPARATOR
Content-Type: text/plain

Hi Bob,

Do NOT forget to bring the cake!

Best,
Alice
--SEPARATOR
Content-Type: text/html

Hi Bob,<br>
<br>
Do <strong>NOT</strong> forget to bring the cake!<br>
<br>
Best,<br>
Alice<br>
--SEPARATOR--

The preceding email example uses two headers to indicate that it's a multipart message. The first one, MIME-Version: 1.0, indicates which version of Multipurpose Internet Mail Extensions (MIME) we're using. MIME is used for all emails that aren't simply plaintext.

The second header, Content-Type: multipart/alternative; boundary="SEPARATOR", specifies that we're sending a multipart message. It also specifies a special boundary character sequence that delineates the parts of the email. In our example, SEPARATOR is used as the boundary. It is important that the boundary not appear in the email text or attachments. In practice, boundary specifiers are often long randomly generated strings.

Once the boundary has been set, each part of the email begins with --SEPARATOR on a line by itself. The email ends with --SEPARATOR--. Note that each part of the message gets its own header section, specific to only that part. These header sections are used to specify the content type for each part.

It is also often useful to attach files to email, which we will cover now.