Email API Send Attachments

How to send email attachments using MailSlurp API.

Sending email attachments

Even though attachments are an incredibly common aspect of email, SMTP, the underlying protocol, doesn’t actually specify what one is or how it should be transferred. Attachments weren’t really a thing when email was invented. However, the designers left room for extension with the concept of MIME Parts.

SMTP MIME extension

Attachments that your receive in Gmail or Outlook are actually transferred as ASCII text using an encoding called MIME. MIME splits binary content into multiple packets of ASCII and demarcates each part with a boundary. It looks a little bit like this:

--abc123boundary text
Content-Type: text/plain;
Content-Disposition: attachment;
        filename="test.txt"

attachment text here

--abc123boundary text--

The email client then joins these together to give you a complete, readable file. It’s really rather clever but can be a real pain for developers and software engineers.

Why is it so hard?

MIME Parts are difficult to get right because they require a developer to break a file up into many pieces, encode them in ASCII, and then place them in an SMTP message in the correct way. For most developers an easier solution is desired.

Email APIs

Email APIs like MailSlurp let developers send and receive email attachments easily without MIME extensions. They abstract away file encodings and SMTP restriction in favour of a familiar REST API that handles file upload and attachment.

What does it look like?

Sending email attachments in code is easy with an email API like MailSlurp. First you upload the file to an attachment endpoint:

const [id] = await mailslurp.uploadAttachment({
    base64Contents: 'base64-encoded-file-contents',
    contentType: "optional/content-type",
    filename: "optional-filename"
})

Then you can use the same attachment any time you send an email and MailSlurp will automatically break it into MIME pieces and append it to the SMTP message for you.

mailslurp.sendEmail(inbox.id, { 
  to: ['recipient@domain.com'],
  subject: 'Your document',
  attachments: [id]
})

How to send attachments with email APIs today

Sign up for MailSlurp - it’s free for personal use. You can get an API Key and start sending email attachments from code or tests easily.