How to send an SMS with Ionic Framework and ngCorodva

Written by on August 20, 2015

How to send an SMS with Ionic Framework and ngCorodva

Have you ever wanted to programmatically send an SMS? Who cares, this technology is no longer important. But if yous till need to do so here’s how you can do this with Ionic Framework and Cordova.

Note: If this tutorial was helpful, you need further clarification, something is not working or you have a request for another Ionic post? Furthermore, leave me a comment below if you don't like something about this blog, if something is bugging you, don't like how I'm doing stuff here. Feel free to comment below, subscribe to my blog, mail me to dragan.gaic@gmail.com. Thanks and have a nice day!

Table of Contents

[spoiler title=” Click here if you want to see other tutorials, or articles about the Ionic framework (themes, templates, plugins, tutorials)”]

Tutorials

Other Resources (themes, templates, plugins, Cordova plugins, starter apps)

Cordova Plugin Tutorials


[/spoiler]

Preparation

Make sure you have these requirements:

  • Android Environment (or iOS if your working on a MacOS)
  • nodeJS
  • Ionic
  • Cordova

If you don’t have a previous Ionic Framework experience you can find more information here: Ionic Framework | Installation Guide.

1. Update Ionic & Cordova

The latest nodeJs version is a top priority, you can’t download/update proper Ionic Framework version without it.

After nodeJS, update Ionic, and Cordova, older versions may not work with this tutorial:

npm update -g cordova ionic

2. Create a New Project

ionic start IonicSendSMSDemo blank
cd IonicSendSMSDemo

Warning: Since some of you never worked with Ionic CLI. From this point and further, every time I tell you to execute something, do that inside a project folder.

Android platform is required for this example:

ionic platform add android

MacOS users can also add iOS platform:

ionic platform add ios

3. Download ngCordova archive

ngCordova is a collection of 63+ AngularJS extensions on top of the Cordova API that make it easy to build, test, and deploy Cordova mobile apps with AngularJS. While we can make this work without ngCordova, it’s much more practical this way. This collection also holds many Ionic Framework compatible plugins.

Download ngCordova zip file, here’s site link:

Official Site
Docs
Download Link

Unzip this archive, find a file name called: ng-cordova.min.js, it should be available at this location: ng-cordova-master\dist\.

Open your newly created project directory and copy ng-cordova.min.js to this location: IonicSendSMSDemo\www\js.

Now include this location to index.html located at IonicSendSMSDemo\www; add it above cordova.js file, like this:

<!-- cordova script (this will be a 404 during development) -->
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>

4. Install Cordova SMS plugin

Next line will import and install necessary plugins into newly created project:

cordova plugin add https://github.com/cordova-sms/cordova-sms-plugin.git
cordova plugin add cordova-plugin-whitelist

If you’re using Cordova 5.0.0 you will already have preinstalled Whitelist plugin.

We also need Cordova File plugin so we can access device file system.

GitHub - SMS
GitHub - Whitelist

Development

At this point, you should have everything set up and ready, we can start working on our example.

Go to IonicSendSMSDemo project directory and find app.js, alter angular.module line and include ngCordova service, like this:

var app = angular.module('starter', ['ionic', 'ngCordova'])

Open index.html file, add a controller to ion-content directive:

  <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">SMS Example</h1>
      </ion-header-bar>
      <ion-content ng-controller="SMSController">
      </ion-content>
    </ion-pane>

Initialize this controller in app.js file; don’t forget to inject $cordovaSms service, like this:

app.controller('SMSController', function($scope, $cordovaSms) {

});

Now we need to initialize Whitelist plugin; add this meta tag to index.html HEAD content:

<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">

We will use next function to send an SMS, don’t forget to wrap it into Cordova deviceready event (or Ionic ready depending on your project):

  document.addEventListener("deviceready", function() {

    var options = {
      replaceLineBreaks: false, // true to replace \n by a new line, false by default
      android: {
        intent: '' // send SMS with the native android SMS messaging
          //intent: '' // send SMS without open any other app
          //intent: 'INTENT' // send SMS inside a default SMS app
      }
    };

    $scope.sendSMS = function() {

      $cordovaSms
        .send('0959052082', 'This is some dummy text', options)
        .then(function() {
          alert('Success');
          // Success! SMS was sent
        }, function(error) {
          alert('Error');
          // An error occurred
        });
    }
  });

options object is important here. The first parameter (replaceLineBreaks) is boolean which defines should message use a “\n” or not, false is a default one. The second parameter defines if our application should send SMS directly or via default SMS application. If default application is selected then you will need to manually press Send button. Both parameters are described in example comments.

Continue Reading

Categories

51 thoughts on “How to send an SMS with Ionic Framework and ngCorodva”

    • You can’t, an emulator is not a real device. To be able to send an SMS, a device must be connected to some mobile network provider.

      But you can receive a SMS, through emulation.

  1. Hi do you also have this one with a database? I mean, the sent and received messages would be save on a database locally or hosted? Thank you !

  2. Is just starting on my ionic adventure. Thanks a lot for such valuable resource. Would love to see how you tackle accessing incoming SMS.

  3. I copied everything literally after it didnt work the first time i just copied and pasted. I can type in a number and a message but when i click send nothing happens just the keyboard disappears

  4. I’ve copied and followed all, it works! but it only send the message defined in the code “This is some dummy text”. And same with the number, I have altered it with sms.message variable but it gives me an error. How to send my own message to any other required number please.

  5. Hi, gajs this is great tutorial. However, why i cannot send message if i leave intent options into nothing ? i only can send msg if i use INTENT options. Could it be whitelist problem? thanks best regard

    • From what I can see intent parameter is required. Worst case scenario it should be empty:

      intent: ” // send SMS without open any other app
      intent: ‘INTENT’ // send SMS inside a default SMS app

  6. Thanks, just sent my first Ionic text to myself. Too bad you are having to support JQuery Mobile.

      • My experiences with JQuery MobileMobile has been pretty miserable. Ionic is so elegant, beautiful and a delight to work with by comparison. For webpages Bootstrap and Foundation are better options.. so I don’t see the point of jqm.. They haven’t updated since 2014..

        • I completely agree with you, you couldn’t have said it better. But I’m still covering jQuery Mobile since it still has a large user base (don’t know why) plus jQuery Mobile 1.5 beta will come in 2-3 weeks, unless they postpone it again.

  7. When I run this application on my device it display an error that unfortunately app has stopped.Tell me what to do.

  8. well i try to do it! but don’t happen nothing! i don’t why! not error, not send! nothing !

  9. Great Article. Has significantly reduced my project completion time. Thanks a lot.
    Just one small thing, it seems the spelling of Cordova in the heading is not right.

  10. Hi, great article. When you said that SMS technology was no longer important, what did you mean by that? Is there a good alternative? I need to send an initial link to phone users, is there an alternative to SMS?

  11. Hi there!
    Can anyone help me solving this issue?

    I keep getting:
    ‘SyntaxError: Unexpected token’

    On the browser I see this:

    cordova.js:1487 GET file:///C:/Program%20Files/nodejs/IonicSendSMSDemo/www/cordova_plugins.js net::ERR_FILE_NOT_FOUNDexports.injectScript @ cordova.js:1487injectIfNecessary @ cordova.js:1495exports.load @ cordova.js:1575(anonymous function) @ cordova.js:1225

    app.js:12 Uncaught TypeError: Cannot read property ‘Keyboard’ of undefined(anonymous function) @ app.js:12(anonymous function) @ ionic.bundle.js:56230onPlatformReady @ ionic.bundle.js:2496Channel.fire @ cordova.js:760(anonymous function) @ cordova.js:223

    2ionic.bundle.js:26794 ReferenceError: sms is not defined

    at Object.send (ng-cordova.min.js:9)

    at Scope.$scope.sendSMS (app.js:41)

    at fn (eval at (ionic.bundle.js:27638), :4:212)

    at ionic.bundle.js:65427

    at Scope.$eval (ionic.bundle.js:30395)

    at Scope.$apply (ionic.bundle.js:30495)

    at HTMLButtonElement. (ionic.bundle.js:65426)

    at defaultHandlerWrapper (ionic.bundle.js:16787)

    at HTMLButtonElement.eventHandler (ionic.bundle.js:16775)

    at triggerMouseEvent (ionic.bundle.js:2953)(anonymous function) @ ionic.bundle.js:26794(anonymous function) @ ionic.bundle.js:23507Scope.$apply @ ionic.bundle.js:30500(anonymous function) @ ionic.bundle.js:65426defaultHandlerWrapper @ ionic.bundle.js:16787eventHandler @ ionic.bundle.js:16775triggerMouseEvent @ ionic.bundle.js:2953tapClick @ ionic.bundle.js:2942tapMouseUp @ ionic.bundle.js:3018

    help anyone??

  12. very assist me, thanks a lot..
    I have one question, is it possible to send SMS without record the message on the sender phone?

    I have one mobile app where the users register by Legal ID number. Then the admin will input their both ID & phone number to the form register. App will generate PIN number and send to users phone number. My concerns, I check on the admin phone device it will record the SMS outbox/sent. While the content is the PIN of the users, I mean it is secret content.

    Is there other trick if we can remove SMS after sent? How to get SMS status if they are pending or have sent?

    I have used gammu previously to build SMS gateway, and it has great feature for us to manage SMS. But it is not useful for the App, because we need to build third dedicated server.

  13. undefined error in ionic.bundle.js (” sms is not defined “) in e
    $apply: function(expr) {
    try {
    beginPhase(‘$apply’);
    try {
    return this.$eval(expr);
    } finally {
    clearPhase();
    }
    } catch (e) {
    $exceptionHandler(e);
    } finally {

    please help

  14. Guys, I’ve tried, used all the same code, still when I hit the send button. Nothing happens. Any guess?

  15. Working perfectly in Lollipop. Any reasons why it doesn’t work in Marshmallow? Please advice if there’s tweaking that needs to be done please…

  16. I use your code, but the problem now is that when the android ask for permission and click cancel referring to not granting the permission , the send method shows success.hope you can help me.

  17. Hi All,Can anyone help me out
    I need success or error callback from from default App.
    For example, if you press send then the app passes the data to the default SMS app, and if there is a network issue or for some reason the SMS does not get sent, the callback from default app will return as error callback to my app ,How could be it can be implemented .Thanks in Advance @dragangai:disqus

  18. I having a problem with this SMS plugin. It doesn’t send the SMS to the number I specified in the code. Instead it send it to myself 🙁 pls help

  19. Hello @Dragan Gaić. Thanks for the post. But I ma having question.
    After run this command ionic run build -l -c -s I found this error. Can anyone help me to understand how I should test application in ios or emulator. Thanks in advance.

    [….] Waiting up to 1 seconds for iOS device to be connected

    [….] Found 62cc57c1fbb18b4105071760146d929d0570c153 (N66AP, iPhone 6s Plus, iphoneos, arm64) a.k.a. ‘Harshilkumar’s iPhone’ connected through USB.

    2017-03-07 10:45:59.397 ios-deploy[46909:507] [ !! ] Can’t access app path ‘/Users/henry/WebstormProjects/stockprofile/stockapp/platforms/ios/build/device/stockapp.app’ : No such file or directory

    Error: Error code 253 for command: ios-deploy with args: –justlaunch,–no-wifi,-d,-b,/Users/henry/WebstormProjects/stockprofile/stockapp/platforms/ios/build/device/stockapp.app

      • @Dragan Gaić I go through all the steps. Still I am not able to send SM using the project? I have a questions how should I run the application on server? Also How should I send the SMS through the localhost application?

Leave a Reply