Step by Step Guide on Sending & Receiving SMS From / In Salesforce

Sending & Receiving SMS in Salesforce

Here is another interesting step-by-step DIY (do-it-yourself) guide for you – how to send & receive SMS from / in  Salesforce (one way / two way). And you’ll be surprised how easy this is. But first things first. Currently (as of this writing) Salesforce does not provide any native capability to allow you to send SMSes, which means that you will need to use a third party SMS Gateway. You can either select one of the 3rd party products available on AppExchange (which will provide you a more seamless integration with Salesforce) or any other SMS Gateway that allows API calls. In this guide, I will be using Twilio to demonstrate the end-to-end functionality. The steps that we are going to be following are as follows

  • Sign up with Twilio
  • Configure Salesforce to Send SMS
  • Send SMS from Salesforce
  • Configure Salesforce to Receive SMS
  • Receive SMS in Salesforce

Some amount of Apex coding is required to send & receive SMS in Salesforce using Twilio and I have included detailed step by step instruction with screenshots & sample codes on how to do it. Even if you are from a non-development background, you should be able to follow this guide quite easily. But if you do get stuck along the way, leave a comment below and I will try my best to help you

So let’s dig in …

Not an “All Access” Pass Member Yet?

Get Download Access to this & 150+ More Step-by-Step Guides with “All Access” Pass. A simple and single plan to access our entire library of courses, guides, workshops & masterclasses on Salesforce.

Though I have used Twilio in this guide, there are quite a few 3rd Party products on AppExchange that provides the functionality to send SMS from Salesforce. Navigate to URL https://appexchange.salesforce.com/results?keywords=SMS to review the different products available on AppExchange. Each product will have its own way to configure and send SMS. Also worthwhile to mention here is that you can also use Salesforce’s “Marketing Cloud” to send SMSes.

And why would you want to send SMS from Salesforce in the first place? Well, here are some of the use cases that I can think of

  • Send appointment reminders
  • Send updates on orders, deliveries, cases
  • Billing & payment alerts /  reminders
  • Send satisfaction surveys
  • Send mass notifications / alerts
  • Two-factor authentication
  • Send promotional offers / run campaigns
  • Send discount coupons or vouchers
  • Etc…

References & Useful URLs

  1. The Twilio Salesforce Helper Library
  2. Twilio Salesforce Project on GitHub
  3. https://developer.salesforce.com/blogs/developer-relations/2012/02/quick-tip-public-restful-web-services-on-force-com-sites.html
  4. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_rest_code_sample_basic.htm

29 thoughts on “Step by Step Guide on Sending & Receiving SMS From / In Salesforce”

  1. I got it..It got rectifed. I defined another Twilio’s number on my contact record and saved it including the +16502002788 in one of the contact and now after that it started working. So it’s looking the format as well. I saved it to the text field called MobilePhone(Custom phone field created by me). But I think it shouldn’t be the case.

  2. Hello Ashish,

    I hope you will help me. COuld you please let me know how to rectify this error? because I followed every steps and it’s showing this error in the message error on Incoming.
    Error : [
    {
    “errorCode”: “APEX_ERROR”,
    “message”: “System.QueryException: List has no rows for assignment to SObject\n\nClass.receiveSMS.saveSMS: line 32, column 1”
    }
    ]

    There was a failure attempting to retrieve the contents of this URL

    Please help me on this. Waiting forward for your response.
    Thanks,
    Prema

  3. shashank Kulshreshtha

    sir how to authenticate a user via connected apps . I am not installing package for salesforce .Sorry if i am asking silly questions as i am new in integration .

  4. shashank Kulshreshtha

    How can we ensure that the incoming SMSes are from an authorized system. Thankyou for help

  5. “errorCode”: “APEX_ERROR”,
    “message”: “System.QueryException: List has no rows for assignment to SObject\n\nClass.receiveSMS.saveSMS: line 32, column 1”

    I am getting the above error, where am i going wrong? can someone please throw some light at this

  6. In 3 ways you can send SMS from Salesforce.

    In every option, you have pros and cons and choose based on your criteria.

    1. Salesforce default SMS sending
    A. Cost wise very expensive in case of messages.
    B.Some places you have to put your development efforts to make the process automatic.
    C. Currently, it supports only 5 countries

    2. Integrate SMS gateway.
    N number of gateways in a market where you can choose and integrate.

    Pros:
    SMS prices are low.
    Cons:
    If you want to send SMS to different countries Integration is not a good option because International SMS gateway can not give SMS at local Price.
    You have to put your development efforts for dynamic message creation in triggers.
    You have to invest your money and time on every SMS template creation.
    Many of famous gateways allow 1 SMS in 1 API call so you have to handle API limits as Salesforce

    3. You can find App in AppExchange.
    There are a few apps in AppExhnage which are providing complete automation.
    No development efforts.
    Like Email template, you can create SMS template.
    You can send SMS with a workflow where you need not to write triggers.

    If your option is 3 ? You can have a look at our ValueText SMS (https://appexchange.salesforce.com/listingDetail?listingId=a0N3A00000EFoedUAD) App (https://goo.gl/9B6B7d) at AppExchange.

    You can find customer reviews at AppExchange before you use.

    1. Hi Murali,

      1. To the best of my knowledge, Salesforce currently does not allow you to send SMS. You have mentioned that currently, it supports only 5 countries. Can you please point me to the related resource
      2. In case of integrating with API gateway, there is no limit on outbound calls (i.e. sending messages from Salesforce -> external system). The API limits are applicable for inbound calls (i.e. from external systems -> Salesforce)

      Thanks & Regards,
      Ashish

  7. Hey Ashish,
    Thank you again for your work!

    Support asked I leave this here too:

    I used a formula field to create an XML file from data fields in SF to make dynamic voice calls with Play and Say using twimlets.com.

    Detailed notes on the URL formula
    How to build an XML file for Twilio through a URL in a formula field:

    Use Case:
    You need to build a dynamic text-to-voice concatinated with different audio urls (audion hosted on a website). To accomplish this you need to dynamically build a XML url in a formlua field with audio or voice to text.
    What I did was anaylize how Twilio was doing with thier Twimlets https://www.twilio.com/labs/twimlets
    Create field for voice-to-text message (will represent Say)
    Create field for audio url (will represent Play)
    Key factors to consider in your formula
    No blank spaces alowed in the url
    Use %20 to represent a blank space
    audio urls always are treated as “Play”
    Message%5B0%5D=[text or url here] is template for seperating the text and audio urls (more on this later)
    text is always treated as “Say”
    %3A = :
    %2F = /
    Example Working Formula:
    1
    ‘http://twimlets.com/message?Message%5B0%5D=’&SUBSTITUTE(Subject, ” “, “,%20”)&’.%20’&Contact.LastName&’.&Message%5B1%5D=’&SUBSTITUTE(SUBSTITUTE(Url__c,’:’, ‘%3A’),’/’, ‘%2F’)&’&Message%5B2%5D=%20’&Id&’&’
    Formula result:
    1
    http://twimlets.com/message?Message%5B0%5D=Thanks,%20for,%20checking,%20this,%20out.%20Houser.&Message%5B1%5D=https%3A%2F%2Fpink-dog-6501.twil.io%2Fassets%2FSampleAudio_0.4mb.mp3&Message%5B2%5D=%205001I000004ffiT&
    XML created:

    Thanks, for, checking, this, out. Houser.

    https://pink-dog-6501.twil.io/assets/SampleAudio_0.4mb.mp3

    5001I000004ffiT

    What this formula does:
    ‘http://twimlets.com/message?Message%5B0%5D=’&SUBSTITUTE(Subject, ” “, “,%20″)&
    twimlets.com check it out
    Message%5B0%5D=
    ​Notice the ‘0’, this indicates first position
    ‘&SUBSTITUTE(Subject, ” “, “,%20”)&
    Replaces blank spaces with an URL acceptable term = %20
    ‘.&Message%5B1%5D=’&SUBSTITUTE(SUBSTITUTE(Audio_URL__c,’:’, ‘%3A’),’/’, ‘%2F’)&
    (.) pauses
    SUBSTITUTE(SUBSTITUTE(Audio_URL__c,’:’, ‘%3A’),’/’, ‘%2F’)
    the audio url
    This replaces “;” and “/” with the acceptable url terms
    ‘&Message%5B2%5D=%20’&Id&’&’
    I ended the call with another text field called Id
    Other notes:
    Message%5B1%5D = Message[1]
    Message[0] The URL of a media file to , or a string to

    Check out the Twimlets from Twilio here –> https://www.twilio.com/labs/twimlets

  8. Hey Ashish, Thank you for working this all out!

    I was able to take your example and create invocable methods to send out sms and calls.
    I would welcome any feed back too 🙂
    Twilio Support asked that I post it here:

    Twilio Voice Object APEX:
    Invocable =
    public class TwilioCallInvocable {

    @InvocableMethod
    public static void callPhoneService(List voiceIDs) {
    List SelectTwilio_Voice = [Select Id, MobileNumber__c, URL_Build__c from Twilio_Voice__c Where ID in :voiceIDs] ;
    for (Twilio_Voice__c t : SelectTwilio_Voice){
    Map params = new Map {
    ‘To’ => t.MobileNumber__c,
    ‘From’ => ‘+19412137479’, // Fastlife number
    ‘Url’ => t.URL_Build__c
    };

    DoCallout(params);
    }
    }

    @future(callout=true)

    private static void DoCallout(Map params){
    String account = ‘AC6a217d8adb3460b5870c05bc6c0a2471’;
    String token = ‘397c3f614cd3cf783154dc238323c615’;
    TwilioRestClient client = new TwilioRestClient(account, token);
    TwilioCall call = client.getAccount().getCalls().create(params);
    system.debug(‘TwilioCAL’ + call);
    }
    }
    Test=
    @isTest
    private class TwilioCallTest
    {
    @testSetup
    static void testTwilioCallInvocable()
    {
    test.startTest();
    test.stopTest();
    }
    static testMethod void test_callService_UseCase1(){
    Twilio_Voice__c calls = new Twilio_Voice__c();
    calls.MobileNumber__c = ‘17602445555’;
    calls.SAY__c = ‘test message’;
    calls.PLAY__c = ‘https://pink-dog-6501.twil.io/assets/SampleAudio_0.4mb.mp3’;
    insert calls;

    TwilioCallInvocable.callPhoneService(new List());
    }
    }

    Twilio SMS Object APEX:
    Invocable =
    public class TwilioSMSInvocable {
    @InvocableMethod
    public static void callSMSService(List caseIDs ) {
    List SelectTwilio_SMS = [Select Id, MobileNumber__C, Message__c from Twilio_SMS__c Where ID in :caseIDs] ;
    for (Twilio_SMS__c t : SelectTwilio_SMS){
    Map params = new Map {
    ‘To’ => t.MobileNumber__c,
    ‘From’ => ‘+19412137479’,
    ‘Body’ => t.Message__c
    };

    DoCallout(params);
    }
    }

    @future(callout=true)

    private static void DoCallout(Map params){
    String account = ‘AC6a217d8adb3460b5870c05bc6c0a2471’;
    String token = ‘397c3f614cd3cf783154dc238323c615’;
    TwilioRestClient client = new TwilioRestClient(account, token);
    TwilioSMS sms = client.getAccount().getSMSMessages().create(params);
    System.Debug(‘TwilioSMS ‘ + sms) ;
    }
    // if(!Test.isRunningTest())
    // TwilioSMS sms = client.getAccount().getSMSMessages().create(params);

    }
    Test =
    @isTest
    private class TwilioSMSTest
    {
    @testSetup
    static void testTwilioSMSInvocable()
    {
    test.startTest();
    test.stopTest();
    }
    static testMethod void test_callSMSService_UseCase1(){
    Twilio_SMS__c txt = new Twilio_SMS__c();
    txt.MobileNumber__c = ‘17602444355’;
    txt.Message__c = ‘test message’;
    insert txt;

    TwilioSMSInvocable.callSMSService(new List());
    }
    }

  9. Hi Ashish,

    This tutorial is amazing in detail and simplicity to follow. Thank you so much!!!

    Do you happen to know how to setup SMS Chatbot on Salesforce using Twilio?

    1. Hi Seyit,

      Glad that it was helpful. As of now I haven’t explored how to setup chatbot. But that will be another good topic to blog on. I will add it to my to-do list.

      Regards,
      Ashish

  10. THANK YOU! I struggled with the dearth of documentation from Twilio and Salesforce… until I found this step-by-step, which led me to success. The gap in (other) documentation is the part about setting up the remote site. Really appreciate your guidance on this.

  11. While twillio is a great app, it is also sad that salesforce does not have any facility of sending sms on its own.
    Also is there any appexchange app that would help in building a sms triggered functionality.?

  12. Hi vaibhav,

    Thats wounderfull article you have written could be please guide me if you are aware of open Cti lightning for inbound calls that is written by you.

  13. It is giving this error when I am sending message from to salesforce
    [
    {
    “message”: “HTTPS Required”,
    “errorCode”: “UNSUPPORTED_CLIENT”
    }
    ]

  14. Hey Ashish, trying to implement as per the slides but stuck(16 slide) when sending SMS on your mobile no, am not getting any message on mobile and not showing the error message link in Response section.

    Thanks & Regards,
    Vrushali

    1. Hi Vrushali, if there is no error in Twilio’s response, then you should be receiving a SMS. Can you try with another mobile number? If you are still not able to receive the SMS, then the best option will be to contact Twilio support. You may also want to check the Message Log section in Twilio to see if you can find something there.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top
Introducing All Access Pass