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
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.
Accessing the HTML content
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
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
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
Next, reference the library in your code:
const { JSDOM } = require('jsdom')
Find the target element
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"