Leverage Cloud-Computing, Saas, and Better Business Processes to Drive Change in Your Industry

Clint Lee

Subscribe to Clint Lee: eMailAlertsEmail Alerts
Get Clint Lee: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn

Related Topics: SaaS Journal, Wireless Technology Magazine, Salesforce.com Journal

Salesforce Journal: Blog Post

Send SMS from Salesforce

With Code

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.

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.

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.


01 public with sharing class SendSMSContactExtension {
03 private final Contact contact;
04 private final String TOKEN = 'My Token';
05 private final String SIGNATURE = 'My Signature';
06 private final String ENCODING = 'Seven';
07 public String recipient {get; set;}
08 public String message {get; set;}
10 public SendSMSContactExtension (ApexPages.StandardController stdController) {
11 this.contact = (Contact)stdController.getRecord();
12 } //close constructor
14 public PageReference sendSMS () {
16 if (contact.MobilePhone != null) {
18 //this reformats the phone number as required by the web service; removes all spaces and characters while adding the country code.  Currently
19 //it's hardcoded to insert the U.S. country code prefix.
20 recipient = '1'+ contact.MobilePhone;
21 recipient = recipient.replace('-', '');
22 recipient = recipient.replace('(','');
23 recipient = recipient.replace(')','');
24 recipient = recipient.replace(' ', '');
26 //initialize the SOAP object and call the web service 'Send_Plain'.  Set the timeout.
27 upsidewirelessComWebserviceSms.SMSSoap sms = new upsidewirelessComWebserviceSms.SMSSoap();
28 sms.timeout_x = 2000;
29 upsidewirelessComWebserviceSms.SMSSendResult result = sms.Send_Plain(TOKEN,SIGNATURE,recipient,message,ENCODING);
31 //Create a new task, related to the Contact, if the response is successful.
32 if (result.isOk == true) {
33 Task smsTask = new Task (Type='SMS',
34 WhoID = contact.id,
35 Status = 'Completed',
36 ActivityDate = System.today(),
37 Description = message,
38 Subject = 'SMS Sent'
39 );
40 try {
41 insert smsTask;
42 } catch (System.Dmlexception e) {
43 System.debug('Error: Unable to insert task: ' + e);
44 }
46 return new ApexPages.StandardController(contact).view();
48 } else {
49 //this message will be triggered if the text was not sent successfully.
50 ApexPages.Message didNotSendMsg = new ApexPages.Message(ApexPages.severity.Info, 'Sorry, but the SMS did not send correctly.  Please try again.');
51 ApexPages.addMessage(didNotSendMsg);
52 return null;
53 } //close else
55 } //close first if-statement
56 else {
57 //this message will be triggered if the Contact doesn't have a mobile phone number.
58 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.');
59 ApexPages.addMessage(noMobileMsg);
60 return null;
61 }
63 } //close sendSMS method
65 public PageReference cancel () {
66 //sends the user back to the Contact detail page.
67 PageReference contactPage = new ApexPages.StandardController(contact).view();
68 contactPage.setRedirect(true);
69 return contactPage;
70 } //close cancel method
72 } //close Class


01 <apex:page standardcontroller="Contact" extensions="SendSMSContactExtension" tabStyle="Contact" >
02 <span style="font-weight:bold; color:red">
03 <apex:messages />
04 </span>
05 <apex:form >
06 <apex:pageBlock title="Send SMS to {!contact.name}">
07 <apex:pageBlockSection >
08 <apex:pageBlockSectionItem >
09 <apex:outputLabel for="message" value="Enter your message:" />
10 <apex:inputText id="message" value="{!message}" size="80" required="true" />
11 </apex:pageBlockSectionItem>
12 <apex:pageBlockSectionItem >
13 <apex:outputLabel for="recipient" value="Mobile Number" />
14 <apex:outputText id="recipient" value="{!contact.MobilePhone}" />
15 </apex:pageBlockSectionItem>
16 <apex:pageBlockSectionItem >
17 <apex:commandButton action="{!sendSMS}" value="Send" id="sendButton" />
18 <apex:commandButton action="{!cancel}" value="Cancel" id="cancelButton" />
19 </apex:pageBlockSectionItem>
20 </apex:pageBlockSection>
21 </apex:pageBlock>
22 </apex:form>
23 </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.

More Stories By Clint Lee

Clint is a Principal and Founder of The Flywheel Group, a premier provider of innovative solutions to the franchise industry. The FranchiseFlywheel™ application was developed out of the industry's need for a cutting-edge and affordable franchise management tool for franchisors. Spending several years in the franchise industry directing daily activities related to franchise and business development processes, marketing, lead-generation, and contract administration, and an understanding of the needs of peers and colleagues, led to the development of the application. The Flywheel Group is focused on improving best practices and driving change in the franchise industry by introducing industry-leading solutions and working with its clients to re-engineer business processes that will ultimately enhance revenue and improve bottom line efficiency. Clint actively writes and shares his thoughts on the Flywheel Blog.