In this article, we are going to learn how we can send SMS or WhatsApp messages with your Node.js app.
Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser.
Approach:
To send SMS and WhatsApp messages we are going to use the Twilio. The Twilio helps us to send SMS, make Calls within our Node.js app. So first, we will install the Twilio package with npm or yarn.
Get the Twilio Credentials:
Go to https://www.twilio.com/
Create a new account for trial.
Copy the account SID, auth token and provided phone number.
Create Node.js Application: You can start creating Node.js project by following command:
npm i
or
yarn
π‘ Note: This will create a node_modules folder.
Install the required package: Now we will install the twilio and dotenv package using the below command:
npm i twilio dotenv
or
yarn add twilio dotenv
π‘ Note: This will install twilio and dotenv package for your project.
Create following files in route directory:
app.js
.env
Your project structure should look like this:
Make Configuration: add following code in .env
file.
TWILIO_SID=your-account-sid
TWILIO_AUTH_TOKEN=your-account-token
β WARNING: replace your-account-sid
and your-account-token
with your twilio credentials copied above!
To Send SMS: add following code in your app.js
file.
require('dotenv').config()
const accountSID = process.env.TWILIO_SID;
const accountToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSID, accountToken);
// send a sms
client.messages.create({
body: 'Hi, this is a test sms!',
from: 'your-provided-phone-number',
to: 'the-recipient-phone-number'
}).then(message => console.log(message));
β WARNING: replace your-provided-phone-number
with your provided dummy twilio phone number copied above! and the-recipient-phone-number
with the phone number whom you want to give a sms.
Explanation:
In the above example first, we are using twilio service to send SMS. After that, we are installing twilio package along with dotenv for configuration with the credentials provided by twilio.
Steps to run the application: Run the below command in the terminal to run the app.
node app.js
Output:
π SUPPORT: Hit like if you like this article and feel free to ask queries!
Top comments (3)
Thank you for this π will be useful for bulk sms π
Sounds good! But twilio is not free at all, it will charge after a certain period! π
Ok no problem πππ½