Sending SMS With Scala
Want to learn how you can send an SMS using Scala? Read through this article and learn how to choose a provider and integrate your applications smoothly.
Join the DZone community and get the full member experience.
Join For FreeAs you probably guessed from the title above, sending an SMS is the main topic of today's article. I started the articles with a few words about SMS service providers, then I explained what you may take into consideration while choosing the one for you, why I choose the Vonage, and added some more details about this platform. I also provided a simple step-by-step implementation of SMS sender service in Scala.
Before we start — a quick disclaimer
Here you can find only the most interesting code samples. The full source code is available in my GitHub repository.
Why Sending Automatic SMS Matter Today?
In our applications, we often need to send users different types of notifications. There are many reasons why we do so. For instance, we have to notify the users that the product they want is now available or that they have to pay an overdue invoice for our services. Although in most cases, sending emails seems to be the option used by companies (at least in my opinion as a user), there are cases when SMS notifications can be more useful. For cases in which the time of user’s reaction is crucial, such notifications may be the only reasonable option.
How to Choose SMS Service Provider
In case of sending emails, we just need to add our mailbox credentials and our application should be able to send an email without more complex configurations. Unfortunately, when it comes to SMS messages, it is not so easy. Here we are forced, unless somehow you have a private tool that can send SMS messages, to choose a service provider which will actually get our messages and forward it to the outside world.
There are many providers out there: Twillio, Nexmo/Vonage, ClickSend or even SNS offered by AWS just to name a few. Because there are so many providers, we can have serious problems while choosing the one worth our trust.
There are different things that we expect from our provider depends on what is our scale. For a big company that send lots of notifications, the main factors in choosing the provider would be different than the ones taken into consideration by smaller companies or someone’s pet projects. Things like special discounts or some customizations may be the most important features offered by a provider.
SMS Provider Checklist
Nevertheless, there are factors that every reasonable company should keep in mind and which should be vital while choosing a provider.
Documentation, even the best API without documentation is at least hard to use.
Amount of boilerplate code needed to send and process a single message.
Ease of integration - is it enough to have an account and API key or maybe you have to do more? It may not sound important, but any additional configuration is potentially problem to solve and a thing that may break in the most unexpected moment.
Supported languages. It may be not the best idea to choose a provider which does not support and languages known to you or your coworkers. Of course, it depends on the scale of your project.
Volume and latency of messages can be handled/guaranteed by a provider. There can be very specific time restrictions on our notifications and for sure we want to choose the provider which will help us to meet them.
Renown of provider on the market. Sometimes it may be better to choose a less known provider and help it grow but, in most cases, old (but not ancient) and tested solutions are the best ones.
For example, in my case, I choose Vonage as my provider and it will be used here as an example. My main motivation was quite a good price per message, small amount of boilerplate, ease of integration (I needed only API key), and support for Java.
After this slightly long introduction, it is time for the main course of the day. However, before we start a few words about Vonage itself.
What Is Vonage?
Vonage is a regular and quite well-known service provider previously called Nexmo. Apart from SMS API it offers other APIs like voice messages, 2 factor auth SMS or video messages. It has rather clear pricing rules and allows you to easily check prices of sending SMS to and from different countries. For me (sending to and from Poland) it was slightly cheaper then Twillio.
After creating an account you are given 2 $ which you can spend on various services. Till the first payment, your account is in free/demo mode and Vonage will adds [FREE SMS DEMO, TEST MESSAGE]
at the end of each message you send. Additionally, you are able to send messages only to numbers verified on your account. Unfortunately, payment options are restricted to credit cards, bank transfers and PayPal.
Moreover, you have a standard send messages log (UX is pretty nice), some account balance alerts and that is all, from what I see there is nothing extraordinary there. There is also Brand and Campaigns feature but I did not have time to read more about it, besides, it is out of scope of this article.
Let’s Start Implementing
While writing this article I assumed that anyone reading it has basic knowledge about Scala, SBT and feels comfortable with some IDE (as usual I recommend InteliJ).
1. Add Vonage client library to your build.sbt file
libraryDependencies += "com.vonage" % "client" % "6.2.0"
It is a wrapper for Vonage REST API calls so there is no magic inside, only some Object Mapper and Apache HTTP calls.
2. Create a sort of main class which will run our application. I choose to extend App class but you can also try and create plain, old main method. The results should look more or less like this:
object Runner extends App
3. The next step is creating an object named Sender, which will contain all code needed to handle sending our text message, with method named “send” of signature shown below.
x
send(receiverNumber: String, message: String, senderName: String): Boolean
4. Here we create our provider client, which is responsible for forwarding our requests to provider service. Vonage requires specifying our API key and secret, both are available in an account setting on web page.
xxxxxxxxxx
VonageClient.builder()
.apiKey("")
.apiSecret("")
.build
5. And now it is time for the most important code fragment of today’s article - we will implement “send” message.
xxxxxxxxxx
val smsMessage: TextMessage = new TextMessage(senderName, receiverNumber, message)
val response: SmsSubmissionResponse = client.submitMessage(smsMessage)
val responseStatus = response.getMessages.get(0).getStatus
if (MessageStatus.OK.equals(responseStatus)) true
else false
Additionally, I want to describe TextMessage
class. It represents the message we want to send and takes 3 parameters of type string:
from, SMS sender’s name displayed in message received by users, limited to 11 chars
to, receiver’s number with country code example (for Poland) 48123456789
messageBody, the exact content of message limited to 160 chars; if you want to send a longer text it will be automatically split by Vonage and sent in multiple messages
6. Finally, we have to add a “send” method call in Runner
object to test if our integration works correctly.
Here you can see the result of calling send method (of course receiver number has been changed).
And here we are, integration is done and tested. We have only one more thing to do: make it better.
How to Make It better
1. Create packages to achieve packaging by feature.
2. Use typesafe-config or some other library to store your API key and secret in configuration file.
3. Create ADTs which represents failure and success of send operation.
4. Add trait Sender (or SmsSender) with “send” method which will represent all SMS service providers then rename current implementation to Vonage and extend it with the newly created trait.
5. Add REST endpoint or some MQ consumer to make application reachable from the outside world.
After all these changes our integration should be a nice stateless service which, after writing some tests, can be run on production.
Points 1-4 will also be available on GitHub in branch named “improved”.
Summing up
There are cases in which sending text messages can be useful and bring value to your project. While choosing your SMS provider remember to check if it has good (or at least descent) documentation supports languages used bu your company. You should also remember to check SLA offered by the provider. Additionally, sending text messages with Scala does not have to be complex and can be implemented relatively easily. I hope that this text will be useful for you and help you with sending your notifications or that you at least learned something new and interesting. Thank you for your time.
Opinions expressed by DZone contributors are their own.
Comments