Using Selenium To Test Account Email Signups

All the code shown in this article is published at

Selenium and Mailsac can be used to test the delivery and contents of a signup email sent by a web application.

This example will demonstrate how to configure Selenium and provide code examples to automate and integrate testing with Mailsac.

What is Selenium?

Selenium is an automation tool for testing website user interfaces. It is open-source and supports multiple programming languages such as Java, Python, Javascript etc.

Selenium is not a single tool but is composed a several tools. Our example will focus on the WebDriver component. This will allow us to test our application as if a real person were operating the web browser.


Installing Selenium

The Selenium WebDriver is installed during step 2 by running npm install.

  1. Clone the selenium-js-example repository and change directories to the cloned repository
    git clone && cd ./selenium-js-example
  2. Install the Selenium WebDriver by running npm install
  3. Download browser driver for the browser that will be tested (see table for download links).
  4. Place the browser driver in the system PATH
Internet ExplorerIEDriverServer.exe

The safaridriver is included with Safari 10 for OSX El Capitan and macOS Sierra. It does require Remote Automation in the Develop Menu to be enabled.

Configure the Browser for Selenium to Use

This example will default to using Firefox. In order to use a different browser set the SELENIUM_BROWSER environment variable.

List of supported SELENIUM_BROWSER values


Web Application Overview

The example web application consists of a single page with a form. The form accepts a username and email address.

Configuring the Web Application

Email will be sent using the Mailsac Outbound Message REST API. You will need to update mailsacAPIKey with your API keymailsacFromAddress is the address that this example will use are the from address.

const mailsacAPIKey = ""; // Generated by mailsac. See
const mailsacFromAddress = "";

Manual Test of Email Delivery

To manually test email delivery, launch the example web application by running npm start from the command line. Use a web browser to view http://localhost:3000/index.html

  1. Enter a username and email address.

2. If everything went well you should see a confirmation.

3. Check the inbox of Mailsac address you send to using the form on

4. Verify the message you sent has been received.

Automated Testing Using Selenium

To automate UI testing a few different components are required:

  • Selenium WebDriver: Automates input into our web application’s form
  • Mocha: Test framework to run the tests
  • HTTP Requests Module: To interact with the Mailsac API
  • Assert Module: Validates if a given expression is true
  • Webserver: Runs our web application

All of these components are installed when running npm install

Configure Mailsac API Key

To interact with the Mailsac API an API Key is needed. To generate a new API Key sign in to Mailsac and go to the API Keys Page.

An API Key is available for free to all registered users of Mailsac.

Configure the test to work with your API Key by adding it to the following line in ./test/test.js

const mailsacAPIKey = ""; // Generated by mailsac. See

Run the Test

Before running the tests your Mailsac API key needs to be configured in ./test/test.js and SMTP settings configured in app.js.

The tests can be executed by running npm test from the command line.

npm test

> selenium-tests@1.0.0 test /home/user/repos/selenium-js-example
> mocha

    register new user
(node:838754) [DEP0066] DeprecationWarning: OutgoingMessage.prototype._headers is deprecated
      ✓ sends email with link to website (1383ms)

  1 passing (1s)

The last line in the above code snippet 1 passing (1s) shows our test passed. If the test failed, an error message will be displayed.

If you are using a browser other than Firefox you will need to add an environment variable when running the tests (eg SELENIUM_BROWSER=chrome npm test).

Using Mocha and Selenium to Automate Tests

This section will cover how Mocha and Selenium work together in this code example to test email delivery.

The integration tests are located in ./test/test.js. The tests are written in Mocha, which uses a behavior driver development model. This allows for the description of tests in easy to understand language.

Mocha Test Introduction

In the following example, the describe block includes a description of what is being tested. The it block describes the expected result. assert is used to test the for truth. If the expected statement is not true, there will be an exception, and the test will fail.

describe("tests truth", () => {
    it('true equals true', function() {
        assert(true); // assert checks for truth
    it('false equals false', () => {
        // assert equal checks the first and second parameter are equal

Mocha and Selenium

This section is a line by line explanation of the Mocha tests in the example. The code example is available on GitHub.

Mocha is used to call the Selenium WebDriver to perform actions on the example Web Application. The describe block shows we are going to be testing the process of registering a new user. The it block tells us what we expect to happen.

Inside the it block Selenium WebDriver is instructed to:

  • open a web browser using the webapp’s localhost URL
  • find the html element with the id username and enter text in the field
  • find the html element with the id email and enter specified text in the field
  • find the html element with the id submitUserCreation and click on it
it("sends email with link to website", async () => {
  await driver.get(webappUrl);
  await driver.findElement("username")).sendKeys("webdriver", "ExampleUser");
  await driver.findElement("email")).sendKeys("webdriver", signupEmailAddress);
  await driver.findElement("submitUserCreation")).click();

Our webapp will then email the address submitted by Selenium.

There is a for loop, following the Selenium commands, that uses the Mailsac API to fetch the mail from the specified email address. If an email isn’t found, it will retry 10 times waiting about 5 seconds between tries.

let messages = [];
for (let i = 0; i < 10; i++) {
   // returns the JSON array of email message objects from mailsac.
   const res = await request("")
           .set("Mailsac-Key", mailsacAPIKey);
   messages = res.body;
   if (messages.length > 0) {
   await wait(4500);

If no messages are received from the Mailsac API after 10 tries, assert will create an exception and throw the error Never received messages!. The contents of the email are checked to see if the link is in the email. If, the link is not found, an exception is created stating Missing / Incorrect link in email

assert(messages.length, "Never received messages!");
const link = messages[0].links.find((l) => "");
assert(link, "Missing / Incorrect link in email");

Next Steps

This example can be modified to automate your team’s UI testing procedures. For another example of Mocha tests using Mailsac see the Integration Tests Blog Post.

Our forums are a great place to discuss usage of Mailsac’s API.

Github repository for all source code in this example:

Write Integration Tests Using Mailsac

Mailsac has a REST API that can be leveraged to validate emails are being received with the correct contents. This can be useful for web applications that send customized emails to customers.

This example will demonstrate how to send an email via an SMTP server and validate the email was received. The code used in this example is available on GitHub.

Setup Project Directory

Node version 12 or greater is required for this example due to the use of async and await.

Begin by creating a directory for the project.

mkdir mailsac-tests
cd mailsac-tests
npm init # enter project information, for test command use 'mocha'

Verify package.json looks something like this. The most important part is "scripts": { "test": "mocha" }

  "name": "mailsac-integration-tests",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "directories": {
    "test": "test"
  "scripts": {
    "test": "mocha"
  "author": "",
  "license": "ISC"

Installing a Test Framework

The test framework for this example is Mocha. It is a test framework for Javascript applications. A test framework will allow us to write tests against our code.

Setup Test Directory

These directions are inspired by the Mocha Getting Started Guide.

cd mailsac-tests
npm install --save-dev mocha
mkdir test
$EDITOR test/test.js # or open with your favorite editor

Write a Test to Test For Truth

This section is for people who are new to Mocha and test frameworks. Skip ahead if you know how to write tests.

Mocha follows a Behavior Driven Development (BDD) model of testing. This allows for human readable descriptions of software behavior. The first line of the code shows exactly what the following tests will test (ie describe("tests truth"). The following lines state the expected outcome of the test (ie it(true equals true).

This test uses Node’s built in assert. The first parameter passed to assert() is checked for true. If it is true, the assert passes. If the value is false, it throws an exception. In this example, we assert that true is true and that false is equal to false.

Create a describe block in test/test.js
describe("tests truth", () => {
    it('true equals true', function() {
        assert(true); // assert checks for truth
    it('false equals false', () => {
        // assert equal checks the first and second parameter are equal

This code can be run and the test should pass. Run the test with npm test . Confirm the test passed.

Congratulations! You have a working test.

Write an Integration Test

In this example, an email will be sent to Mailsac using the ubiquitous Javascript SMTP library NodeMailer, then the test framework will call Mailsac to validate that the email was received.

Install Dependencies

There are a few Node modules that will make sending an email and interacting with the Mailsac REST API easier. NodeMailer will be used to send the email via SMTP. SuperTest will be used to call the Mailsac API.

npm install

Integration Test Example

Back in the text editor, open / create the file test.js in the test folder. Copy and paste the following code or see GitHub for the complete example.

Import required modules
const assert = require("assert");
const nodemailer = require("nodemailer");
const request = require("supertest");
Configure SMTP settings and Mailsac Credentials
// Generated by mailsac. See
const mailsacAPIKey = "";
// Mailsac email address where the email will be sent
const mailsacToAddress = "";
// Username for smtp server authentication
const smtpUserName = "";
// Password for smtp server authentication
const smtpPassword = "";
// hostname of the smtp server
const smtpHost = "";
// port the smtp is listening on
const smtpPort = 587;
Create wait Function

The test will contact the Mailsac API multiple times while waiting for the email to arrive. This function will be used later in a for loop while waiting for the email to arrive.

const wait = (millis) => new Promise((resolve) => setTimeout(resolve, millis));
Add a Describe block with Timeout and Test Cleanup

The describe callback describes in human readable terms what the test is going to do. The increased timeout is required because the default timeout for Mocha is 2 seconds. The test email will likely not arrive that quickly. The afterEach section is used to delete all messages after the test runs. This prevents a leaky test.

describe("send email to mailsac", function () {
  this.timeout(50000); // test can take a long time to run. This increases the default timeout for mocha

  /* delete all messages in the inbox after the test runs to prevent leaky tests.
       This requires the inbox to private, which is a paid feature of Mailsac.
       The afterEach section could be omitted if using a public address
  afterEach(() =>
      .set("Mailsac-Key", mailsacAPIKey)
Add it block and NodeMailer Configuration

The it interface describes what the test will do "sends email with link to website“. The transport variable is used to store the configuration of the SMTP server.

result = await transport.sendMail({… Attempts to send the email and capture the result.

describe("send email to mailsac", function () {

  it("sends email with link to website", async () => {
    // create a transporter object using the default SMTP transport
    const transport = nodemailer.createTransport({
      host: smtpHost,
      port: smtpPort,
      auth: {
        user: smtpUserName,
        pass: smtpPassword,
    // send mail using the defined transport object
    const result = await transport.sendMail({
      from: smtpUserName, // sender address
      to: mailsacToAddress, // recipient address
      subject: "Hello!",
      text: "Check out",
      html: "Check out <a href>My website</a>",

    // logs the messageId of the email, confirming the
    // email was submitted to the smtp server
    console.log("Sent email with messageId: ", result.messageId);
Add Loop to Check Mail

This section of code uses a for loop and a http library (supertest) to check if the message has arrived at Mailsac. The test uses the Mailsac API endpoint /api/addresses/{email}/messages which lists all messages in an inbox.

describe("send email to mailsac", function () {

  it("sends email with link to website", async () => {
    // Check email in the inbox 10x, waiting 5 secs in between. Once we find mail, abort the loop.
    let messages = [];
    for (let i = 0; i < 10; i++) {
      // returns the JSON array of email message objects from mailsac.
      const res = await request("")
        .set("Mailsac-Key", mailsacAPIKey);

      messages = res.body;
      if (messages.length > 0) {
      await wait(4500);
Add Assertion to Check for Link in the Message

assert is used twice. First, to check to see if any messages were fetched from the Mailsac inbox. This checks the length of the messages array to see if any messages were received. The second assert is used to check for a link to .

describe("send email to mailsac", function () {
  // ...
  it("sends email with link to website", async () => {
    // ...
    let messages = [];
    for (let i = 0; i < 10; i++) {
      // ... await get messages from mailsac
    assert(messages.length, "Never received messages!");

    // After a message is retrieved from mailsac, the JSON object is checked to see if the link was parsed from the email and it is the correct link
    const link = messages[0].links.find((l) => "");
    assert(link, "Missing / Incorrect link in email");
Run Test

At this point the test code is complete and can be run using npm test. If all went well the following output is written to the console.

npm test

Run Test Using GitHub Repository

If you are having some trouble with the tests, I recommend downloading the code from GitHub and running it.

git clone
cd mailsac-integration-test-examples
npm install
$EDITOR test/test.js # or open with your favorite editor

Edit the test.js and fill in your SMTP settings and Mailsac API key

const mailsacAPIKey = ""; // Generated by mailsac. See
const mailsacToAddress = ""; // Mailsac email address where the email will be sent
const smtpUserName = ""; // Username for smtp server authentication
const smtpPassword = ""; // Password for smtp server authentication
const smtpHost = ""; // hostname of the smtp server
const smtpPort = 587; // port the smtp is listening on

Run test running the command npm test in your terminal.

Next Steps

The example above can be used as part of your team’s quality assurance process. A real world example would be validating password reset links to customers. This test could be used to validate that when a customer requests a password reset an email is sent to them containing the correct password reset link.

If you have any questions about this example or want to talk about other implementations reach out to our community at .

Multi-User Login using API Credentials, For Team Collaboration

Update: April 2021 – Multi-User login is now called “Sub-Accounts”

Named API Keys can now be used as website authentication.

Custom domains and Private Addresses have been great for quality assurance teams to conduct end to end automated testing of email. But sometimes interacting with an REST API can be a lot of overhead for non-repeating tasks. API Credentials can now be used to login to the website.

All private addresses and custom domains associated with the primary account will be visible from the website for API users. The permissions for API users are the same as API keys.

Quality assurance teams often share credentials of test accounts for the web application they are testing. These test accounts might to be associated with an email provisioned by their IT department or the QA tester’s personal email. Mailsac private domains allow the test accounts to be created in an an environment all members of the QA team have access to.

This feature allows teams to work together in the Mailsac platform. There is no longer a need to for each person to have their own Mailsac account. A named API Key can be created for each person. That API key can be used to interact with the REST API and the website. As a result, password resets and transaction emails sent to a Mailsac private domain can be accessed by any member of the QA team.

“Internally we have used Mailsac for collaboration. Being able to share a private address or domain allows my team members to see exactly what I am seeing. This feature allows our customers to do the same with their own private domains and addresses” Michael Mayer – Member – Forking Software LLC

Getting started is as easy as provisioning a new set of API credentials and enabling the website login on the API Key. This can be done the the Dashboard and selecting API Credentials & Users

Enable Website Login

We will be rolling this feature out to our Business and Enterprise Plans in the next couple weeks. If you have an immediate need for this feature we can enable it on your account. Contact to get early access to this feature on you Business or Enterprise Plan.

Using Mailsac for Shared QA Email Accounts

When building software-as-a-service, several pre-production environments are often in play.

Developers, product managers, and QA engineers work together to test software in the various environments.

But there’s confusion around which user accounts can be used in which environments. Which accounts have the right permissions for testing. And your test environments environments don’t map 1:1 with 3rd party services. It’s confusing to know if you tested the right thing.

Mailsac lets you create disposable email accounts within a private custom. Temp email addresses to share with the team. This results in less effort keeping testing environment accounts separate. It prevents user collisions with third party providers.

Common Environment Setup Example

A QA team may have a test environment called “UAT” and developers have a different test environment called “Staging.”

The infrastructure might map to URLs with different subdomains like:

  • – QA team
  • – Developers
  • – Production (customers)

where each subdomain has a completely separate database with a users table.

However, our sample app uses a 3rd identity provider (such as Amazon Cognito, Forgerock, Auth0, etc). The identity provider only has two environments:

  • – All non-production usage (UAT, Staging)
  • – Production (customers)

Furthermore, our app uses Stripe, which also has only two environments:

  • Stripe Test Mode – All non-production usage (UAT, Staging)
  • Production Mode – Production (customers)

One can imagine a users database table with the following properties:

  • int, primary
  • text, unique
  • users.identity_provider_id text, unique, corresponds to the Identity Provider
  • users.stripe_customer_id text, unique, corresponds to the Stripe Customer ID

Such a setup is common. Problems begin brewing when using the same email address in multiple environments.

Password issues with shared email addresses

A QA person wants to test their app. They sign up with in UAT. was created by a friendly sysadmin at their company. It is a real email inbox. The company has to pay a few bucks per month for the inbox, and it isn’t easily accessible by anybody else. Where’s that password again? Oh you asked Dave from IT to reset the email password? Oh you mean the UAT app password was changed only? The new password should be in a spreadsheet..oops somebody reset it and didn’t update the password? It doesn’t look like I have access to the inbox. Wait a second..the Dev team is also using it?

Identity Provider Clash, Stripe duplicate

UAT person uses and creates the user account with the Identity Provider, linking the identity_provider_id to their user in UAT. They also link the Stripe customer.

UAT users table

But then a developer in Staging attempts to perform the action but gets blocked by the identity provider, and duplicates the customer in Stripe with the same email address, making the tracking of financial transactions overly complicated. UAT and Stating also end up with a different user id.

19alice@example.comNULL (failed)cus_yb1
Staging users table

It is possible the same password is used for with the identity provider, and both UAT and Development are able to login. But the identity_provider_id will need to be manually set to match both environments, and it will never match the column.

Let’s add one more common layer: role based permissions.

Developer 1 sets up to

These are just a few of the problems with using a limited number of shared credentials for testing software.

Using Mailsac for Test User Accounts

A software team and QA team can share the Mailsac Business account to add nearly unlimited email addresses, and apply special features to up to 50 private address across 5 custom domains (and more via addons). Mailsac allows any custom subdomain of *, it may not even be necessary to involve an IT department to configure DNS.

QA team sets up

The QA team will create 10 private addresses with specific purposes such as a user they will configure in with elevated admin permissions:

Next the Dev team, can do something similar but with a different custom domain, and different private email addresses.

Setting up a bunch of private addresses is simple and included with any paid plan. It can help prevent test credential collisions.

Random Inboxes and API Keys

It is not even necessary to setup private addresses, as done above, to receive email.

With a custom domain, any Developer or QA person can send email to any address in the domain without needing to create it first. Then they can check the mail with a personal API key.

The Business Plan allows creating multiple custom API keys:

API Key management in Mailsac

To make a random address, generate a random string:

openssl rand -hex 4 yields de692e19 (for example)

and prefix it to your custom domain:

Assume Greg’s API key is: wv6OCCXE4svjxuv7sOsCBA (note: never share these!)

He can easily check the inbox using the following URL scheme:

Or get messages as JSON:

curl --header 'Mailsac-Key: wv6OCCXE4svjxuv7sOsCBA'

which returns an array of messages including any links to be clicked.

  "_id": "m77238f-0",
  "inbox": "",
  "subject": "Confirm your account or something",
  "links": [""]

Concluding remarks

We hope this guide provides an overview of how software teams are using Mailsac to simplify testing.

Thousands of enterprises and software project teams use Mailsac to test their environments and manage “known good” test accounts for their SaaS.

Start for free instantly