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

Send SMS and MMS


All Functions execute with a pre-initialized instance of the Twilio Node.js SDK available for use. This means you can access and utilize any Twilio helper library method in your Function. For example, sending SMS via Twilio's Programmable SMS from a Function is incredibly accessible, as we'll show in the following example snippets.

These examples are not exhaustive, and we encourage you to peruse the Programmable SMS tutorials for more inspiration on what you can build.


Prerequisites

prerequisites page anchor

Before you start, be sure to complete the following prerequisites. You can skip to "Create and host a Function" if you've already completed these steps and need to know more about Function deployment and invocation, or you can skip all the way to "Send a single SMS" if you're all ready to go and want to get straight to the code.


Create and host a Function

create-and-host-a-function page anchor

In order to run any of the following examples, you will first need to create a Function into which you can paste the example code. You can create a Function using the Twilio Console or the Serverless Toolkit as explained below:

ConsoleServerless Toolkit

If you prefer a UI-driven approach, creating and deploying a Function can be done entirely using the Twilio Console and the following steps:

  1. Log in to the Twilio Console and navigate to the Functions tab(link takes you to an external page) . If you need an account, you can sign up for a free Twilio account here(link takes you to an external page) !
  2. Functions are contained within Services . Create a Service by clicking the Create Service(link takes you to an external page) button and providing a name such as test-function .
  3. Once you've been redirected to the new Service, click the Add + button and select Add Function from the dropdown.
  4. This will create a new Protected Function for you with the option to rename it. The name of the file will be path it is accessed from.
  5. Copy any one of the example code snippets from this page that you want to experiment with, and paste the code into your newly created Function. You can quickly switch examples by using the dropdown menu of the code rail.
  6. Click Save to save your Function's contents.
  7. Click Deploy All to build and deploy the Function. After a short delay, your Function will be accessible from: https://<service-name>-<random-characters>-<optional-domain-suffix>.twil.io/<function-path>
    For example: test-function-3548.twil.io/hello-world .

Your Function is now ready to be invoked by HTTP requests, set as the webhook of a Twilio phone number, invoked by a Twilio Studio Run Function Widget, and more!


How to invoke your Function

how-to-invoke-your-function page anchor

Functions created in the UI are Protected by default, and we highly recommend you to set Functions deployed via the Serverless Toolkit to protected as well by prepending protected before the file extension, for example: send-sms.protected.js. This will help secure your Function and protect it from being accessed by bad actors. However, this also adds an extra layer of complexity if you want to manually invoke and test code, such as the examples on this page.

In order to successfully call your protected Function, you will need to provide a valid X-Twilio-Signature header in your request. You can learn more about the request validation process, but in the meantime, let's get started with some code that will get you up and running fast.

Generate a valid X-Twilio-Signature header

generate-a-valid-x-twilio-signature-header page anchor

While it's possible to generate the header yourself using HMAC-SHA1, we highly recommend you use the convenience utilities exported by Twilio's Helper Libraries to perform this operation. Head over to the libraries page to download the library for your language of choice.

Once you have the library of your choice installed, you'll need to:

  1. Set your Auth Token(link takes you to an external page) as an environment variable .
  2. Modify the URL of the example below to match your Service and any intended data that you want to communicate as query parameters, if any, if using Node.js. (Refer to the examples here for how to generate a signature with other SDKs.)
  3. Execute the modified script and save the resulting X-Twilio-Signature for use in the next step.

Here are two examples for if you want to generate a signature for a POST request which includes JSON, or a GET request that communicates its data as query parameters instead:

With a JSON bodyWith Query Parameters

_21
const { getExpectedTwilioSignature } = require('twilio/lib/webhooks/webhooks');
_21
_21
// Retrieve your auth token from the environment instead of hardcoding
_21
const authToken = process.env.TWILIO_AUTH_TOKEN;
_21
_21
// Use the Twilio helper to generate your valid signature!
_21
// The 1st argument is your Twilio auth token.
_21
// The 2nd is the full URL of your Function.
_21
// The 3rd is any application/x-www-form-urlencoded data being sent, which is none!
_21
const xTwilioSignature = getExpectedTwilioSignature(
_21
authToken,
_21
'https://example-4321.twil.io/sms/send',
_21
{} // <- Leave this empty if sending request data via JSON
_21
);
_21
_21
// Print the signature to the console for use with your
_21
// preferred HTTP client
_21
console.log('xTwilioSignature: ', xTwilioSignature);
_21
_21
// For example, the output will look like this:
_21
// xTwilioSignature: coGTEaFEMv8ejgNGtgtUsbL8r7c=

Create a valid request

Once you've generated a valid X-Twilio-Signature value, it's time to use this as a header in a request to your Function. You can do so using a variety of tools, such as curl(link takes you to an external page), Postman(link takes you to an external page), and more. Be sure to:

  • Set the URL of the Function, including the root of your Service and the full path to the deployed Function.
  • Set the X-Twilio-Signature header and content type header ( application/json ) for your request.
  • Define the JSON body that you're sending to the Function

Using curl, the example request above would look like this:


_10
curl -X POST 'http://test-4321.twil.io/sms/send' \
_10
-H 'X-Twilio-Signature: coGTEaFEMv8ejgNGtgtUsbL8r7c=' \
_10
-H 'Content-Type: application/json' \
_10
--data-raw '{
_10
"Body": "Hello, there!"
_10
}'


(warning)

Warning

For any Function using the built-in Twilio Client, the "Add my Twilio Credentials (ACCOUNT_SID) and (AUTH_TOKEN) to ENV" option on the Settings > Environment Variables tab must be enabled.

You can use a Function to send a single SMS from your Twilio phone number via Twilio's Programmable SMS. The To, From, and Body parameters of your message must be specified to successfully send.

You'll tell Twilio which phone number to use to send this message by either providing a From value in your request, or by omitting it and replacing the placeholder default value in the example code with your own Twilio phone number.

Next, specify yourself as the message recipient by either providing a To value in your request, or by omitting it and replacing the default value in the example code with your personal number. The resulting from and to values both must use E.164 formatting ("+" and a country code, e.g., +16175551212).

Finally, the body value determines the contents of the SMS that is being sent. As with the other values, either pass in a Body value in your request to this Function or override the default in the example to your own custom message.

Once you've made any modifications to the sample and have deployed your Function for testing, go ahead and make some test HTTP requests against it. Example code for invoking your Function is described earlier in this document.

Send a single SMS

send-a-single-sms-1 page anchor

_26
exports.handler = function (context, event, callback) {
_26
// The pre-initialized Twilio Client is available from the `context` object
_26
const twilioClient = context.getTwilioClient();
_26
_26
// Query parameters or values sent in a POST body can be accessed from `event`
_26
const from = event.From || '+15017122661';
_26
const to = event.To || '+15558675310';
_26
const body = event.Body || 'Ahoy, World!';
_26
_26
// Use `messages.create` to generate a message. Be sure to chain with `then`
_26
// and `catch` to properly handle the promise and call `callback` _after_ the
_26
// message is sent successfully!
_26
twilioClient.messages
_26
.create({ body, to, from })
_26
.then((message) => {
_26
console.log('SMS successfully sent');
_26
console.log(message.sid);
_26
// Make sure to only call `callback` once everything is finished, and to pass
_26
// null as the first parameter to signal successful execution.
_26
return callback(null, `Success! Message SID: ${message.sid}`);
_26
})
_26
.catch((error) => {
_26
console.error(error);
_26
return callback(error);
_26
});
_26
};


You are not limited to sending a single SMS in a Function. For example, suppose you have a list of users to send messages to at the same time. As long as the list is reasonably short to avoid hitting rate limiting (see Messaging Services for how to send high volume messages), you can execute multiple, parallel calls to create a message and await the result in a Function as shown in the example below:


_44
// Note: Since we're using the `await` keyword in this Function, it must be declared as `async`
_44
exports.handler = async function (context, event, callback) {
_44
// The pre-initialized Twilio Client is available from the `context` object
_44
const twilioClient = context.getTwilioClient();
_44
_44
// In this example the messages are inlined. They could also be retrieved from
_44
// a private Asset, an API call, a call to a database, etc to name some options.
_44
const groupMessages = [
_44
{
_44
name: 'Person1',
_44
to: '+15105550100',
_44
body: 'Hello Alan',
_44
from: '+15095550100',
_44
},
_44
{
_44
name: 'Person2',
_44
to: '+15105550101',
_44
body: 'Hello Winston',
_44
from: '+15095550100',
_44
},
_44
{
_44
name: 'Person3',
_44
to: '+15105550102',
_44
body: 'Hello Deepa',
_44
from: '+15095550100',
_44
},
_44
];
_44
_44
try {
_44
// Create an array of message promises with `.map`, and await them all in
_44
// parallel using `Promise.all`. Be sure to use the `await` keyword to wait
_44
// for the promises to all finish before attempting to log or exit!
_44
const results = await Promise.all(
_44
groupMessages.map((message) => twilioClient.messages.create(message))
_44
);
_44
results.forEach((result) => console.log(`Success: ${result.sid}`));
_44
// Make sure to only call `callback` once everything is finished, and to pass
_44
// null as the first parameter to signal successful execution.
_44
return callback(null, 'Batch SMS Successful');
_44
} catch (error) {
_44
console.error(error);
_44
return callback(error);
_44
}
_44
};


Include MMS in a message

include-mms-in-a-message page anchor

Media, such as images, can be included in your text messages by adding the mediaUrl parameter to the call to client.messages.create. This can either be a single string to a publicly accessible URL or an array of multiple media URLs.


_29
exports.handler = function (context, event, callback) {
_29
// The pre-initialized Twilio Client is available from the `context` object
_29
const twilioClient = context.getTwilioClient();
_29
_29
// Query parameters or values sent in a POST body can be accessed from `event`
_29
const from = event.From || '+15017122661';
_29
const to = event.To || '+15558675310';
_29
const body = event.Body || 'This is the ship that made the Kessel Run in fourteen parsecs?';
_29
// Note that the `mediaUrl` value may be a single string, or an array of strings
_29
const mediaUrl = event.mediaUrl || 'https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg';
_29
_29
// Use `messages.create` to generate a message. Be sure to chain with `then`
_29
// and `catch` to properly handle the promise and call `callback` _after_ the
_29
// message is sent successfully!
_29
// Note the addition of the `mediaUrl` value as configuration for `messages.create`.
_29
twilioClient.messages
_29
.create({ body, to, from, mediaUrl })
_29
.then((message) => {
_29
console.log('MMS successfully sent');
_29
console.log(message.sid);
_29
// Make sure to only call `callback` once everything is finished, and to pass
_29
// null as the first parameter to signal successful execution.
_29
return callback(null, `Success! Message SID: ${message.sid}`);
_29
})
_29
.catch((error) => {
_29
console.error(error);
_29
return callback(error);
_29
});
_29
};


Rate this page: