AWS-SNS-SMS with NodeJS

A quick example of sending an SMS with AWS SNS and NodeJS

Download this repository

git clone https://github.com/Sean-Bradley/AWS-SNS-SMS-with-NodeJS.git

$ cd AWS-SNS-SMS-with-NodeJS

$ npm install

Create a specific AWS IAM user and add to group ‘AmazonSNSFullAccess’

Rename the .env.example file to .env and enter your correct AWS access key, secret and region.

$ npm start

Open browser and visit something like,

http://localhost:3000/?message=[The Message]&number=[The Number]&subject=[The Subject]

The mobile number should be E.164 format but without the + character.

eg,

You want to send a message to a number,

The country code is 44

The mobile number is (0)7700 900123

The E.164 format would be +447700900123

Remove the + character

Then Visit

http://localhost:3000/?message=my message&number=447700900123&subject=My Subject

Video Tutorial how to install and setup the SMS API

Create an SMS API in 5 minutes with AWS SNS and NodeJS

2. the app.js file


const express = require('express');
const app = express();
require('dotenv').config();

var AWS = require('aws-sdk');

app.get('/', (req, res) => {

    console.log("Message = " + req.query.message);
    console.log("Number = " + req.query.number);
    console.log("Subject = " + req.query.subject);
    var params = {
        Message: req.query.message,
        PhoneNumber: '+' + req.query.number,
        MessageAttributes: {
            'AWS.SNS.SMS.SenderID': {
                'DataType': 'String',
                'StringValue': req.query.subject
            }
        }
    };

    var publishTextPromise = new AWS.SNS({ apiVersion: '2010-03-31' }).publish(params).promise();

    publishTextPromise.then(
        function (data) {
            res.end(JSON.stringify({ MessageID: data.MessageId }));
        }).catch(
            function (err) {
                res.end(JSON.stringify({ Error: err }));
            });

});

app.listen(3000, () => console.log('SMS Service Listening on PORT 3000'))