Fetching email content

Some email receiving methods return lists of email previews. This is to keep response sizes low. To receive full messages use the email ID with getEmail methods.

MailSlurp inboxes can receive email and attachments. They listen for emails all the time and you can access them when you wish using getEmail methods. You can also wait for emails to arrive during tests

Parsed email object

When MailSlurp receives email it parses the SMTP message and extracts useful data. To fetch an email and its body use the getEmail method.

_log
  console.log(emails);
  // [ { id: '', to: [], subject: '', ...etc } ]
  

The response is something like as follows:

{
  "id": "",
  "inboxId": "",
  "subject": "",
  "to": [""],
  "from": "",
  "cc": [],
  "bcc": [],
  "body": "",
  "attachments": [],
  "analysis": {},
  "headers": {},
  "createdAt": "",
  "html": true
}

Email body

The body of the email is parsed in the detected character set and made available as a string. A message body may look like this:

"<div dir="ltr"><br><br><div class="gmail_quote"><div dir="ltr" class="gmail_attr">---------- Forwarded message ---------<br>From: <b class="gmail_sendername" dir="auto">Uber Receipts</b> <span dir="auto">&lt;<a href="mailto:uber.deutschland@uber.com">uber.deutschland@uber.com</a>&gt;</span><br>Date: Wed, 11 Mar 2020 at 20:11<br>Subject: Your Wednesday evening trip with Uber<br>To:  &lt;<a ..."

Query email content

Given a known email ID you can fetch the email content in various others ways.

Fetch body

Fetch the raw body using the getEmail method.

const { body } = await mailslurp.getEmail(email.id!!);

Get lines of text in email

If you wish to parse the email content and return an array of text use the following methods:

await mailslurp.inboxController.sendEmailAndConfirm({
  inboxId: inbox.id!,
  sendEmailOptions: {
    to: [inbox.emailAddress!],
    body: 'Dear user,\n\nHere is a multiline email.\nThanks',
  },
});
const email = await mailslurp.waitController.waitForLatestEmail({
  inboxId: inbox.id,
  timeout: 60000,
  unreadOnly: true,
});
const linesResult = await mailslurp.emailController.getEmailTextLines({
  emailId: email.id!,
  decodeHtmlEntities: true,
});
expect(linesResult.lines).toEqual([
  'Dear user,',
  'Here is a multiline email.',
  'Thanks',
]);

Query email HTML content

You can also query HTML content using common CSS selectors.

await mailslurp.inboxController.sendEmailAndConfirm({
  inboxId: inbox.id!,
  sendEmailOptions: {
    to: [inbox.emailAddress!],
    body: '<p>Hello <span class="name">Bob</span> you have mail</p>',
    isHTML: true,
  },
});
const email = await mailslurp.waitController.waitForLatestEmail({
  inboxId: inbox.id,
  timeout: 60000,
  unreadOnly: true,
});
const htmlResult = await mailslurp.emailController.getEmailHTMLQuery({
  emailId: email.id!,
  htmlSelector: '.name',
});
expect(htmlResult).toEqual({
  body: '<p>Hello <span class="name">Bob</span> you have mail</p>',
  // the matches for .name selector
  lines: ['Bob'],
});

Headers

The headers property contains every SMTP header associated with the email. For a list of common headers are their meanings see the ietf specification.

Attachments

When you fetch an email its attachments are given as a list of attachment IDs.

{
  "id": "",
  "attachments": ["0192", "1728"]
}

Attachment IDs can be used with attachment methods to get attachment metadata or download contents. Remember, to send attachments, use the upload methods with base64 encoded file contents:

const attachmentContent = 'test';
const base64Contents = Buffer.from(attachmentContent).toString('base64');
// notice array is returned and first element is attachment id
const [attachmentId] = await mailslurp.uploadAttachment({
  base64Contents,
  contentType: 'text/plain',
  filename: 'test.txt',
});

Get attachment meta data

To get the name, content type, and size of attachments use the getAttachmentMetaData methods.

const { contentType, contentLength, name } =
  await mailslurp.attachmentController.getAttachmentInfo({ attachmentId });

Get attachment content

To download or fetch the attachment as a byte stream use the downloadAttachmentAsBytes methods.

await mailslurp.attachmentController.downloadAttachmentAsBytes({
  attachmentId,
});

Sometimes it is better to download content in base64 encoded format. Use the alternative download method like so:

const attachmentDto =
  await mailslurp.attachmentController.downloadAttachmentAsBase64Encoded({
    attachmentId,
  });
expect(attachmentDto.base64FileContents).toBeTruthy();
const content = new Buffer(
  attachmentDto.base64FileContents!,
  'base64'
).toString('utf-8');
expect(content).toContain('test content');
// access the base64 content
expect(attachmentDto.sizeBytes).toBeTruthy();
expect(attachmentDto.contentType).toBeTruthy();

See the developer documentation for more information on attachments.

Sending attachments

To send attachments first use the AttachmentController upload methods to upload a file with a name and content type. Use the returned attachment ID in subsequent sendEmail calls to attach the file.

You can upload attachments as byte streams or base64 encoded strings. In a node environment the latter is recommended:

const { basename } = require('path');
const { readFile } = require('fs/promises');
const { MailSlurp } = require('mailslurp-client');

// read the file with base64 encoding flag so it is base64 encoded
const fileBase64Encoded = await readFile(pathToAttachment, {
  encoding: 'base64',
});

// upload the attachment and include a content-type and filename
const mailslurp = new MailSlurp(config);

const [attachmentId] = await mailslurp.uploadAttachment({
  base64Contents: fileBase64Encoded,
  contentType: 'text/plain',
  filename: basename(pathToAttachment),
});

// send attachment by including attachment id
const sent = await mailslurp.sendEmail(inboxId, {
  to: [emailAddress],
  attachments: [attachmentId],
  subject: 'test',
});
expect(sent.attachments).toHaveLength(1);

Previewing attachments

You can also use the dashboard to view and download attachments manually.

attachments

Raw message

You can retrieve the raw SMTP message for an email by using the raw endpoints with an email ID.

const { id: emailId } = await mailslurp.waitForLatestEmail(inboxId);
const rawEmail: string = await mailslurp.getRawEmail(emailId);
expect(rawEmail).toContain('Subject: test');

Raw emails use content boundaries and look a bit like this:

Content-Type: multipart/alternative; boundary="0000000000009ff26c05a0bd68ac"

--0000000000009ff26c05a0bd68ac
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable

---------- Forwarded message ---------
From: Uber Receipts <uber.deutschland@uber.com>

HTML preview

You can use the dashboard to preview HTML emails and attachments visually.

inbox

Special characters

SMTP mail servers can sometimes use arcane encodings for special characters (quoted-printable format for instance). MailSlurp attempts to decode these entities but cannot always do so.

When testing with MailSlurp it helps to view the message bodies in the dashboard or by logging the results. This way you can ensure that expected characters are present in unencoded or decoded form and write code accordingly.

See quoted-printable article for more information.

Validations

MailSlurp performs validations on emails so you can check their validity. These include spam anaylsis and HTML validation.

Spam ratings

MailSlurp analyzes emails to estimate spam detection likelihood and virus verdicts. It also validates SMTP headers for SPF, DKIM, and DMARC validity.

analysis

HTML validation

For HTML emails MailSlurp can validate HTML for symantically correct markup. The results can be viewed in the dashboard:

Sending emails

Now we know what an email looks like let’s send one.

Next page