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

Example

This is what our application looks like:

HTML

Application main page.

<!DOCTYPE html>
<html ng-app="starter">
  <head>
    <meta charset="utf-8">
	<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

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

    <!-- your app's js -->
    <script src="js/app.js"></script>
  </head>
  <body ng-controller="SMSController">

    <ion-pane>
      <ion-header-bar class="bar-stable">
        <h1 class="title">SMS Example</h1>
      </ion-header-bar>
      <ion-content>
        <div class="list">
          <label class="item item-input">
            <span class="input-label">Number</span>
            <input type="text" ng-model="sms.number">
          </label>
          <label class="item item-input item-floating-label">
            <span class="input-label">Message</span>
            <input type="text" placeholder="Message" ng-model="sms.message">
          </label>
          <button class="button button-full button-positive" ng-click="sendSMS()">
            Send SMS
          </button>
        </div>	  
      </ion-content>
    </ion-pane>
  </body>
</html>

JavaScript

Application JavaScript file.

// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
var app = angular.module('starter', ['ionic', 'ngCordova'])

app.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
});

app.controller('SMSController', function($scope, $cordovaSms) {
  $scope.sms = {
    number: '0959052082',
    message: 'This is some dummy text'
  };

  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
        });
    }
  });
});

Deployment

Next step, we need to build our application:

ionic build android

Be careful here, this step may break if you’re behind a firewall. The first execution will take a long time, so be patient.

When this step ends, look at the output log, last two lines should look something like this:

Built the following apk(s):
    D:\Development\IonicSendSMSDemo\platforms\android\build\outputs\apk\android-debug.apk

We’ll use the last line location to deploy our application. Make sure your smartphone is prepared to accept an incoming application. In case of Android platform, you must enable Developer Options and USB Debugging.

Do this:

adb install -r platforms\android\build\outputs\apk\android-debug.apk

or you can do this:

ionic run android -l -c -s

Who Am I?

Between working as a senior Java developer in one of the largest insurance companies in the world and traveling, in my free time, I work as a professional mobile development adviser. I'm also a major jQuery Mobile supporter back at StackOverflow and a forum moderator at the official Ionic Framework forum.



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