How to send an email with attachments using SMTP

更新时间:
复制 MD 格式

Send email attachments over SMTP by structuring your message in Multipurpose Internet Mail Extensions (MIME) format.

Sending attachments over SMTP requires the email body to follow the MIME format. MIME defines how to package multiple content parts—body text, images, files—into a single email message that any standard mail client can parse.

MIME basics

  • MIME is an Internet standard that extends the format of email messages.

  • For more information, see RFC 2045.

How attachments are encoded

Email protocols transmit text, not binary data. To carry binary files, MIME uses Base64 encoding to convert raw bytes into a safe ASCII representation. This adds roughly 33–37% to the original file size, so a 10 MB file becomes approximately 13–14 MB after encoding.

A MIME message with attachments uses multipart/mixed as the top-level content type. Each part is separated by a unique boundary string and carries its own headers. An attachment part must include:

Header

Description

Example

Content-Type

The file's MIME type and filename

application/pdf; name="report.pdf"

Content-Disposition

Set to attachment so the client saves the file rather than displaying it inline

attachment

Content-Transfer-Encoding

Set to base64 for file attachments

base64

The following example shows a minimal complete MIME message with one attachment:

From: sender@example.com
To: recipient@example.com
Subject: Monthly report
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="boundary123"

--boundary123
Content-Type: text/plain; charset="UTF-8"

Please find this month's report attached.

--boundary123
Content-Type: application/pdf; name="report.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="report.pdf"

JVBERi0xLjQKJ...
--boundary123--

If this structure is malformed—for example, a missing boundary or incorrect header—email clients may display corrupted files or silently drop attachments.

Note

The total size of an email with attachments cannot exceed 15 MB. An email can contain a maximum of 100 attachments.

The 15 MB limit applies to the total size of the sent email, which includes the email header, email body, and attachments. Because Base64 encoding increases the file size, the final email can be more than 1.5 times the size of the original attachments. Therefore, keep the total size of your original attachment files to 8 MB or less. To send larger files, add hyperlinks to them in the email body.

Code examples

The following pages provide working SMTP code examples in several languages. Each example constructs a multipart/mixed MIME message and sends it over SMTP.

For sample code, see:

SMTP call example for Java

SMTP call example for Python 3.6 or later

SMTP call example for C#

SMTP call example for PHP

SMTP call example for Node.js