Saturday, March 19, 2016

How to enable Grails application to send SMS via Twilio API

How to send SMS with Grails Application via Twilio


Are you trying to send text messages from your Grails web application? If your answer is Yes then you are in luck. If your answer is No .. well... stick around... you'll learn something. 

Target audience:

People interested in software development, Grails framework and Groovy programming language.
This article may be more interesting if you already know Grails framework. 

What you need:

  1. A twilio account with your API keys
  2. The grails-twilio plugin
  3. Your grails application ( Grails version 2.x and above )

To create a twilio account, please visit Copy your API Keys
The twilio-grails plug-in provides sms sending capability to a Grails application via twilio api.

Add twilio plugin

Depending on what version of Grails you are using, open your buildConfig.groovy file or build.gradle file and add the following line.

compile "org.grails.plugins:twilio:0.1"
for grails 2.x


compile "org.grails.plugins:twilio:0.1.0"
For grails 3.x

Add twilio properties

Add your twilio properties to grails configuration file: The config file for grails 2.x is Config.groovy. For Grails 3.x users, please add the following to your application.groovy file or application.yml ( Use yml syntax )
twilio {
    // Enter your host address
    host = ''
    apiID = 'enter your api Id'
    apiPass = 'enter your api password'
    smsUrl = '/2010-04-01/Accounts/' + apiID + '/Messages.json'
    number = ""

Add more dependencies

Copy and paste the following to your BuildConfig.groovy or Build.gradle file 
 compile(group:'org.apache.httpcomponents',name:'httpclient',version:'4.3.6') compile(group:'org.apache.httpcomponents',name:'fluent-hc',version:'4.3.6') compile(group:'org.apache.httpcomponents',name:'httpclient-cache',version:'4.3.6') compile(group:'org.apache.httpcomponents',name:'httpmime',version:'4.3.6') 

Create your controller

Create the grails controller you wish to handle the SMS sending flow

Inject smsService into your controller

Inject smsService into your class
def smsService
smsService is a Grails service provide by the twilio plugin for easy sending SMSs. 
It provides a method called send() that can take mapped parameters. Please note that 'send()' is overloaded 'see' and can take various variations of parameters.

One simple form is:  send(Map map) 
Where ......
map contains parameters;
map['phone'] :  The phone number of recipient eg +1234444444
map['from'] : Your twilio assigned number eg. +09899898989
map['body']:  "The body of your message" map.mediaUrl: "Url for any attachment" (optional )

Example Usage

An example usage can be seen below.
Class YourController{

    def smsService
    def yourMethod(){
        def map = [to:"070987878787",from:"09808000000",body:"SMS BODY"]



You are done.

No comments: