# Fetching email content
TIP
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.
# 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.
const email = await mailslurp.getEmail(emailId);
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"><<a href="mailto:uber.deutschland@uber.com">uber.deutschland@uber.com</a>></span><br>Date: Wed, 11 Mar 2020 at 20:11<br>Subject: Your Wednesday evening trip with Uber<br>To: <<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:
// example using mailslurp-client for Node and Jest
it("can extract text lines", async () => {
jest.setTimeout(60000)
const inbox1 = await inboxController.createInbox({})
await inboxController.sendEmailAndConfirm({
inboxId: inbox1.id,
sendEmailOptions: {
to: [inbox1.emailAddress],
body: `Dear user,\n\nHere is a multiline email.\nThanks`,
}
});
const email = await waitController.waitForLatestEmail({
inboxId: inbox1.id,
timeout: 60000,
unreadOnly: true
});
const linesResult = await 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.
it("can extract html and lines", async () => {
jest.setTimeout(60000)
const inbox1 = await inboxController.createInbox({})
await inboxController.sendEmailAndConfirm({
inboxId: inbox1.id,
sendEmailOptions: {
to: [inbox1.emailAddress],
body: '<p>Hello <span class="name">Bob</span> you have mail</p>',
isHTML: true
}
});
const email = await waitController.waitForLatestEmail({
inboxId: inbox1.id,
timeout: 60000,
unreadOnly: true
});
const htmlResult = await 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 (opens new window).
# Attachments
When you fetch an email its attachments are given as a list of attachment IDs.
{
"id": "",
"attachments": ["0192", "1728"]
}
# Get attachment meta data
To get the name, content type, and size of attachments use the getAttachmentMetaData
methods.
const {
contentType,
contentLength,
name,
} = await mailslurp.getAttachmentMetaData(attachmentId, emailId);
# Get attachment content
To download or fetch the attachment as a byte stream use the downloadAttachment
methods.
const bytes = await mailslurp.downloadAttachment(attachmentId, emailId);
Sometimes it is better to download content in base64 encoded format. Use the alternative download method like so:
const attachmentDto = await mailslurp.emailController.downloadAttachmentBase64(email.attachments[0], email.id)
expect(attachmentDto.base64FileContents).toBeTruthy()
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');
expect(pathToAttachment).toBeTruthy();
// 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 attachmentController = new MailSlurp(config).attachmentController;
return attachmentController.uploadAttachment({
base64Contents: fileBase64Encoded,
contentType: 'text/plain',
filename: basename(pathToAttachment)
})
# Previewing attachments
You can also use the dashboard to view and download attachments manually.
# Raw message
You can retrieve the raw SMTP message for an email by using the raw endpoints with an email ID.
await mailslurp.getRawEmail(emailId);
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 (opens new window) to preview HTML emails and attachments visually.
# 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 (opens new window) 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.
# 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.