top of page
Writer's pictureC. Baghel

SEND SMS FROM SALESFORCE BY USING TWILIO

Updated: Nov 8, 2023



Twilio: Twilio is a cloud communications platform that provides APIs for developers to integrate messaging, voice, and video capabilities into their applications. On the other hand, Salesforce is a customer relationship management (CRM) platform that helps businesses manage their customer data, sales, and marketing activities.


Way to send SMS from salesforce by using Twilio-

  1. By using API

  2. By using flow

  3. By using process builder


In this blog, I will be showing you how to integrate Twilio's SMS API with Salesforce and send SMS messages directly from your Salesforce org.


Send SMS from Salesforce by using API


Step 1: Create Twilio Account To Get an API Credential


First, create a trial account on Twilio.com and then get the API credentials for making the API calls. Also, create a phone number for your account from which you can send the SMS. In the trial account, you can send the SMS only to the verified numbers; so, you must verify all the phone numbers you will send the SMS.

  • Go to https://www.twilio.com/try-twilio & click Start for free

  • Provide detailed Name, Last Name, Email, and Password, and accept the condition then click the start for the free trial button.

  • Then click to send verification of email after that you will get an email for verification.

  • Click verify email and provide your email and password to sign up.

  • Then provide a mobile number to get sms code. You can choose your country and enter your temporary number.

  • After that, you get Account SID & Auth tokens for communicating with Salesforce.

  • After that go to the Messaging section and click SMS after that you will get a number that is used to send sms. Similar to the image given below:

Step 2: Remote Site Settings

To make remote site settings in Salesforce, follow these steps:

  1. Login to your Salesforce account.

  2. Click on the Gear icon in the top right corner of the page and select "Setup".

  3. In the left navigation panel, go to Security Controls > Remote Site Settings.

  4. Click on the "New Remote Site" button.

  5. Fill in the required information such as Remote Site Name, Remote Site URL, and Description.

  6. Check the "Disable Protocol Security" checkbox if you want to allow insecure connections to this remote site.

  7. Click on the "Save" button to save the remote site settings.



Step 3: Create an Apex class(SendMessage)

Go to the developer console and create one apex class in this step. In the class, create SendMessage and pass Twilio Account SID and Account Token in place of accountSid and token.


SendMessage.cls

public class SendMessage {
    /**
    * This method aims to send message by using authentication information
    * @param phNUmber, smsBody, fromPhoneNumber
    * @return Message
    */
    @AuraEnabled
    public static String processSms(String toPhoneNumber, String smsBody, String fromPhoneNumber) {
        HttpRequest request = new HttpRequest();
        Http http = new Http();
        HTTPResponse response = new HTTPResponse();
        request.setEndpoint('callout:Twilio_Credentail_data');
        request.setMethod('POST');
        request.setBody(
            'To=' + EncodingUtil.urlEncode(toPhoneNumber, 'UTF-8') + '&From='
            + EncodingUtil.urlEncode(fromPhoneNumber,'UTF-8') + '&Body=' + smsBody
            );
        response = http.send(request);
        if (response.getStatusCode() == 201) {
            return System.Label.SUCCESS_MESSAGE;
        }
        else {
           return System.Label.ERROR_MESSAGE;
        }
    }
}

Step-4: Create Aura Component

In this step, we create an aura component for the UI part so users can interact and send SMS by entering their phone number and SMS in the input.

SendMessageComp.cmp


<aura:component controller="SendMessage" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global">
    <aura:attribute name="toPhoneNumber" type="String"/>
    <aura:attribute name="smsBody" type="String"/>
    <aura:attribute name="fromPhoneNumber" type="String"/>
    <aura:attribute name="showSpinner" type="Boolean" default="false"/>
    <aura:attribute name="MsgSentOrNot" type="String"/>
    <lightning:card>
        <div>
            <lightning:icon iconName="doctype:image" alternativeText="Image file" title="Image"/>
            <h1>
              <span>{!$Label.c.SEND_SMS_TITLE}</span>
            </h1>
        </div>
    </lightning:card>
    <lightning:card>
        <lightning:icon iconName="standard:sms" alternativeText="Approved" title="Approved"/>
        <div class="row">
           <lightning:input label="To Phone Number" name="toPhoneNumber" class="fieldvalidate" value="{!v.toPhoneNumber}"/>
           <lightning:input label="SMS Body" name="smsBody" class="fieldvalidate" value="{!v.smsBody}" />
           <lightning:input label="From Phone Number" name="fromPhoneNumber" class="fieldvalidate" value="{!v.fromPhoneNumber}"/>
        </div>
        <lightning:button class="slds-align_absolute-center" variant="success" label="Send" title="Brand action"onclick="{! c.sendMessage }"/>
        <aura:if isTrue="{!v.showSpinner}">
            <div class="spinner">{!$Label.c.SPINNER_MESSAGE}</div>
        </aura:if>
    </lightning:card>
</aura:component>

SendMessageCompController.js

({
    sendMessage: function(component, event, helper) {
        helper.sendMessage(component, event, helper);
    }
})

SendMessageCompHelper.js

({
    sendMessage : function(component, event, helper) {
        component.set("v.showSpinner", true);
        let action = component.get("c.processSms");
        action.setParams({
            "toPhoneNumber" : component.get("v.toPhoneNumber"),
            "smsBody" : component.get("v.smsBody"),
            "fromPhoneNumber" : component.get("v.fromPhoneNumber")
        });
        action.setCallback(this, function(response) {
            component.set("v.showSpinner", false);
            component.set("v.MsgSentOrNot", response.getReturnValue());
            helper.messageData(response.getReturnValue());
        });
        $A.enqueueAction(action);
    },

    messageData : function(message) {
        var toastEvent = $A.get("e.force:showToast");
        var successMessage = $A.get("$Label.c.SUCCESS_MESSAGE");
        if (message === successMessage) {
            toastEvent.setParams({
                title : 'Info',
                message : message,
                duration :'5000',
                key : 'info_alt',
                type : 'success',
                mode : 'dismissible'
            });
        }
        else {
            toastEvent.setParams({
                title : 'Info',
                message : message,
                duration :'5000',
                key : 'info_alt',
                type : 'error',
                mode : 'dismissible'
            });
        }
        toastEvent.fire();
    }
});

Step-5: Test the functionality

For the testing, we must provide “To Phone No” and From No. you can set these up using the below links:

Note: To Phone No should be your Twilio registered number and From No. would be the generated number assigned to you by Twilio.



This is the way you can send SMS from Salesforce by using Twilio. Happy!! to help you add to your knowledge. You can leave a comment to help me understand how the blog helped you. If you need further assistance, please get in touch with us at Reach us. You can click "Reach Us" on the website and share the issue with me.


Happy Coding! You can leave a comment to help me understand how the blog helped you. If you need further assistance, please contact us. You can click "Reach Us" on the website and share the issue with me.



Blog Credit:

C. Baghel

Salesforce Developer

Avenoir Technologies Pvt. Ltd


Reach us: team@avenoir.ai



Comments


bottom of page