How to use the Twilio API for sending SMS in Node.js



Image not found!!

To use the Twilio API for sending SMS in Node.js, you need to follow these steps:

  1. Create a Twilio Account:

    • If you don't have a Twilio account, sign up at Twilio.
  2. Get Twilio API Credentials:

    • After creating an account, log in and get your Account SID and Auth Token from the Twilio Console.
  3. Get a Twilio Phone Number:

  4. Install the Twilio Node.js Library:

    • Open your terminal and run the following command to install the Twilio Node.js library:
      bash
      npm install twilio
  5. Write the Node.js Code:

    • Create a new JavaScript file (e.g., send-sms.js) and use the following code:

      javascript
      const accountSid = 'YOUR_TWILIO_ACCOUNT_SID'; const authToken = 'YOUR_TWILIO_AUTH_TOKEN'; const twilioPhoneNumber = 'YOUR_TWILIO_PHONE_NUMBER'; const twilio = require('twilio'); const client = new twilio(accountSid, authToken); const recipientPhoneNumber = '+1234567890'; // Replace with the recipient's phone number const messageBody = 'Hello, this is a test message from Twilio!'; client.messages .create({ body: messageBody, from: twilioPhoneNumber, to: recipientPhoneNumber, }) .then((message) => console.log(`Message sent with SID: ${message.sid}`)) .catch((error) => console.error(`Error sending message: ${error.message}`));
    • Replace 'YOUR_TWILIO_ACCOUNT_SID', 'YOUR_TWILIO_AUTH_TOKEN', and 'YOUR_TWILIO_PHONE_NUMBER' with your actual Twilio Account SID, Auth Token, and Twilio phone number, respectively.

    • Replace '+1234567890' with the recipient's actual phone number.

  6. Run the Code:

    • Save the file and run it using Node.js:
      bash
      node send-sms.js

    If everything is set up correctly, you should see a message indicating that the SMS has been sent.

Remember to keep your Twilio credentials secure and never share them publicly. It's good practice to use environment variables to store sensitive information like API keys.