Skip to content

Instantly share code, notes, and snippets.

@philnash

philnash/README.md

Last active Feb 5, 2021
Embed
What would you like to do?
Send an SMS with Twilio in Node.js

Send an SMS with Twilio in Node.js

This is an example of how to send an SMS. To run this script you should:

  1. Download the index.js and package.json files
  2. Install the dependencies with npm install
  3. Get your Twilio Account SID and Auth Token from your Twilio console (sign up for a free account if you don't already have one)
  4. Get a Twilio number that can send SMS
  5. Set the credentials and other variables in the environment and run the script:
TWILIO_ACCOUNT_SID=ACXXXX \
  TWILIO_AUTH_TOKEN=abc123 \
  TWILIO_PHONE_NUMBER=+12345678 \
  TO_PHONE_NUMBER=YOUR_PHONE_NUMBER \
  node index.js

Alternatively, you can replace the calls to process.env with your variables.

Run the script and you will receive a new SMS message.

const twilio = require("twilio");
const client = twilio(
process.env.TWILIO_ACCOUNT_SID,
process.env.TWILIO_AUTH_TOKEN
);
function sendSMS(from, to, body) {
client.messages
.create({ from, to, body })
.then((message) => {
console.log(
`SMS message sent from ${from} to ${to}. Message SID: ${message.sid}`
);
})
.catch((error) => {
console.error(error);
});
}
sendSMS(
process.env.TWILIO_PHONE_NUMBER,
process.env.TO_PHONE_NUMBER,
"This is an SMS notification!"
);
{
"name": "sms",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Phil Nash <philnash@twilio.com> (https://philna.sh)",
"license": "MIT",
"dependencies": {
"twilio": "^3.55.1"
},
"devDependencies": {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment