Before you begin
The examples shown below are based on two key assumptions:
- That you have already create a basic automated test using our getting started guides.
- You have a chosen assertion library that you will use to test the values shown below.
How many attachments
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
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
The length
property returns the size of the attached file (in bytes).
const firstAttachment = message.attachments[0]
console.log(firstAttachment.length) // 4028
Embedded Images
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.fileName) // "contract.pdf"
console.log(firstAttachment.contentType) // "application/pdf"
Testing attachment file size
The length
property returns the size of the attached file (in bytes).
const firstAttachment = message.attachments[0]
console.log(firstAttachment.contentId) // "ii_1435fadb31d523f6"
Fetching an attachment as base64
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
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)
See also
Previous
Extracting codes from email and SMS