How to send SMS using Twilio API + Nodejs

Nupoor
Nupoor
Sep 3, 2018 · 2 min read

Twilio SMSAPI Workflow

Often we are required to send automated emails and SMS to notify user about something. Common examples would be placing an order on e-commerce website, online bookings, banking transactions, etc. Twilio provides pretty user friendly API to achieve this functionality. Let’s implement it using Node Expressjs. In this article we will set up simple front end and backend step by step.

First off visit Twilio official website and create your account. You can set upto 10 numbers from which you can receive sms. The send to sms number will be configured and twilio will send an OTP to confirm the same. Once the account is setup you’ll be able to see accountSid and authToken in your profile’s setting section.

Official website: https://www.twilio.com/docs/


app.js

Install express,ejs,body-parser and twilio using npm. Include the same in your app.js file.

Add view engine as ejs and configure public folder path.

Set localhost port to test your app.

views/index.ejs

index.ejs template will have From textbox, To textbox and a submit button like below. Feel free to style it as per your interest.

<input type=”tel” name=”number” id=”number” placeholder=”Enter Mobile Number”><input type=”text” name=”msg” id=”msg” placeholder=”Enter message here” ><input type=”button” value=”Send Text” id=”button” class=”button btn-primary” >

post route

Configure client using sid and token like below:

const client = require(‘twilio’)(accountSid, authToken);

From and To numbers will be available on req.body.

client.messages .create({body: "",from: ‘<YOUR_FROM_NUMBER>’, to: ‘+’ + number // To number requires ‘+’ , India country code }) .then(message => console.log(message.sid)) .done(); });

Test the app

Start the service using nodemon app.js and visit localhost://<YOUR_PORT>

Enter “From” and “To” numbers and hit submit. You shall receive sms from Twilio with default message configured in body parameter of client.messages.create

For any further information please check official documentation, it’s user friendly and easy to use than nexmo. I tried using it in the past but to my avail couldn’t integrate it with my project. If you have any question please leave a comment till then happy coding. Here’s a sample sms I received on my mobile.

SMS sent from Twilio

Nupoor

Written by

Nupoor

JS | Nodejs | Expressjs | Mongo | MySQL | Tech Enthusiast | Songwriter | Guitarist

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade