Send SMS from Salesforce – Build Your Own

[ Update ]

We recently released an application on the AppExchange that provides the ability to send and receive SMS messages from Salesforce.  If you’re looking for a pre-built solution you can find it here – Simple SMS

Otherwise, if you’re just looking to flex your development muscle on the Force.com platform keep reading for how I built this older solution.

Ever send SMS messages to your Contacts and Leads?

I recently had a conversation with a fairly new Salesforce customer who wanted to send SMS messages to their leads and contacts.  They had been using another CRM system that gave them this ability and it’s an integral part of the way they communicate with leads and prospects.  The great thing about Salesforce and the Force.com platform is that there are multiple ways to achieve this goal.  A quick search of the AppExchange will bring up a number of options.  Or, if one of these options doesn’t fit your needs you could build it on your own.  With my curiosity peaked, I chose the latter option and decided to spend some time looking for a way to build this functionality myself.  Below, I’ll share with you the process and code that I put together.

Step 1 – Find an SMS Gateway company

According to Wikipedia, “An SMS gateway is a device or service offering SMS transit, transforming messages to mobile network traffic from other media, or vice versa, allowing transmission or receipt of SMS messages with or without the use of a mobile phone.”  If you Google around for “SMS Gateway” you’ll find a number of companies offering this service.  I decided on a company called Upside Wireless primarily because the pricing options appeared straight-forward and flexible, and there were API docs available for sending messages via SOAP and HTTP.  It only took a few minutes to set up a free account on their website.

**UPDATE: After creating your account with Upside Wireless, you’ll need to request API access to the account.  Visit their Contact Us page and use the form to request that API access be turned on.

Step 2 – Get the WSDL

We’ll use the SOAP method to send messages to the Upside Wireless web service, so the first step is to download the Upside Wireless SOAP WSDL here.  Then, create an APEX class from this WSDL by going to Setup-> Develop-> API -> Generate from WSDL.  You’ll need to do this in either a Developer or Sandbox account.  Parsing the WDL will generate some errors while because there are unaccepted items like multiple portTypes, etc that need to be removed.  It took a few attempts before I was able to complete the parsing successfully.  My final version of the WSDL file can be downloaded here.

**UPDATE: Upside’s API must have changed slightly since I posted this and the original WSDL will now throw an error due to a missing element.  You can skip the part of generating the class from the WSDL and just download the complete version of the web service class here.

Step 3 – The Basic Design

The basic design is to create a “Send SMS” button that resides on the Contact detail page.  When the button is clicked, a Visualforce page lets you type in the message and press send.  If the send is not successful, an error message will appear.  If the SMS is sent successfully, a task will be created to record this activity and the user will be sent back to the Contact’s detail page.

Here is the APEX Class and VF Page.  You’ll notice this is for Contacts, but it can essentially be duplicated for use with Leads.

APEX CLASS

public with sharing class SendSMSContactExtension {

    private final Contact contact;
    private final String TOKEN = 'My Token';
    private final String SIGNATURE = 'My Signature';
    private final String ENCODING = 'Seven';
    public String recipient {get; set;}
    public String message {get; set;}

    public SendSMSContactExtension (ApexPages.StandardController stdController) {
        this.contact = (Contact)stdController.getRecord();
    } //close constructor

    public PageReference sendSMS () {

       if (contact.MobilePhone != null) {

          //this reformats the phone number as required by the web service; removes all spaces and characters while adding the country code.  Currently
          //it's hardcoded to insert the U.S. country code prefix.
          recipient = '1'+ contact.MobilePhone;
          recipient = recipient.replace('-', '');
          recipient = recipient.replace('(','');
          recipient = recipient.replace(')','');
          recipient = recipient.replace(' ', '');

    	  //initialize the SOAP object and call the web service 'Send_Plain'.  Set the timeout.
          upsidewirelessComWebserviceSms.SMSSoap sms = new upsidewirelessComWebserviceSms.SMSSoap();
          sms.timeout_x = 2000;
          upsidewirelessComWebserviceSms.SMSSendResult result = sms.Send_Plain(TOKEN,SIGNATURE,recipient,message,ENCODING);

          //Create a new task, related to the Contact, if the response is successful.
          if (result.isOk == true) {
             Task smsTask = new Task (Type='SMS',
        							  WhoID = contact.id,
        							  Status = 'Completed',
        							  ActivityDate = System.today(),
        							  Description = message,
        							  Subject = 'SMS Sent'
        							 );
        	 try {
        	    insert smsTask;
        	 }  catch (System.Dmlexception e) {
        	   	   System.debug('Error: Unable to insert task: ' + e);
        	     }

        	 return new ApexPages.StandardController(contact).view();

          } else {
           	   //this message will be triggered if the text was not sent successfully.
        	   ApexPages.Message didNotSendMsg = new ApexPages.Message(ApexPages.severity.Info, 'Sorry, but the SMS did not send correctly.  Please try again.');
        	   ApexPages.addMessage(didNotSendMsg);
        	   return null;
             } //close else

       } //close first if-statement
          else {
    	     //this message will be triggered if the Contact doesn't have a mobile phone number.
    	  	 ApexPages.Message noMobileMsg = new ApexPages.Message(ApexPages.severity.Info, 'This Contact does not have a mobile phone number.  Please update the mobile number and try again.');
    	  	 ApexPages.addMessage(noMobileMsg);
    	  	 return null;
    	  }

    } //close sendSMS method

    public PageReference cancel () {
       //sends the user back to the Contact detail page.
       PageReference contactPage = new ApexPages.StandardController(contact).view();
       contactPage.setRedirect(true);
       return contactPage;
    } //close cancel method

} //close Class

VISUALFORCE PAGE

<apex:page standardcontroller="Contact" extensions="SendSMSContactExtension" tabStyle="Contact" >
 <span style="font-weight:bold; color:red">
 <apex:messages />
 </span>
 <apex:form >
 <apex:pageBlock title="Send SMS to {!contact.name}">
 <apex:pageBlockSection >
 <apex:pageBlockSectionItem >
 <apex:outputLabel for="message" value="Enter your message:" />
 <apex:inputText id="message" value="{!message}" size="80" required="true" />
 </apex:pageBlockSectionItem>
 <apex:pageBlockSectionItem >
 <apex:outputLabel for="recipient" value="Mobile Number" />
 <apex:outputText id="recipient" value="{!contact.MobilePhone}" />
 </apex:pageBlockSectionItem>
 <apex:pageBlockSectionItem >
 <apex:commandButton action="{!sendSMS}" value="Send" id="sendButton" />
 <apex:commandButton action="{!cancel}" value="Cancel" id="cancelButton" />
 </apex:pageBlockSectionItem>
 </apex:pageBlockSection>
 </apex:pageBlock>
 </apex:form>
</apex:page>

In the APEX class you’ll notice two variables called Token and Signature. These are used for authentication by Upside Wireless and are passed in as arguments to the Send_Plain method.  To get your Token and Signature, go here and then enter your username and password and click Invoke – obviously you’ll need to have created your account prior to doing this.  Copy and paste your Token and Signature into the class.

Step 4 – Create the Button

To create the Send SMS button, go to Setup-> Customize -> Contacts -> Buttons and Links.  Create a new detail page button called ‘Send SMS’.  For Content Source select Visualforce Page.  Then, select the page from the drop-down menu.

Go to Setup -> Customize -> Contacts -> Page Layouts.  Select your page layout and click Edit.  Add the Send SMS button to your Custom Buttons section.

Step 5 – Add Remote Site Setting

Before you can send SMS’s, you’ll need to add the Upside Wireless web service endpoint to your remote site settings.  Go to Setup-> Security Controls-> Remote Site Settings.  Add a new Remote Site with this URL address – http://api.upsidewireless.com.

Step 6 – Send SMS

Now you’re ready to send SMS’s from any Contact detail page.  Just make sure that you have a mobile number for the Contact.  When opening your free account you do have a small amount of SMS credits to work with.

I’d suggest reading through the API docs to familiarize yourself with the available methods regarding testing, sending through a dedicated phone number, etc.

This is just a rudimentary design primarily for the purpose of demonstrating capabilities.  However, it is another testament to the power of the Force.com platform and the ability to quickly put together something that works.

I hope this has been helpful and, as always, would be happy to hear any feedback.

Tags: , , , ,

Send SMS from Salesforce – Build Your Own

32 Responses

  1. Nice walk through!!

    I just clicked send and got this permission error:
    Web service callout failed: WebService returned a SOAP Fault: System.Web.Services.Protocols.SoapException: No Permission to: sms.send.plain at SMS.Send_Plain(String token, String signature, String recipient, String message, SmsEncoding encoding) faultcode=soap:Client faultactor=

    My token and signiture are correct. And I can’t think of any other permission issues.

    Any ideas welcome!

    Cheers,
    Adam

    Adam Dry August 24, 2010 at 6:20 am #
  2. Adam,

    I updated this post slightly as a couple of things have changed. Your error is most likely due to the fact that you need to request API access on your account from UpsideWireless. You’ll see where that’s been updated above.

    You can also download the upsidewirelessComWebserviceSMS Apex Class that I posted. Copy and paste it over the class that you generated from the WSDL, as there were a few things that changed.

    Hope that helps.

    Clint

    Clint Lee August 24, 2010 at 10:05 am #
  3. Hi, I tried the same steps you provided and got this error.

    Visualforce Error
    Help for this Page

    System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: System.Web.Services.Protocols.SoapException: Invalid Authentication Parameters at SMS.Send_Plain(String token, String signature, String recipient, String message, SmsEncoding encoding) faultcode=soap:Client faultactor=

    Class.upsidewirelessComWebserviceSms.SMSSoap.Send_Plain: line 192, column 13 Class.SendSMSContactExtension.sendSMS: line 29, column 65 External entry point

    Umesh July 11, 2011 at 7:23 am #
  4. Hi Clint,

    Thanks a lot to post this simple steps to Sending Message.
    I achieved but i would like to send SMS in bulk.What i want to do is i would like to select 10 Contacts at a time and send Bulk SMS to all those contacts…Can you suggest me how to achieve this.

    Thanks,

    surya

    Surya July 30, 2012 at 2:27 am #
  5. Hi, I tried the same steps you provided and got this error.

    System.CalloutException: IO Exception: Unauthorized endpoint, please check Setup->Security->Remote site settings. endpoint = http://api.upsidewireless.com/soap/SMS.asmx
    Error is in expression ‘{!sendSMS}’ in component in page sms

    pradeep July 31, 2012 at 3:11 am #
  6. Hi Pradeep,

    Did you complete Step 5 above? You have to add that url to your Remote Site Settings, otherwise you will receive an Unauthorized Endpoint error.

    Clint

    Clint Lee July 31, 2012 at 7:06 am #
  7. Hi Client lee,

    I am getting error when i save the webservice class which is in step 2. I am getting the error as

    Error: Compile Error: Method does not exist or incorrect signature: WebServiceCallout.invoke(upsidewirelessComWebserviceSms.SMSSoap, upsidewirelessComWebserviceSms.HLR_Lookup_element, MAP, LIST) at line 133 column 13

    Can you please help me out.

    Thanks

    lakshmi August 14, 2012 at 5:59 am #
  8. Are you referring to the link posted in the updated part of Step 2?

    Try compiling this class – http://www.clintslee.com/wp-content/uploads/2010/09/upsidewirelessComWebserviceSms.txt

    Clint Lee August 14, 2012 at 10:05 am #
  9. Hi Clint lee,

    Yes i have used the same code which you have given.. then it gives the error as
    Error: Compile Error: Method does not exist or incorrect signature: WebServiceCallout.invoke(upsidewirelessComWebserviceSms.SMSSoap, upsidewirelessComWebserviceSms.HLR_Lookup_element, MAP, LIST) at line 133 column 13

    Please help me out…

    lakshmi August 16, 2012 at 3:32 am #
  10. Hi Clint Lee,

    I am able to send message from salesforce. How can we receive message in salesforce. I am trying to built a two-way communication application.

    Thanks,
    Varun

    Varun October 23, 2012 at 3:38 am #
  11. Hi i followed the same but i am getting an error message

    Pls help (URGENT)
    Visualforce Error
    Help for this Page

    System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: System.Web.Services.Protocols.SoapException: Invalid Authentication Parameters at SMS.Send_Plain(String token, String signature, String recipient, String message, SmsEncoding encoding) faultcode=soap:Client faultactor=
    Error is in expression ‘{!sendSMS}’ in page sms1

    Class.upsidewirelessComWebserviceSms.SMSSoap.Send_Plain: line 192, column 1
    Class.SendSMSContact.sendSMS: line 30, column 1

    anand July 31, 2013 at 2:49 am #
  12. HI I am also facing same error , Please help me out

    System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: System.Web.Services.Protocols.SoapException: No Permission to: sms.send.plain at SMS.Send_Plain(String token, String signature, String recipient, String message, SmsEncoding encoding) faultcode=soap:Client faultactor=
    Error is in expression ‘{!sendSMS}’ in page sms

    Class.upsidewirelessComWebserviceSms.SMSSoap.Send_Plain: line 190, column 1
    Class.SendSMSContactExtension.sendSMS: line 29, column 1

    Haritha September 14, 2013 at 4:04 pm #
  13. I am getting an Error like “Invalid Authentication Parameters at SMS.Send_Plain(String token, String signature, String recipient, String message, SmsEncoding encoding) faultcode=soap:Client faultactor=”
    In apex class i’m specifying Token and Signature Correctly but you have to specify the ENCODE =’Seven’ in that apex class,what value i will place in that ENCODE

    Swathi April 9, 2014 at 7:40 am #
  14. Hi,

    Is it possible to provide the corrected WSDL file.

    Praveen January 13, 2015 at 9:44 pm #
  15. Error: Compile Error: Incompatible types since an instance of SObject is never an instance of contact at line 15 column 24

    15. this.contact = (Contact)stdController.getRecord();

    harish January 21, 2016 at 6:03 am #
  16. I have been checking out many of your articles and i must say pretty nice stuff. I will definitely bookmark your blog.

    ????? January 22, 2017 at 3:08 am #
  17. You could certainly see your enthusiasm within the paintings you write. The sector hopes for even more passionate writers like you who aren’t afraid to mention how they believe. At all times go after your heart.

    ???? January 22, 2017 at 3:08 am #
  18. Admiring the dedication you put into your blog and in depth information you present. It’s great to come across a blog every once in a while that isn’t the same old rehashed material. Wonderful read! I’ve bookmarked your site and I’m adding your RSS feeds to my Google account.

    ???? January 22, 2017 at 3:09 am #
  19. I don? even know how I ended up here, but I thought this post was great. I do not know who you are but certainly you are going to a famous blogger if you are not already 😉 Cheers!

    ???? January 22, 2017 at 3:10 am #
  20. Good blog! I really love how it is simple on my eyes and the data are well written. I am wondering how I could be notified when a new post has been made. I have subscribed to your feed which must do the trick! Have a great day!

    ????? January 22, 2017 at 3:10 am #
  21. Thanks for the good writeup. It in fact used to be a enjoyment account it. Glance complex to far introduced agreeable from you! However, how could we keep in touch?

    ???????? January 22, 2017 at 3:10 am #
  22. This design is spectacular! You definitely know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Fantastic job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!

    ????? January 22, 2017 at 3:11 am #
  23. I am continuously looking online for ideas that can benefit me. Thx!

    ???? January 22, 2017 at 3:12 am #
  24. This web page is known as a stroll-by for all of the information you wanted about this and didn? know who to ask. Glimpse here, and you?l positively uncover it.

    ???? January 22, 2017 at 3:13 am #
  25. you have got a terrific blog here! would you prefer to make some invite posts on my weblog?

    ?????? January 22, 2017 at 3:13 am #
  26. It is really a nice and helpful piece of information. I am glad that you shared this helpful info with us. Please keep us informed like this. Thank you for sharing.

    ????? January 22, 2017 at 3:13 am #
  27. Thanks a bunch for sharing this with all of us you really know what you’re talking about! Bookmarked. Kindly also visit my site =). We could have a link exchange agreement between us!

    ????? January 22, 2017 at 3:13 am #
  28. you’ve an important weblog here! would you prefer to make some invite posts on my blog?

    ?????? January 22, 2017 at 3:14 am #
  29. Hello there, just turned into alert to your blog via Google, and located that it is really informative. I am going to be careful for brussels. I will be grateful if you continue this in future. Numerous other folks will be benefited out of your writing. Cheers!

    ????? January 22, 2017 at 3:14 am #
  30. Very good website you have here but I was wanting to know if you knew of any forums that cover the same topics talked about in this article? I’d really love to be a part of community where I can get suggestions from other knowledgeable people that share the same interest. If you have any suggestions, please let me know. Bless you!

    ????? January 22, 2017 at 3:16 am #
  31. It? really a great and useful piece of info. I am glad that you shared this useful information with us. Please keep us up to date like this. Thanks for sharing.

    ????? January 22, 2017 at 3:16 am #
  32. You can certainly see your expertise in the paintings you write. The arena hopes for more passionate writers such as you who are not afraid to say how they believe. At all times follow your heart.

    ????? January 22, 2017 at 3:16 am #

Leave a Reply