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 SDK 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.
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.
- A Twilio account.
- A Twilio Phone number with SMS (and MMS) capabilities.
Before you run any of the examples on this page, create a Function and paste the example code into it. You can create a Function in the Twilio Console or by using the Serverless Toolkit.
If you prefer a UI-driven approach, complete these steps in the Twilio Console:
- Log in to the Twilio Console and navigate to Develop > Functions & Assets. If you're using the legacy Console, open the Functions tab.
- Functions are contained within Services. Click Create Service to create a new Service.
- Click Add + and select Add Function from the dropdown.
- The Console creates a new protected Function that you can rename. The filename becomes the URL path of the Function.
- Copy one of the example code snippets from this page and paste the code into your newly created Function. You can switch examples by using the dropdown menu in the code rail.
- Click Save.
- Click Deploy All to build and deploy the Function. After deployment, you can access your Function at
https://<service-name>-<random-characters>-<optional-domain-suffix>.twil.io/<function-path>
For example:test-function-3548.twil.io/hello-world.
You can now invoke your Function with HTTP requests, configure it as the webhook for a Twilio phone number, call it from a Twilio Studio Run Function Widget, and more.
Functions that you create in the UI are protected by default. Set Functions that you deploy with the Serverless Toolkit to protected as well by adding "protected" before the file extension, for example, "send-sms.protected.js". This configuration helps secure your Function and prevents unauthorized access. However, it also adds an extra step when you want to invoke and test the Function manually, as shown in the examples on this page.
To call a protected Function, provide a valid X-Twilio-Signature header in the request. See the documentation for details about the request-validation process.
Though you can generate the header manually with HMAC-SHA1, use the convenience utilities exported by Twilio's SDKs instead. Download the SDK for your preferred language from the libraries page.
After you install the SDK, complete these steps:
- Set your Auth Token as an environment variable.
- If you use the Node.js example, update the request URL to reference your Service and any query parameters you plan to pass. For other languages, see the examples here.
- Run the script and copy the generated
X-Twilio-Signaturevalue for use in the next step.
The following sections show how to generate a signature for a POST request with a JSON body and for a GET request that passes data as query parameters:
1const { getExpectedTwilioSignature } = require('twilio/lib/webhooks/webhooks');23// Retrieve your auth token from the environment instead of hardcoding4const authToken = process.env.TWILIO_AUTH_TOKEN;56// Use the Twilio helper to generate your valid signature!7// The 1st argument is your Twilio auth token.8// The 2nd is the full URL of your Function.9// The 3rd is any application/x-www-form-urlencoded data being sent, which is none!10const xTwilioSignature = getExpectedTwilioSignature(11authToken,12'https://example-4321.twil.io/sms/send',13{} // <- Leave this empty if sending request data via JSON14);1516// Print the signature to the console for use with your17// preferred HTTP client18console.log('xTwilioSignature: ', xTwilioSignature);1920// For example, the output will look like this:21// xTwilioSignature: coGTEaFEMv8ejgNGtgtUsbL8r7c=
Create a valid request
After you generate a valid X-Twilio-Signature value, include it as a header in the request to your Function. You can use tools such as curl or Postman. Make sure to do the following:
- Set the full URL of the Function, including the root of your Service and the full path to the deployed Function.
- Set the
X-Twilio-Signatureheader and content type header (application/json) for your request. - Define the JSON body that you're sending to the Function
Using curl, the request looks like this:
1curl -X POST 'http://test-4321.twil.io/sms/send' \2-H 'X-Twilio-Signature: coGTEaFEMv8ejgNGtgtUsbL8r7c=' \3-H 'Content-Type: application/json' \4--data-raw '{5"Body": "Hello, there!"6}'
Twilio credentials required
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.
1exports.handler = function (context, event, callback) {2// The pre-initialized Twilio client is available from the `context` object3const twilioClient = context.getTwilioClient();45// Query parameters or values sent in a POST body can be accessed from `event`6const from = event.From || '+15017122661';7const to = event.To || '+15558675310';8const body = event.Body || 'Ahoy, World!';910// Use `messages.create` to generate a message. Be sure to chain with `then`11// and `catch` to properly handle the promise and call `callback` _after_ the12// message is sent successfully!13twilioClient.messages14.create({ body, to, from })15.then((message) => {16console.log('SMS successfully sent');17console.log(message.sid);18// Make sure to only call `callback` once everything is finished, and to pass19// null as the first parameter to signal successful execution.20return callback(null, `Success! Message SID: ${message.sid}`);21})22.catch((error) => {23console.error(error);24return callback(error);25});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:
1// Note: Since we're using the `await` keyword in this Function, it must be declared as `async`2exports.handler = async function (context, event, callback) {3// The pre-initialized Twilio client is available from the `context` object4const twilioClient = context.getTwilioClient();56// In this example the messages are inlined. They could also be retrieved from7// a private Asset, an API call, a call to a database, etc to name some options.8const groupMessages = [9{10name: 'Person1',11to: '+15105550100',12body: 'Hello Alan',13from: '+15095550100',14},15{16name: 'Person2',17to: '+15105550101',18body: 'Hello Winston',19from: '+15095550100',20},21{22name: 'Person3',23to: '+15105550102',24body: 'Hello Deepa',25from: '+15095550100',26},27];2829try {30// Create an array of message promises with `.map`, and await them all in31// parallel using `Promise.all`. Be sure to use the `await` keyword to wait32// for the promises to all finish before attempting to log or exit!33const results = await Promise.all(34groupMessages.map((message) => twilioClient.messages.create(message))35);36results.forEach((result) => console.log(`Success: ${result.sid}`));37// Make sure to only call `callback` once everything is finished, and to pass38// null as the first parameter to signal successful execution.39return callback(null, 'Batch SMS Successful');40} catch (error) {41console.error(error);42return callback(error);43}44};
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.
1exports.handler = function (context, event, callback) {2// The pre-initialized Twilio client is available from the `context` object3const twilioClient = context.getTwilioClient();45// Query parameters or values sent in a POST body can be accessed from `event`6const from = event.From || '+15017122661';7const to = event.To || '+15558675310';8const body = event.Body || 'This is the ship that made the Kessel Run in fourteen parsecs?';9// Note that the `mediaUrl` value may be a single string, or an array of strings10const mediaUrl = event.mediaUrl || 'https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg';1112// Use `messages.create` to generate a message. Be sure to chain with `then`13// and `catch` to properly handle the promise and call `callback` _after_ the14// message is sent successfully!15// Note the addition of the `mediaUrl` value as configuration for `messages.create`.16twilioClient.messages17.create({ body, to, from, mediaUrl })18.then((message) => {19console.log('MMS successfully sent');20console.log(message.sid);21// Make sure to only call `callback` once everything is finished, and to pass22// null as the first parameter to signal successful execution.23return callback(null, `Success! Message SID: ${message.sid}`);24})25.catch((error) => {26console.error(error);27return callback(error);28});29};