3

Send SMS with Node.js App

 1 year ago
source link: https://dev.to/sujeetgund/send-sms-with-nodejs-app-1c38
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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:

  1. Go to https://www.twilio.com/

  2. Create a new account for trial.

  3. Copy the account SID, auth token and provided phone number.

Screenshot 1

Create Node.js Application: You can start creating Node.js project by following command:

npm i
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
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:
Screenshot 3

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:

Screenshot 4

💖 SUPPORT: Hit like if you like this article and feel free to ask queries!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK