Send SMS Messages using Twilio's API in Javascript

January 06, 2019

Twilio is a popular platform for sending & receiving SMS/MMS messages. Twilio's easy to use APIs make on-demand messaging real fun!

Before running the code below, fill in the values that are wrapped with <>. Signup for a Twilio developer account, and save your SID & auth token.

Then Run:

npm install --save axios querystring

Save the code below into a file (e.g. app.js):

const axios = require("axios");
const querystring = require('querystring');

// Twilio (TEST) Credentials found here:
// https://www.twilio.com/console/project/settings
const apiVersion = '2010-04-01';
const accountSid = '<YOUR ACCOUNT SID HERE>';
const authToken = '<YOUR TWILIO AUTH TOKEN HERE>';

axios.post(`https://api.twilio.com/${apiVersion}/Accounts/${accountSid}/Messages.json`, querystring.stringify({
  Body: "Testing automated SMS",
  From: "<YOUR TWILIO PHONE NUMBER HERE>",
  To: "<ANY PHONE NUMBER YOU'D LIKE TO SEND SMS TO>"
}), {
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "Authorization": `Basic ${Buffer.from(accountSid + ':' + authToken).toString('base64')}`
  }
})
  .then(response => {
    const { body, to, status } = response.data;
    console.log("Succesful!", {
      body,
      to,
      status
    });
  })
  .catch(error => {
    console.log("Error", error.response.data);
  })

Then run the code above using:

node app.js