Remote Site Settings:
Sample Code:
- public class TwilioSMSHandler {
- public static void send( String strPhone ) {
- ErrorResponseWrapper erw;
- String smsBody = ‘Test Message’;
- String strMediaURL = ‘IMAGE_URL_WITH_EXTENSION’;
- final String fromNumber = ‘FROM_NUMBER’;
- String account = ‘ACCOUNT_SID’;
- String token = ‘ACCESS_TOKEN’;
- HttpRequest req = new HttpRequest();
- req.setEndpoint( ‘https://api.twilio.com/2010-04-01/Accounts/’ + account + ‘/Messages’ );
- req.setMethod( ‘POST’ );
- req.setHeader( ‘Content-Type’, ‘application/x-www-form-urlencoded’ );
- Blob headerValue = Blob.valueOf( account + ‘:’ + token );
- String authorizationHeader = ‘BASIC ‘ +
- EncodingUtil.base64Encode( headerValue );
- req.setHeader( ‘Authorization’, authorizationHeader );
- if ( strPhone != null ) {
- req.setBody( ‘To=’ + EncodingUtil.urlEncode( strPhone, ‘UTF-8’ ) + ‘&From=’ + fromNumber + ‘&Body=’ + smsBody + ‘&MediaUrl=’ + strMediaURL );
- try {
- Http http = new Http();
- HTTPResponse res = http.send(req);
- System.debug( ‘Response Body is ‘ + res.getBody() );
- if ( res.getStatusCode() == 201 )
- system.debug( ‘Twilio Success ‘ + strPhone );
- else {
- system.debug( ‘Twilio failed ‘ + strPhone );
- erw = ( ErrorResponseWrapper )json.deserialize( res.getBody(), ErrorResponseWrapper.class );
- system.debug( ‘Twilio error ‘ + erw.message );
- }
- } catch( Exception e ) {
- system.debug( ‘Exception is ‘ + e );
- }
- }
- }
- public class ErrorResponseWrapper {
- String code;
- String message;
- String moreInfo;
- String status;
- }
- }