Base64 in MIME/Email Attachments
How email systems use Base64 to encode attachments. Learn about MIME, Content-Transfer-Encoding, line wrapping rules, and the history of Base64 in email.
Detailed Explanation
Base64 encoding was originally popularized by email. The MIME (Multipurpose Internet Mail Extensions) standard, defined in RFC 2045 (1996), specified Base64 as the preferred method for encoding binary attachments in email messages, which must be transmitted as 7-bit ASCII text.
Why email needs Base64: Early email systems (SMTP) were designed to handle only 7-bit ASCII text. Binary files (images, documents, executables) contain bytes with values above 127, which would be corrupted by these systems. Base64 converts any binary data into safe ASCII characters.
MIME structure of an email with an attachment:
From: sender@example.com
To: recipient@example.com
Subject: Report attached
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="----=_Part_123"
------=_Part_123
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: 7bit
Please find the report attached.
------=_Part_123
Content-Type: application/pdf; name="report.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="report.pdf"
JVBERi0xLjQKJcOkw7zDtsOcCjEgMCBvYmoKPDwgL1R5cGUgL0Nh
dGFsb2cgL1BhZ2VzIDIgMCBSID4+CmVuZG9iago1IDAgb2JqCjw8
IC9MZW5ndGggNDQgPj4Kc3RyZWFtCkJUCi9GMSAxOCBUZgo1MCA3
...
------=_Part_123--
Key header: Content-Transfer-Encoding: base64 tells the email client that the following content is Base64-encoded and must be decoded before use.
Line wrapping rule: MIME requires Base64 output to be wrapped at 76 characters per line, with CRLF (\r\n) line endings. This is different from a continuous Base64 string. The 76-character limit was chosen to stay well within the SMTP line length limit of 998 characters and to be compatible with older systems that had even stricter limits.
Other Content-Transfer-Encoding options:
7bit: plain ASCII text, no encoding needed.quoted-printable: for mostly-ASCII text with occasional special characters. More readable than Base64 for text content.8bit: raw 8-bit data (not safe for all mail servers).binary: raw binary (almost never used in practice).
Base64 is the only option that safely handles arbitrary binary data across all email systems. While modern SMTP supports 8-bit content (via the 8BITMIME extension), Base64 remains the default for attachments because backward compatibility cannot be guaranteed across the entire email delivery chain.
Common mistake: Manually constructing MIME messages without proper line wrapping. Most Base64 libraries have a MIME-specific encoder that handles the 76-character wrapping automatically (Python's encodebytes(), Java's getMimeEncoder()).
Use Case
Building a transactional email service that programmatically attaches PDF invoices to confirmation emails, encoding each attachment as Base64 within the MIME structure.