To use the Twilio API for sending SMS in Node.js, you need to follow these steps:
Create a Twilio Account:
Get Twilio API Credentials:
Get a Twilio Phone Number:
Install the Twilio Node.js Library:
bashnpm install twilio
Write the Node.js Code:
Create a new JavaScript file (e.g., send-sms.js
) and use the following code:
javascriptconst 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.
Run the Code:
bashnode 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.