Skip to content

Instantly share code, notes, and snippets.

Created September 11, 2019 16:32
Show Gist options
  • Save tygerbytes/378a647545ef143de97dae7e8da4e232 to your computer and use it in GitHub Desktop.
Save tygerbytes/378a647545ef143de97dae7e8da4e232 to your computer and use it in GitHub Desktop.
Azure Function snippet for sending text messages with Twilio
public static async Task<IActionResult> Run(
// This is an HTTP trigger accepting POST requests. That's why we are able to invoke it using Postman.
[HttpTrigger(AuthorizationLevel.Function, "post", Route = "tygerbytes/sygnal")] HttpRequest req,
ILogger log,
ExecutionContext context)
// The FuncConfig class encapsulates environment-specific settings like those
// TWILIO... environment variables.
var funcConfig = new FuncConfig(context);
// Grab the request body, the thing we added as "raw" JSON content in Postman.
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
// "Deserialize" the JSON string into an SendSmsRequest object.
var request = JsonConvert.DeserializeObject<SendSmsRequest>(requestBody);
if (!request.IsValid())
// If this request is malformed, return a 400 Bad Request HTTP code.
// See the SendSmsRequest class for more info.
return new BadRequestObjectResult(request.InvalidRequestReason());
// Convert the request object back to JSON (serialize) and log it.
// Wasteful? Perhaps. But very useful when debugging. :)
// Initialize the Twilio engine. Vroooom!
await funcConfig.TwilioInitAsync();
// Convert the semi-colon delimited list of phone numbers to an array
// of PhoneNumber objects, then send an SMS to each one.
foreach (var number in Utils.SplitTo<PhoneNumber>(request.ToPhoneNumbers))
// Creating the MessageResource sends the SMS.
var messageResource = MessageResource.Create(
// Note that we append the SMS signature to the end of the message.
body: $"{request.Message}\n{funcConfig.SmsSignature}",
from: funcConfig.TwilioPhoneNumber,
to: number
// Log it along with the status message returned.
log.LogInformation($"SMS to {number} has been {messageResource.Status}.");
catch (Exception ex)
// Uh-oh. Something went wrong. Send a HTTP 500 Internal Server error code,
// including the exception message.
return new ObjectResult(ex.Message)
StatusCode = 500
// Yay! Everything worked. Return an HTTP 200 OK.
return new OkObjectResult($"Message sent.");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment