How do I send SMSes from Salesforce?

A number of companies provide SMS services that you pre-pay for and invoke using a REST API. To send an SMS is usually quite simple e.g.:

private static final String ENDPOINT = 'https://api.twilio.com';
private static final String VERSION = '2010-04-01';

public void send(String toNumber, String message) {

    // Custom setting containing SMS service information
    SmsConfiguration__c config = SmsConfiguration__c.getInstance();

    HttpRequest req = new HttpRequest();
    req.setHeader('X-Twilio-Client', 'salesforce-' + VERSION);
    req.setHeader('User-Agent', 'twilio-salesforce-' + VERSION);
    req.setHeader('Accept', 'application/json');
    req.setHeader('Authorization', 'Basic '+ EncodingUtil.base64Encode(Blob.valueOf(
            config.AccountSid__c + ':' + config.AuthToken__c)));
    req.setEndpoint(ENDPOINT + '/' + VERSION + '/Accounts/' + config.AccountSid__c
            + '/SMS/Messages');
    req.setMethod('POST');
    req.setBody(''
           + 'From=' + EncodingUtil.urlEncode(config.FromNumber__c, 'UTF-8')
           + '&To=' + EncodingUtil.urlEncode(toNumber, 'UTF-8')
           + '&Body=' + + EncodingUtil.urlEncode(message, 'UTF-8')
           );
    HttpResponse res = new Http().send(req);
    if (res.getStatusCode() >= 200 && res.getStatusCode() < 300) {
        // OK
    } else {
        // Error
    }
}

You could expose your own simple @RestResource endpoint that you call from the client side to in turn call the above code on the server:

@RestResource(urlMapping='/sms')
global with sharing class SmsRest {
    @HttpPost
    global static void doPost(String toNumber, String message) {
        new SmsSender().send(toNumber, message);
    }
}

or that could say accept the ID of the Contact to send to and query to get the number and then send.


I built a solution for an NPO using Twilio - you can see the code on GitHub

Twilio has a pre-built library for Salesforce that enables you to invoke their REST API for sending messages that the code above takes advantage of.