Sending messages using Twilio and Node.js

Development Feb 8, 2020

Messaging is a basic feature now-a-days required by almost all types of applications be it a mobile app or web app.
Through messaging we can keep our clients updated even when they are not using our app.
Messaging can be used for varied purposes some of which are:
* Verifying users by sending them OTP
* Provide updates about system to subscribed users

For this blog I will explain how to send programmable SMS in Node.js using Twilio

Brief about Twilio
* Has support for various technologies like PHP, .Net, JAVA, Node.js, Ruby, Pyhton.
* We can also handle inbound messages on twilio i.e. we can reply to twilio message.
* Other than plain text we can also send media in message (like images)
* It have some nominal charges for the messages we send (charges vary based on country to country, service providers, message is being sent to some local number or international number and also on the length of content. Pricing for different countries can be checked on https://www.twilio.com/sms/pricing)
* Provides us with a dashboard for tracking the amount of messages sent and their status along with amount they cost us and other details.
* Sends messages to valid numbers only.
* We can also track for any error occurred while sending SMS

Using Twilio library in Node.js

Following are the things required for starting to send messages with twilio:
1. Verified account on Twilio (can create one by visiting https://www.twilio.com/try-twilio)
2. SMS-enabled Twilio phone number for sending messages
3. Auth token and Account Sid (auto generated for every new project we create)

Steps for sending programmable messages in node.js:

  1. Install the twilio package

     > npm install twilio 
    
  2. Get your credentials and store them in environment file (accountSid, authToken, and fromPhoneNumber purchased on twilio or trial phoneNumber)

  3. Get twilio client by requiring twilio package along with passing accountSid and authToken from environment variable

Following is the sample code for sending simple message through twilio:

const FROM_NUMBER = 'TWILIO_PURCHASED_NUMBER';
const TO_NUMBER = 'NUMBER_ON_WHICH_MESSAGE_IS_TO_BE_SENT';
const AUTH_TOKEN = 'your_auth_token';
const ACCOUNT_SID = 'ACXXXXXXXXXXXXXXXXXXXXX';

const client = require('twilio')(ACCOUNT_SID, AUTH_TOKEN);

client.messages
    .create({
      body: 'message we want to send',
      from: FROM_NUMBER,
      to: TO_NUMBER
    })
    .then(message => {
      console.log(message);
    }).catch((error) => {
      console.log(error)
    });

Here in this demo code I have hard coded the creadentials but it should be taken from environment file.

If we’re using a trial account, we'll notice that any messages we send will always begin with “Sent from a Twilio trial account.” Once we upgrade our account, we will no longer see that message.

When Twilio receives our request to send an SMS via the REST API, it will check that we’ve included a valid Twilio phone number in the From field. Twilio will then either queue the SMS or return this HTTP error in its response to our request.

twilio_sms

If SMS was sent successfully we will get response as follows:

{
    "accountSid":"ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "apiVersion":"2010-04-01",
    "body":"This is the ship that made the Kessel Run in fourteen parsecs?",
    "dateCreated":"2018-09-11T17:29:05.000Z",
    "dateUpdated":"2018-09-11T17:29:05.000Z",
    "dateSent":null,"direction":"outbound-api",
    "errorCode":null,
    "errorMessage":null,
    "to":"+15558675310",
    "from":"+15017122661",
    "messagingServiceSid":null,"numMedia":"0",
    "numSegments":"1",
    "price":null,"priceUnit":"USD",
    "sid":"SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "status":"queued",
    "uri":"/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX7/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json",
    "subresourceUris":{
      "media": null
    }
}

When we send a SMS message over 160 characters the message will be split. Large messages are segmented into 153 character segements and sent individually then rebuilt by the recipients device. For example, a 161 character message will be sent as two messages, one with 153 characters and the second with 8 characters.
We can see on our programmable dashboard as to in how many segments our message was sent:

Screenshot-2020-02-08-at-12.23.34-PM

Detail of message sent:

Screenshot-2020-02-08-at-12.19.39-PM

Here in the detail log we can see that I have sent a long message so it is divided into various segments and the time at which each segment was delivered

Some points to remember:
1. For sending message from trial account we need to verify the TO_PHONE_NUMBERS.
2. Phone numbers provided to twilio should be with country code.
3. Phone numbers provided to twilio should be valid phone number.

Helpful links:
* https://www.twilio.com/docs/sms/tutorials/how-to-send-sms-messages-node-js
* https://www.twilio.com/docs/sms/quickstart/node

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.