Skip to content

Instantly share code, notes, and snippets.

@papoms
Created April 11, 2015 07:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save papoms/7e64c60b39ecf442d5ed to your computer and use it in GitHub Desktop.
Save papoms/7e64c60b39ecf442d5ed to your computer and use it in GitHub Desktop.
Twilio SMS API for Google App Scripts - Send a Textmessage from Google Docs
/**
* Sends a Short Message using the Twilio REST API
*
* It uses UrlFetchApp.fetch to send a POST request with Basic Authentication to the Messages list resource URI
* See https://www.twilio.com/docs/api/rest/sending-sms for documentation of the Twilio Api Call
* See https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app for Documentation on UrlFetchApp
*
* Get Your Api Credentials from https://www.twilio.com/user/account/settings
*
* @param {String} to The Recipients Number e.g. '+1323452345'
* @param {String} body The message Body - Text to send
* @param {String} from Number to send from e.g. '+1323452345'. Get this from your Twilio Account Page
* @param {String} accountSID Twilio AccountSID
* @param {String} authToken Twilio AuthToken
*/
function sendSMS(to, body, from, accountSID, authToken){
var headers = {
"Authorization" : "Basic " + Utilities.base64Encode( accountSID + ':' + authToken )
};
var url = 'https://api.twilio.com/2010-04-01/Accounts/' + accountSID + '/Messages.json';
var payload = {
"To" : to,
"From" : from,
"Body" : body
}
var params = {
"method" : "POST",
"payload" : payload,
"headers" : headers
};
var response = UrlFetchApp.fetch(url, params);
var twilioJSON = JSON.parse(response.getContentText());
/* Twilio returns a Message id 'sid' for successfully queued / created messages.
* It does not necessarly mean the message was send successfully but at least it indicates
* that our request was well formated and accepted.
*/
if ( twilioJSON.hasOwnProperty('sid') ) {
/* return twilioJSON.sid; Could be used to return the SID of the created message for further processing. For now just return true or false */
return true;
} else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment