Twilio binding for Azure Functions

This article explains how to send text messages by using Twilio bindings in Azure Functions. Azure Functions supports output bindings for Twilio.

This is reference information for Azure Functions developers. If you're new to Azure Functions, start with the following resources:

Install extension

The extension NuGet package you install depends on the C# mode you're using in your function app:

Functions execute in the same process as the Functions host. To learn more, see Develop C# class library functions using Azure Functions.

The functionality of the extension varies depending on the extension version:

Add the extension to your project by installing the NuGet package, version 3.x.

Install bundle

Starting with Functions version 2.x, the HTTP extension is part of an extension bundle, which is specified in your host.json project file. To learn more, see extension bundle.

This version of the extension should already be available to your function app with extension bundle, version 2.x.


::: zone-end

Example

Unless otherwise noted, these examples are specific to version 2.x and later version of the Functions runtime.

A C# function can be created using one of the following C# modes:

  • In-process class library: compiled C# function that runs in the same process as the Functions runtime.
  • Isolated process class library: compiled C# function that runs in a process isolated from the runtime. Isolated process is required to support C# functions running on .NET 5.0.
  • C# script: used primarily when creating C# functions in the Azure portal.

The following example shows a C# function that sends a text message when triggered by a queue message.

using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace TwilioQueueOutput
{
    public static class QueueTwilio
    {
        [FunctionName("QueueTwilio")]
        [return: TwilioSms(AccountSidSetting = "TwilioAccountSid", AuthTokenSetting = "TwilioAuthToken", From = "+1425XXXXXXX")]
        public static CreateMessageOptions Run(
        [QueueTrigger("myqueue-items", Connection = "AzureWebJobsStorage")] JObject order,
        ILogger log)
        {
            log.LogInformation($"C# Queue trigger function processed: {order}");

            var message = new CreateMessageOptions(new PhoneNumber(order["mobileNumber"].ToString()))
            {
                Body = $"Hello {order["name"]}, thanks for your order!"
            };

            return message;
        }
    }
}

This example uses the TwilioSms attribute with the method return value. An alternative is to use the attribute with an out CreateMessageOptions parameter or an ICollector<CreateMessageOptions> or IAsyncCollector<CreateMessageOptions> parameter.

The following example shows a Twilio output binding in a function.json file and a JavaScript function that uses the binding.

Here's binding data in the function.json file:

Example function.json:

{
  "type": "twilioSms",
  "name": "message",
  "accountSidSetting": "TwilioAccountSid",
  "authTokenSetting": "TwilioAuthToken",
  "from": "+1425XXXXXXX",
  "direction": "out",
  "body": "Azure Functions Testing"
}

Here's the JavaScript code:

module.exports = async function (context, myQueueItem) {
    context.log('Node.js queue trigger function processed work item', myQueueItem);

    // In this example the queue item is a JSON string representing an order that contains the name of a
    // customer and a mobile number to send text updates to.
    var msg = "Hello " + myQueueItem.name + ", thank you for your order.";

    // Even if you want to use a hard coded message in the binding, you must at least
    // initialize the message binding.
    context.bindings.message = {};

    // A dynamic message can be set instead of the body in the output binding. The "To" number 
    // must be specified in code. 
    context.bindings.message = {
        body : msg,
        to : myQueueItem.mobileNumber
    };
};

Complete PowerShell examples aren't currently available for SendGrid bindings.

The following example shows how to send an SMS message using the output binding as defined in the following function.json.

    {
      "type": "twilioSms",
      "name": "twilioMessage",
      "accountSidSetting": "TwilioAccountSID",
      "authTokenSetting": "TwilioAuthToken",
      "from": "+1XXXXXXXXXX",
      "direction": "out",
      "body": "Azure Functions Testing"
    }

You can pass a serialized JSON object to the func.Out parameter to send the SMS message.

import logging
import json
import azure.functions as func

def main(req: func.HttpRequest, twilioMessage: func.Out[str]) -> func.HttpResponse:

    message = req.params.get('message')
    to = req.params.get('to')

    value = {
      "body": message,
      "to": to
    }

    twilioMessage.set(json.dumps(value))

    return func.HttpResponse(f"Message sent")

The following example shows how to use the TwilioSmsOutput annotation to send an SMS message. Values for to, from, and body are required in the attribute definition even if you override them programmatically.

package com.function;

import java.util.*;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;

public class TwilioOutput {

    @FunctionName("TwilioOutput")
    public HttpResponseMessage run(
            @HttpTrigger(name = "req", methods = { HttpMethod.GET, HttpMethod.POST },
                authLevel = AuthorizationLevel.FUNCTION) HttpRequestMessage<Optional<String>> request,
            @TwilioSmsOutput(
                name = "twilioMessage",
                accountSid = "AzureWebJobsTwilioAccountSID",
                authToken = "AzureWebJobsTwilioAuthToken",
                to = "+1XXXXXXXXXX",
                body = "From Azure Functions",
                from = "+1XXXXXXXXXX") OutputBinding<String> twilioMessage,
            final ExecutionContext context) {

        String message = request.getQueryParameters().get("message");
        String to = request.getQueryParameters().get("to");

        StringBuilder builder = new StringBuilder()
            .append("{")
            .append("\"body\": \"%s\",")
            .append("\"to\": \"%s\"")
            .append("}");

        final String body = String.format(builder.toString(), message, to);

        twilioMessage.setValue(body);

        return request.createResponseBuilder(HttpStatus.OK).body("Message sent").build();
    }
}

Attributes

Both in-process and isolated process C# libraries use attributes to define the output binding. C# script instead uses a function.json configuration file.

In in-process function apps, use the TwilioSmsAttribute, which supports the following parameters.

Attribute/annotation property Description
AccountSidSetting This value must be set to the name of an app setting that holds your Twilio Account Sid (TwilioAccountSid). When not set, the default app setting name is AzureWebJobsTwilioAccountSid.
AuthTokenSetting This value must be set to the name of an app setting that holds your Twilio authentication token (TwilioAccountAuthToken). When not set, the default app setting name is AzureWebJobsTwilioAuthToken.
To This value is set to the phone number that the SMS text is sent to.
From This value is set to the phone number that the SMS text is sent from.
Body This value can be used to hard code the SMS text message if you don't need to set it dynamically in the code for your function.

Annotations

The TwilioSmsOutput annotation allows you to declaratively configure the Twilio output binding by providing the following configuration values:

+

Place the TwilioSmsOutput annotation on an OutputBinding<T> parameter, where T may be any native Java type such as int, String, byte[], or a POJO type.

Configuration

The following table explains the binding configuration properties that you set in the function.json file, which differs by runtime version:

function.json property Description
type must be set to twilioSms.
direction must be set to out.
name Variable name used in function code for the Twilio SMS text message.
accountSidSetting This value must be set to the name of an app setting that holds your Twilio Account Sid (TwilioAccountSid). When not set, the default app setting name is AzureWebJobsTwilioAccountSid.
authTokenSetting This value must be set to the name of an app setting that holds your Twilio authentication token (TwilioAccountAuthToken). When not set, the default app setting name is AzureWebJobsTwilioAuthToken.
from This value is set to the phone number that the SMS text is sent from.
body This value can be used to hard code the SMS text message if you don't need to set it dynamically in the code for your function.

In version 2.x, you set the to value in your code.

When you're developing locally, add your application settings in the local.settings.json file in the Values collection.

Next steps