Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Send SMS and MMS Messages in Node.js


In this tutorial, we'll show you how to use Programmable Messaging to send SMS and MMS messages from your Node.js application.

(warning)

Warning

The code samples in this tutorial use Twilio's Node helper library(link takes you to an external page). Let's get started!


Sign up for (or log in to) your Twilio account

sign-up-for-or-log-in-to-your-twilio-account page anchor
(information)

Info

If you have a Twilio account and Twilio phone number with SMS capabilities, you're all set! Feel free to jump straight to the code.

(warning)

Warning

If you are sending SMS to the U.S. or Canada, before proceeding further please be aware of updated restrictions on the use of Toll-Free numbers for messaging, including TF numbers obtained through Free Trial. Please click here(link takes you to an external page) for details.

Before you can send messages from the Twilio API, you'll need a Twilio account(link takes you to an external page) and a Twilio-powered phone number(link takes you to an external page).

If you're brand new to Twilio, you can sign up for a free trial account(link takes you to an external page) to get started.

Once you've signed up and selected a project (the "Learn and Explore" template will work for this tutorial), head over to your Console(link takes you to an external page) and get your Account SID and Auth Token. You will need those values for the code samples below.


Get a phone number with SMS (and MMS) capabilities

get-a-phone-number-with-sms-and-mms-capabilities page anchor

Sending messages requires a Twilio phone number with SMS capabilities. If you don't currently own a Twilio phone number with SMS capabilities, you'll need to buy one. After navigating to the Buy a Number page(link takes you to an external page), check the 'SMS' box and click 'Search':

Buy an SMS-capable Twilio Number.

If you live in the US or Canada and also wish to send MMS messages, you can select the 'MMS' box. When viewing the search results, you can see the capability icons in the list of available numbers:

Click Buy Button to Purchase an SMS-capable Number.

Find a number you like and click "Buy" to add it to your account.

(warning)

Warning

If you're using a trial account, you will need to verify your personal phone number via the console(link takes you to an external page) so that you can test sending SMSes to yourself. Learn more about how to work with your free trial account.

Now that you have a Twilio phone number you can start sending messages to mobile devices.


Send an SMS message in Node.js via the REST API

send-an-sms-message-in-nodejs-via-the-rest-api page anchor

To send an outgoing SMS message from your Twilio account, you'll need to make an HTTP POST request to Twilio's Message resource.

Twilio's helper library for Node.js helps you create a new instance of the Message resource, specifying the To, From, and Body parameters of your message.

If you don't already have the Node helper library installed, you can do so using npm(link takes you to an external page):


_10
npm install twilio

This will install the twilio module so that Node.js scripts in the current directory can use it.

Now, create a file named sms.js and include the following code.

Send an SMS using the Programmable Messaging API

send-an-sms-using-the-programmable-messaging-api page anchor
Node.js

_14
// Download the helper library from https://www.twilio.com/docs/node/install
_14
// Find your Account SID and Auth Token at twilio.com/console
_14
// and set the environment variables. See http://twil.io/secure
_14
const accountSid = process.env.TWILIO_ACCOUNT_SID;
_14
const authToken = process.env.TWILIO_AUTH_TOKEN;
_14
const client = require('twilio')(accountSid, authToken);
_14
_14
client.messages
_14
.create({
_14
body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
_14
from: '+15017122661',
_14
to: '+15558675310'
_14
})
_14
.then(message => console.log(message.sid));

Output

_24
{
_24
"account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_24
"api_version": "2010-04-01",
_24
"body": "This is the ship that made the Kessel Run in fourteen parsecs?",
_24
"date_created": "Thu, 30 Jul 2015 20:12:31 +0000",
_24
"date_sent": "Thu, 30 Jul 2015 20:12:33 +0000",
_24
"date_updated": "Thu, 30 Jul 2015 20:12:33 +0000",
_24
"direction": "outbound-api",
_24
"error_code": null,
_24
"error_message": null,
_24
"from": "+15017122661",
_24
"messaging_service_sid": null,
_24
"num_media": "0",
_24
"num_segments": "1",
_24
"price": null,
_24
"price_unit": null,
_24
"sid": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_24
"status": "queued",
_24
"subresource_uris": {
_24
"media": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Media.json"
_24
},
_24
"to": "+15558675310",
_24
"uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json"
_24
}

Replace the placeholder values for accountSid and authToken with your unique values. You can find these in your Twilio console(link takes you to an external page).

(error)

Danger

Please note: it's okay to hardcode your credentials when getting started, but you should use environment variables to keep them secret before deploying to production. Check out our blog post "Working with Environment Variables in Node.js(link takes you to an external page)" for guidance.

You'll tell Twilio which phone number to use to send this message by replacing the from number with the Twilio phone number you purchased earlier.

Next, specify yourself as the message recipient by replacing the to number with your mobile phone number. Both the from and to parameters must use E.164 formatting ("+" and a country code, e.g., +16175551212).

We also include the body parameter, which contains the content of the SMS we're going to send.

Once you've updated the code sample, you can test it out by running it from the command line:


_10
node sms.js

In just a few moments you should receive an SMS!

(warning)

Warning

If you're using a trial account, you'll notice that any messages you send will always begin with "Sent from a Twilio trial account." Once you upgrade your account, you will no longer see this message. Learn more about sending SMS and MMS messages from a trial account.

Let's take a moment to understand what's going on behind the scenes when you send this request to Twilio.

Twilio's response

twilios-response page anchor

When Twilio receives your request to send an SMS via the REST API, it will check that you've included a valid Twilio phone number in the From field. Twilio will then either queue the SMS or return this HTTP error in its response to your request.

Outgoing SMS Diagram.

Assuming your request didn't result in any errors, Twilio's HTTP response will include the SID of the new message. This unique identifier will help us reference this message later: in the code above, we printed that SID to the terminal.

Twilio's JSON response includes a robust amount of data about your message. A sample response might look like this:


_21
{
_21
"accountSid":"ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_21
"apiVersion":"2010-04-01",
_21
"body":"This is the ship that made the Kessel Run in fourteen parsecs?",
_21
"dateCreated":"2018-09-11T17:29:05.000Z",
_21
"dateUpdated":"2018-09-11T17:29:05.000Z",
_21
"dateSent":null,"direction":"outbound-api",
_21
"errorCode":null,
_21
"errorMessage":null,
_21
"to":"+15558675310",
_21
"from":"+15017122661",
_21
"messagingServiceSid":null,"numMedia":"0",
_21
"numSegments":"1",
_21
"price":null,"priceUnit":"USD",
_21
"sid":"SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_21
"status":"queued",
_21
"uri":"/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX7/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json",
_21
"subresourceUris":{
_21
"media": null
_21
}
_21
}

You can access any of these attributes from your Node.js code, much like we did when we logged the message.sid.

Try updaing the existing logging statement in your code to be .then(message => console.log(message.status)) instead. Save the file, then run the code again. You should see the status of your message, "queued", printed to your terminal.

If you receive an error in response from Twilio or never receive the message, you may want to check out these tips for troubleshooting undelivered messages(link takes you to an external page).

(information)

Info

If you'd like to track the status of your messages in real-time, you'll need to set up a StatusCallback URL. Learn more in our guide on tracking outbound message delivery.

Send a message to multiple recipients

send-a-message-to-multiple-recipients page anchor

If you want to send a message to several recipients, you could create a list of recipients (or get a list from a database) and iterate through each phone number in the list:


_11
var numbersToMessage = ["+15558675310", "+14158141829", "+15017122661"]
_11
_11
numbersToMessage.forEach(function(number){
_11
var message = client.messages.create({
_11
body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
_11
from: '+16468635472',
_11
to: number
_11
})
_11
.then(message => console.log(message.status))
_11
.done();
_11
});

This will create a new Message instance for each phone number in the list.

A note on message rate limiting

a-note-on-message-rate-limiting page anchor

As you send more messages via the API, Twilio will queue them up for delivery at your prescribed rate limit(link takes you to an external page). API requests for messages that exceed the specified rates(link takes you to an external page) will be queued and executed as capacity is available.

If your application tries to enqueue more than 4 hours worth of outbound traffic (e.g., enqueuing more than 14,400 messages to Canada over one long code phone number), the API will start returning 429 errors.

If you need to enqueue a large volume of messages, you may find that it's helpful to leverage Twilio's Messaging Services. See our guide on how to set up and send messages from a messaging service in your language of choice for more tips.


Send a message containing media (MMS) in Node.js

send-a-message-containing-media-mms-in-nodejs page anchor

To include media in your Twilio-powered text message, you need to make an addition to the code we wrote above. This time, we need to add the mediaUrl parameter.

Send a Message with an Image URL

send-a-message-with-an-image-url page anchor
Node.js

_15
// Download the helper library from https://www.twilio.com/docs/node/install
_15
// Find your Account SID and Auth Token at twilio.com/console
_15
// and set the environment variables. See http://twil.io/secure
_15
const accountSid = process.env.TWILIO_ACCOUNT_SID;
_15
const authToken = process.env.TWILIO_AUTH_TOKEN;
_15
const client = require('twilio')(accountSid, authToken);
_15
_15
client.messages
_15
.create({
_15
body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
_15
from: '+15017122661',
_15
mediaUrl: ['https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg'],
_15
to: '+15558675310'
_15
})
_15
.then(message => console.log(message.sid));

Output

_24
{
_24
"account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_24
"api_version": "2010-04-01",
_24
"body": "This is the ship that made the Kessel Run in fourteen parsecs?",
_24
"date_created": "Thu, 24 Aug 2023 05:01:45 +0000",
_24
"date_sent": "Thu, 24 Aug 2023 05:01:45 +0000",
_24
"date_updated": "Thu, 24 Aug 2023 05:01:45 +0000",
_24
"direction": "outbound-api",
_24
"error_code": null,
_24
"error_message": null,
_24
"from": "+15017122661",
_24
"num_media": "0",
_24
"num_segments": "1",
_24
"price": null,
_24
"price_unit": null,
_24
"messaging_service_sid": "MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_24
"sid": "SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_24
"status": "queued",
_24
"subresource_uris": {
_24
"media": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Media.json"
_24
},
_24
"to": "+15558675310",
_24
"uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json"
_24
}

Again, update the from and to parameters to use your Twilio phone number and your mobile phone.

The new mediaUrl parameter in this code tells Twilio where to go to get the media we want to include. This must be a publicly accessible URL: Twilio will not be able to reach any URLs that are hidden or that require authentication.

Just as when you send a simple SMS, Twilio will send data about the message in its response to your request. The JSON response will contain the unique SID and URI for your media resource:


_10
"subresourceUris": {"media": "/2010-04 01/Accounts/ACxxxxxxxx/Messages/SMxxxxxxxxxxxxx/Media.json"}

When the Twilio REST API creates your new Message resource, it will save the image found at the specified mediaUrl as a Media resource. Once created, you can access this resource at any time via the API.

You can print this value from your Node.js code to see where the image is stored. Update your sms.js file's console.log to see your newly provisioned Media URI:


_10
console.log(message.subresourceUris.media)

Save the file and run your project. In just a moment you should receive a text message with an image and see the your new Media URI printed to your console.


You've now successfully sent some messages with the Twilio Programmable Messaging API and the Node.js helper library.

Check out these in-depth resources to take your programmatic messaging a step further:


Rate this page: