Mailosaur logo
Mailosaur logo

Email attachments

Learn how to test the email attachments with Mailosaur.

Before you begin
A hashtag icon

The examples shown below are based on two key assumptions:

  1. That you have already create a basic automated test using our getting started guides.
  2. You have a chosen assertion library that you will use to test the values shown below.

How many attachments
A hashtag icon

The attachments property of a message contains an array of attachments. The length of this array corresponds to the number of files attached to the email.

console.log(message.attachments.length) // 2

Testing the file name and content type
A hashtag icon

Each attachment contains metadata on the file name and content type.

const firstAttachment = message.attachments[0]
console.log(firstAttachment.fileName) // "contract.pdf"
console.log(firstAttachment.contentType) // "application/pdf"

Testing attachment file size
A hashtag icon

The length property returns the size of the attached file (in bytes).

const firstAttachment = message.attachments[0]
console.log(firstAttachment.length) // 4028

Embedded Images
A hashtag icon

If an email contains embedded images then the contentId attribute will be populated and will have a corresponding entry in the images array.

const firstAttachment = message.attachments[0]
console.log(firstAttachment.contentId) // "ii_1435fadb31d523f6"

Fetching an attachment as base64
A hashtag icon

You can fetch the content of an attachment, encoded as base64, using the “get attachment” method:

const firstAttachment = message.attachments[0]
const file = await mailosaur.files.getAttachment(firstAttachment.id)
const base64 = file.toString('base64')
console.log(base64)

Saving an attachment to disk
A hashtag icon

You can also write an attached file to disk:

const firstAttachment = message.attachments[0]
const file = await mailosaur.files.getAttachment(firstAttachment.id)
fs.writeFileSync(firstAttachment.fileName, file)