Receive Mail Using a WebSocket

Receiving mail from a Websocket allows for interacting with incoming email in near real time.

Web sockets are a powerful tool allowing you to end-to-end test your application’s email delivery systems, or respond to incoming mail in sophisticated ways - without having to setup a mail server or mess around with SMTP code.


Create directory for example code
$ mkdir websocket-example
$ cd websocket-example
Create package.json file with the following contents
  "name": "mailsac-node-websocket-example",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "ws": "^2.2.3"
Create example.js file with the following contents
const WebSocket = require('ws');
const log = console.log; // eslint-disable-line

// Mailsac uses secure web sockets. This is the web socket API base endpoint.
const BASE_URL = 'wss://';

// In this example, we pull the username and API key from environment variables.
// You could also hardcode the credentials, or use a package like node-config for managing them.
const username = process.env.MAILSAC_USER;
const apiKey = process.env.MAILSAC_KEY;
// List the addresses you want to receive messages for.
// You MUST have web socket forwarding turned on for the addresses!
const listenAddresses = process.env.ADDRESSES;

const urlParams = '?_id=' + username + '&key=' +apiKey+ '&addresses=' + listenAddresses;

log('attempting to open web socket to', BASE_URL + urlParams);
const ws = new WebSocket(BASE_URL + urlParams);

ws.on('open', function () {
  log('web socket opened');

ws.on('error', function (err) {
  log('connection error', err);

ws.on('message', function (data) {
Install required node packages
npm install
Set environmental variables
export MAILSAC_USER='your mailsac username / _id';
export MAILSAC_KEY='your mailsac api key';
export ADDRESSES='[email protected],[email protected]'

Launch WebSocket Example

Launch the node program
node example.js
Expected output
attempting to open web socket to wss://[email protected]
web socket opened
{"status":200,"msg":"Listening","addresses":["[email protected]"]}


Now, when an email messages are delivered to, they will also be sent to your web socket. Try sending a message - it will be parsed into JSON and dumped to your console.