Send Twilio Sms

sendTwilioSms(to, body) sends one SMS through Twilio's Messages API. It POSTs with basic auth, reads TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, and TWILIO_FROM from Script Properties, uses muteHttpExceptions, and returns {ok, sid, error} so the caller can log the result instead of crashing mid-loop.

When to use

  • Texting a team from a roster sheet
  • A status alert that should not go out as email
  • Any script that must record success or failure per number

How to use this snippet

/** * Send one SMS via Twilio. Credentials come from Script Properties: * TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_FROM. * * @param {string} to E.164 number, e.g. +15551234567 * @param {string} body * @return {{ok: boolean, sid: string|null, error: string|null}} */ function sendTwilioSms(to, body) { var props = PropertiesService.getScriptProperties(); var sid = props.getProperty('TWILIO_ACCOUNT_SID'); var token = props.getProperty('TWILIO_AUTH_TOKEN'); var from = props.getProperty('TWILIO_FROM'); if (!sid || !token || !from) { return { ok: false, sid: null, error: 'Missing Script Properties: TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_FROM' }; } var url = 'https://api.twilio.com/2010-04-01/Accounts/' + encodeURIComponent(sid) + '/Messages.json'; var resp = UrlFetchApp.fetch(url, { method: 'post', contentType: 'application/x-www-form-urlencoded', payload: { To: to, From: from, Body: body == null ? '' : String(body) }, headers: { Authorization: 'Basic ' + Utilities.base64Encode(sid + ':' + token) }, muteHttpExceptions: true }); var code = resp.getResponseCode(); var json = {}; try { json = JSON.parse(resp.getContentText() || '{}'); } catch (e) { json = {}; } if (code >= 200 && code < 300 && json.sid) { return { ok: true, sid: json.sid, error: null }; } return { ok: false, sid: json.sid || null, error: json.message || ('HTTP ' + code) }; }

Example

function textAda() { var result = sendTwilioSms('+15551234567', 'The report is in Drive.'); Logger.log(result); }

Notes

  • Set the three Script Property keys in Project Settings. Do not hard-code the auth token, and do not log it. Require Script Property is the same idea if you want a hard fail at startup.
  • to should already be E.164. Pair with Normalize Phone when the sheet has formatted numbers.
  • Twilio errors (invalid number, unpaid account) come back as {ok: false, error: "..."} rather than a thrown exception, except for Script Properties that are missing, which also return {ok: false}.
  • This does not retry and does not record a send log — the calling script should write the sid or error onto the row so the same person is not texted twice.

Happy Coding!

NitroGAS Chrome Extension

Want this snippet handy inside the Apps Script editor? NitroGAS gives you free snippets — plus optional Co-Pilot when you want a boost (Day Pass — $3, or 1-week, 1-month, or yearly passes — no subscription). Happy Coding!

Get the Extension