How To Add Web3 Messaging into My App (for Devs)

January 4, 2023
For Developers

This tutorial shows you how to integrate an API that you can use to send messages from your app to any EVM-compatible blockchain address, ENS name or Unstoppable domain.

Why might you want to do this?

  • Because projects can’t communicate directly with their users, and users can’t communicate with each other.
  • Collectors can’t message NFT owners to discuss trades, DAOs can’t privately message members, and projects can’t send updates.
  • Integrating Web3-native messaging allows you and your users to send private messages to each other using wallet addresses or ENS/Unstoppable Domains.

Solution Overview

Through a practical example, you’ll learn how to build an Express App that exposes an API you can use to send messages with Mailchain.

Your app will use the Mailchain SDK that handles signatures, encryption, and sending the message. In most cases, you would add a route to an existing Express App, but for this tutorial, you'll create a new app.

For more detailed instructions see the written tutorial here. You can find the final code and working example in mailchain/examples-js on GitHub.

Video walkthrough:

Or continue with text:


Step 1: New API server: You’ll create a new Express app that exposes an API.

Step 2: Mailchain SDK: You’ll install and configure the Mailchain SDK which handles all the sending and encryption.

Step 3: ‘Send’ service: Express uses services to perform tasks. You’ll create a service for sending mail using the Mailchain SDK.

Step 4: Mail controller: Controllers manage HTTP requests and send the necessary data to the correct service. You’ll create a Mail controller to manage the HTTP request and response.

Step 5: Wire up the API: You’ll create an additional MailRoute and add it to the server.

Step 6: Test: You’ll send a message from your app to your Mailchain account.


To complete this example, you need to first:

  1. Download and install NodeJS.
  2. Install npx by running npm install -g npx.
  3. Create new Mailchain account for development and testing purposes.

Step 1 - New API server

The simplest way to create a new Express app that exposes an API is with a generator that creates an Express App structure. There are various express generators, for this tutorial you'll use typescript-express-starter.

To begin, open a terminal window on your computer and run:

npx typescript-express-starter@9.2.0 mailchain-send-api

Select the following responses: default;  n; y (as shown below)

Your Express App is now created.

Open mailchain-send-api in your favorite code editor. You'll see it contains example services, controllers, routes, etc.

Step 2 - Mailchain SDK

The Mailchain SDK is the easiest way to use Mailchain, it deals with all of the encryption, signatures, and hashing for you.

2.1 Install

To install the Mailchain SDK you need to run an npm command in the base directory of your project mailchain-send-api. If you are following Step 1, you should already be in this folder. Otherwise, open up a terminal window and navigate to your mailchain-send-api folder.

Install Mailchain SDK using npm:

npm install --save @mailchain/sdk

You have now installed the Mailchain SDK and are ready to configure it.

2.2 Configure

The Mailchain SDK needs to be authenticated with your Secret Recovery Phrase to send messages. We are assuming you are developing on a local machine and it is secure.

WARNING: Secret Recovery Phrase

Whoever has the Secret Recovery Phrase controls the Mailchain account. Secret Recovery Phrases MUST be kept safely and only saved in a trusted store. We suggest for this tutorial that you use a Secret Recovery Phrase from a test account. Go ahead and create a new account if you don't already have one.

Get the Secret Recovery Phrase for your test development account (see WARNING). Open .env.development.local in your editor, and add a new line to the bottom

SECRET_RECOVERY_PHRASE=enter your secret phrase here

Replace enter your secret phrase here with your Secret Recovery Phrase and save the file.

In your terminal window run, npm run dev from the root directory of your mailchain-send-api app. You should get a response to say the app successfully started, e.g. App is listening on port 3000.

Step 3 - ‘Send’ Service

The service (MailService) will:

  1. Authenticate the Mailchain SDK using the SECRET_RECOVERY_PHRASE.
  2. Send mail from address to the Mailchain account associated with the SECRET_RECOVERY_PHRASE using the Mailchain SDK.

Inside src/services/ create mail.service.ts and copy the code below into it.

import { Mailchain, SendMailParams, SendMailResult } from '@mailchain/sdk'; class MailService { async send(params: SendMailParams): Promise { // use the environment variable to provide your secret recovery phrase const secretRecoveryPhrase = process.env.SECRET_RECOVERY_PHRASE; if (secretRecoveryPhrase == null) { throw new Error('You must provide a secret recovery phrase'); } const mailchain = Mailchain.fromSecretRecoveryPhrase(secretRecoveryPhrase); if (!params.from || params.from === '') { // set the from address to current user if not provided const currentUser = await mailchain.user(); params.from = currentUser.address; } return await mailchain.sendMail(params); } } export default MailService;

Step 4 - Mail controller

MailController will perform the following actions:

  1. Pass the HTTP request body to the send service.
  2. Set the HTTP response status field using the SDK response.

In your editor create mail.controller.ts in the src/controllers/ folder.

Copy and paste the code below into it.

import { NextFunction, Request, Response } from 'express'; import mailService from '@services/mail.service'; class MailController { public mailService = new mailService(); public postMail = async (req: Request, res: Response, next: NextFunction): Promise => { try { const sendResult = await this.mailService.send(req.body); res.status(200).json({ status: sendResult.status }); } catch (error) { next(error); } }; } export default MailController;

Step 5 - Wire up API

5.1 Add mail route

The API is called by clients using HTTP. You'll create an additional route that accepts mail parameters. The route will use the sendMail function you created in Step 3.

MailRoute performs the following actions:

  1. Adds the send path.
  2. Listens for a POST.
  3. Route request to the mail controller.

In your editor create mail.route.ts in the src/routes/ folder. Copy and paste the code below into it.

import { Router } from 'express'; import { Routes } from '@interfaces/routes.interface'; import MailController from '@/controllers/mail.controller'; class MailRoute implements Routes { public path = '/send'; public router = Router(); private mailController: MailController; constructor() { this.mailController = new MailController(); this.initializeRoutes(); } private initializeRoutes() {`${this.path}`, this.mailController.postMail); } } export default MailRoute;

5.2 Add to server

Now MailRoute has been created, the final code change is to add MailRoute to the server.

In your editor open the existing server.ts file in the src/ folder.

Replace the existing contents by copying and pasting the code below into it.

import App from '@/app'; import IndexRoute from '@routes/index.route'; import MailRoute from './routes/mail.route'; const app = new App([new IndexRoute(), new MailRoute()]); app.listen();

Now your app is ready to start accepting HTTP requests.

6. Test your API using CURL

Now you have API that can send messages. You can test this by sending a sample request via HTTP.

Open a new terminal window, and paste the following curl command into a terminal window.

curl http://localhost:3000/send -i -X POST \ -H 'Content-Type: application/json' \ -d '{"to": [""], "subject": "Sent via curl", "content": {"text": "Hello Mailchain 👋", "html": "

Hello Mailchain 👋


You should get a {"status": "success"} response.

You can check the message has been sent by looking in the sent folder in the Mailchain web app.

Want to try more? Edit the curl command above and give these go:

  • Send a message to your Mailchain account. Change the to address "<username>". Check your inbox and you'll see your message. ✅
  • Do you want to send mail to an Ethereum address? Register your Ethereum address in the Mailchain application. Then send a message to <ethereum-address> ✅

Congratulations 🎉 you have built an App that exposes an API. You can use this API to send messages from other services and apps, for example messaging your users about exciting updates.

Email that's built for Web3.
Send. Receive. Own.

Claim your Web3 Inbox