Mailosaur logo
Mailosaur logo

HTML content of an email

Learn how to work with the HTML content found within your emails.

HTML and text content within an email Most email sent today is HTML-based, however an email may also contain a plain text alternative for older mail clients. Learn how to work with text content of an email.

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.

Accessing the HTML content
A hashtag icon

An email’s HTML body can be accessed via the html.body property of a message.

console.log(message.html.body) // "<html><head ..."

Mailosaur also automatically extracts certain content for you, such as links and images.

Extracting from the HTML
A hashtag icon

You may wish to work with individual elements within your email’s HTML content. This is useful for extracting key pieces of data, such as account verification codes.

Install an HTML library
A hashtag icon

To extract content from the body of an email, you will need to use an HTML library in your tests. Each language has alternative libraries to those shown here, but this should get you started.

First, install a library for the language you are working with:

npm i -D jsdom
# or
yarn add -D jsdom

Import the library in your code
A hashtag icon

Next, reference the library in your code:

const { JSDOM } = require('jsdom')

Find the target element
A hashtag icon

In this example, we want to extract the verification code from the HTML below:

<div>
  <h1>To activate your account, enter this code:</h1>
  <p class="verify-code">542163</p>
</div>

To do this, we pass the email’s HTML body into our library, then find the element we need and access the 6-digit access code within:

const dom = new JSDOM(message.html.body);

const el = dom.window.document.querySelector('.verify-code');
const verificationCode = el.textContent;

console.log(verificationCode); // "542163"