Skip to main content

Overview

This guide shows how to forward incoming SMS messages to an email address using Node.js, Express, and Nodemailer. This is a great way to centralize communications and create a searchable archive.

Prerequisites


Create the email forwarding application

Create a file named smsemail.js. This code sets up an Express server that listens for incoming SMS webhooks from Plivo. When a message is received, it uses Nodemailer to send its contents to your email address.Replace all the placeholder values in the <...> brackets with your actual information.
const express = require('express');
const nodemailer = require("nodemailer");
const app = express();

app.use(express.urlencoded({ extended: true }));
app.set('port', (process.env.PORT || 5000));

app.all('/email_sms/', async (request, response) => {
    const from_number = request.body.From;
    const text = request.body.Text;
    console.log(`Message from: ${from_number}, Text: ${text}`);

    // Acknowledge the webhook from Plivo immediately
    response.status(204).send();

    const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: "<your_gmail_address>",
            pass: "<your_gmail_app_password>"
        }
    });

    const mailOptions = {
        from: "<your_from_email_address>", // e.g., [email protected]
        to: "<your_recipient_email_address>",
        subject: `New SMS from ${from_number}`,
        text: text
    };

    try {
        let info = await transporter.sendMail(mailOptions);
        console.log('Email sent: ' + info.response);
    } catch (error) {
        console.error('Error sending email:', error);
    }
});

app.listen(app.get('port'), () => {
    console.log('Node app is running on port', app.get('port'));
});

Create and configure a Plivo application

  1. Create an Application: Go to Messaging > Applications and click Add New Application.
  2. Configure the URL: Name the application (e.g., Forward SMS to Email). In the Message URL field, enter your ngrok URL (e.g., https://<yourdomain>.ngrok.io/email_sms/). Set the method to POST. Click Create Application.
  3. Assign a Number: Go to the Numbers page, select your number, and link it to the Forward SMS to Email application.

Test

Send an SMS to your Plivo number. The message content should arrive in your email inbox shortly.