Skip to content
Sign inGet all access
Chapter 4·18 minFree

MIME

Attachments, HTML and anything not ASCII.

SMTP was specified for 7-bit ASCII text. Everything else is MIME.

Why MIME exists

A message body is lines of text — chapter 2 showed the rules. There is no room in that for an image.

MIME does not change SMTP. It encodes everything into text SMTP already carries, and adds headers saying how to undo it.

The two headers

MIME-Version: 1.0 says the message uses MIME. Content-Type says what it is:

EHLO test.local
MAIL FROM:<[email protected]>
RCPT TO:<[email protected]>
DATA
From: [email protected]
Subject: Simple
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8

Just text.
.
QUIT
Output250 Ok: queued as <id>@mailhog.example221 Bye

multipart/alternative

The same message twice, in two formats:

EHLO test.local
MAIL FROM:<[email protected]>
RCPT TO:<[email protected]>
DATA
From: [email protected]
Subject: Alt
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="BOUND1"

--BOUND1
Content-Type: text/plain

plain version

--BOUND1
Content-Type: text/html

<b>html version</b>

--BOUND1--
.
QUIT
Output221 Bye

A real parser reads it back as two parts:

curl -s localhost:8025/api/v2/messages | python3 -c '
import json, sys, email, email.policy
d = json.load(sys.stdin)
m = [x for x in d["items"]
     if "Alt" in str(x["Content"]["Headers"].get("Subject", ""))][0]
raw = "\r\n".join(k + ": " + v[0]
                 for k, v in m["Content"]["Headers"].items() if k != "Received")
msg = email.message_from_string(raw + "\r\n\r\n" + m["Content"]["Body"],
                                policy=email.policy.default)
print("is_multipart:", msg.is_multipart())
for p in msg.iter_parts():
    print(" ", p.get_content_type(), "->", repr(p.get_content().strip()))'
Outputis_multipart: True text/plain -> 'plain version' text/html -> '<b>html version</b>'

alternative means these are the same content. A client shows the last part it understands, which is why HTML goes second.

Boundaries

Three rules, and all three are easy to get wrong:

Where Looks like
In Content-Type boundary="BOUND1"
Before each part --BOUND1
After the last part --BOUND1--

Omit the hyphens and a parser finds nothing:

printf '%s\n' 'MIME-Version: 1.0' \
  'Content-Type: multipart/alternative; boundary="X"' '' \
  'X' 'Content-Type: text/plain' '' 'oops' 'X--' > /tmp/bad.eml
python3 -c 'import email,email.policy;print("parts found:",
  len(list(email.message_from_string(open("/tmp/bad.eml").read(),
  policy=email.policy.default).iter_parts())))'
Outputparts found: 0

The string is yours to choose and must appear in no part’s content — which is why real clients generate a long random one.

multipart/mixed

Parts that are not the same content:

EHLO test.local
MAIL FROM:<[email protected]>
RCPT TO:<[email protected]>
DATA
From: [email protected]
Subject: Mixed
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="MIX"

--MIX
Content-Type: text/plain

See attached.

--MIX
Content-Type: text/plain; name="note.txt"
Content-Disposition: attachment; filename="note.txt"
Content-Transfer-Encoding: base64

aGVsbG8gYXR0YWNobWVudA==

--MIX--
.
QUIT
Output221 Bye
curl -s localhost:8025/api/v2/messages | python3 -c '
import json, sys, email, email.policy
d = json.load(sys.stdin)
m = [x for x in d["items"]
     if "Mixed" in str(x["Content"]["Headers"].get("Subject", ""))][0]
raw = "\r\n".join(k + ": " + v[0]
                 for k, v in m["Content"]["Headers"].items() if k != "Received")
msg = email.message_from_string(raw + "\r\n\r\n" + m["Content"]["Body"],
                                policy=email.policy.default)
for p in msg.iter_parts():
    print(p.get_content_type(), "| filename:", p.get_filename(),
          "|", repr(p.get_content().strip()))'
Outputtext/plain | filename: None | 'See attached.'text/plain | filename: note.txt | 'hello attachment'

The parser decoded the base64 back to hello attachment. Nothing was binary on the wire.

Content-Transfer-Encoding

Two encodings, and the choice is about what the data looks like:

python3 -c '
import quopri, base64
s = "Grüße".encode()
print("qp:    ", quopri.encodestring(s).decode())
print("base64:", base64.b64encode(s).decode())'
Outputqp: Gr=C3=BC=C3=9Febase64: R3LDvMOfZQ==

Quoted-printable leaves ASCII alone and escapes the rest. Base64 encodes everything and grows by a third.

Encoded-words

A header cannot hold raw UTF-8, so a non-ASCII subject is encoded in place:

python3 -c '
from email.header import Header, decode_header
h = Header("Grüße aus München", "utf-8").encode()
print("encoded:", h)
print("decoded:", decode_header(h)[0][0].decode("utf-8"))'
Outputencoded: =?utf-8?b?R3LDvMOfZSBhdXMgTcO8bmNoZW4=?=decoded: Grüße aus München

=?charset?encoding?data?=, with b for base64 and q for quoted-printable.

Each encoded-word is limited to 75 characters, so a long subject becomes several. Never split one by hand.

Content-Disposition

One header decides whether a part is rendered or offered as a file:

Value Client does
inline render it in the message
attachment offer it as a file
attachment; filename="x" offer it with that name
python3 -c 'import email, email.policy
for d in ["inline", "attachment", "attachment; filename=x.pdf"]:
    m = email.message_from_string(
        "Content-Type: text/plain\nContent-Disposition: " + d + "\n\nx",
        policy=email.policy.default)
    print(d, "->", m.get_content_disposition(), m.get_filename())'
Outputinline -> inline Noneattachment -> attachment Noneattachment; filename=x.pdf -> attachment x.pdf

Nesting

A real message is a tree. HTML plus a plain-text alternative plus an attachment needs two levels:

terminal
python3 -c 'import email, email.policy
msg = email.message_from_string(open("/tmp/nested.eml").read(),
                                policy=email.policy.default)
def walk(p, d=0):
    print("  " * d + p.get_content_type())
    if p.is_multipart():
        for s in p.iter_parts(): walk(s, d + 1)
walk(msg)'
Outputmultipart/mixed multipart/alternative text/plain text/html application/pdf

multipart/related is the third you will meet — an HTML part plus the images it references, tied by Content-ID and cid: URLs.