Send an SMS

In this guide, we’ll see how to use Plivo APIs to send SMS messages from your web application. Let’s have a look at some prerequisites before we dive into the code.

  • Plivo Auth Id and Auth Token: You will find your Plivo Auth Id and Auth Token on the home screen of your Plivo management console. Click here to sign-up for a Plivo account if you haven’t already!
  • Plivo Server-side SDK: The code in this tutorial uses Plivo’s Python Server-side SDK. To get started with the SDK in the language of your choice, visit the Server-side SDKs page.
  • Plivo Phone Number: You must have a valid Plivo phone number to send messages to the US and Canada. You can purchase numbers from the Numbers section of your Plivo Management Console. It is also possible to purchase numbers using the Numbers API.

Sending Messages Using Plivo REST API

This tutorial will show you how to send an outbound Short Message Service (SMS) (i.e., text message) using Plivo’s REST API. This can be used in any web or mobile application that requires communication with end users via SMS text messages including delivery notifications, system alerts, two-factor authentication and even rideshare alerts.

Plivo’s Message API supports Unicode UTF-8 encoded texts, which means that you can send messages in any language. The Message API also automatically splits long messages at 160 characters and concatenates them into a single SMS on the receiver’s end. Delivery reports are also automatically supported in networks where they are provided by the operator.

To send an SMS, we’ll need to make an HTTP POST request to the Message API.

POST https://api.plivo.com/v1/Account/{auth_id}/Message/

Getting Started

  1. Sign up for a Plivo trial account.
  2. Check out our server-side SDKs page and install the right helper based on the programming language you want to use.
  3. Buy a Plivo phone number (optional).
    Note: A phone number is required only for sending SMS to US and Canadian phone numbers. However, country-specific carrier conditions may still apply. You can buy a US or Canadian phone number through the Buy Numbers tab on your Plivo account UI.
  4. Use a web hosting service to host your web application. There are many inexpensive cloud hosting providers that you can use for just a few dollars a month. Follow the instructions of your hosting provider to host your web application.
    Note: If you are using a Plivo Trial account for this example, you can only send sms to phone numbers that have been verified with Plivo. Phone numbers can be verified at the Sandbox Numbers page.

Implementation

  1. Copy the relevant code below into a text file and save it.
  2. Replace Your AUTH_ID and Your AUTH_TOKEN with the AUTH ID and AUTH TOKEN found on your Plivo dashboard.
  3. Add your 'src' (source) phone number. This will show up as your Sender ID. Be sure that all phone numbers include country code, area code, and phone number without spaces or dashes (e.g., 14153336666).
    Note: You can send SMS text messages to any country using the Message API and set any 'src' number except for US and Canadian numbers. In order to send text messages to phones in the US or Canada, you will need to purchase a US or Canadian phone number from Plivo and use it as the 'src' number. You can buy a Plivo number from the Buy Numbers tab on your Plivo account dashboard.
  4. Add your 'dst' (destination) phone numbers. These are the phone numbers you will be sending SMS text messages to. To send multiple messages in the same API request, separate your destination phone numbers with the “<” character (e.g., 14156667777<14157778888<14158889999). Be sure that all phone numbers include country code, area code, and phone number without spaces or dashes (e.g., 14153336666).
    Note: If you are using a trial account, your destination number needs to be verified with Plivo. Phone numbers can be verified at the Sandbox Numbers page.
  5. Edit the 'text' field with your SMS text message.
    Note: Text messages that are longer than 160 characters are concatenated and billed separately as individual text messages.
  6. Make the 'HTTP POST' request to Plivo. If successful, Plivo will queue your SMS deliver it to your recipients at a base rate of 1 message per second.
    Advanced Hack: Check out our full Message API docs to see all the parameters and functionalities you can use.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import plivo

client = plivo.RestClient("AUTH_ID","AUTH_TOKEN")
response = client.messages.create(
    dst='17652348329',
    text='Hello, this is a sample text',
    url='http://foo.com/sms_status/',
    method='POST',
    log=False,
    type_='sms',
    trackable=True,
    powerpack_uuid='2dca8f70-1387-4cbd-b97f-796717a5784b'
    #Incase of no powerpack, replace powerpack_uuid with --> src:"13644444296"
    )
print(response)

#Prints only the message_uuid
print(response.message_uuid)

# Sample Response:
# {
#     u'api_id': u'74381b64-bffb-11e9-b306-0242ac110004',
#     u'message': u'message(s) queued',
#     u'message_uuid': [u'743b6f08-bffb-11e9-b306-0242ac110004']
# }

# ===============================================================
#Prints only the message_uuid
# [u'743b6f08-bffb-11e9-b306-0242ac110004']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
require "rubygems"
require "plivo"

include Plivo
include Plivo::Exceptions

api = RestClient.new("AUTH_ID", "AUTH_TOKEN")

begin
  response = api.messages.create(
    nil, #Incase if no pwerpack, 'nil' to be replaced with -->"13644444296" as source number and remove the powerpack_uuid.
    ["17652348329"], #dst
    "Hello, this is a sample text", #text
    { url: "http://foo.com/sms_status/",
      method: "POST",
      log: false,
      trackable: true,
      type: "sms" },
    "2dca8f70-1387-4cbd-b97f-796717a5784b", #powerpack_uuid
  )

  puts response

  #Prints only the message_uuid
  puts response.message_uuid
rescue PlivoRESTError => e
  puts "Exception: " + e.message
end

# Sample Response:
# {
#   "api_id"=>"37aac418-bfe6-11e9-b157-0242ac110004",
#   "message"=>"message(s) queued",
#   "message_uuid"=>["37af9ae2-bfe6-11e9-b157-0242ac110004"],
#   "id"=>["37af9ae2-bfe6-11e9-b157-0242ac110004"]
# }

# ===============================================================
# prints only the message_uuid
#37af9ae2-bfe6-11e9-b157-0242ac110004
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
var plivo = require('plivo');

(function main() {
    'use strict';
    var client = new plivo.Client("AUTH_ID","AUTH_TOKEN");
    client.messages.create(
         null, //Incase if no pwerpack, 'nil' to be replaced with -->"13644444296" as source number and remove the powerpack_uuid.
        "17652348329", // dst
        "Hello, this is a sample text from Plivo", // text
        {
            method: "GET",
            url:"http://foo.com/sms_status/",
            log: "true",
            type: "sms"
        },
        "2dca8f70-1387-4cbd-b97f-796717a5784b" //powerpack_uuid

    ).then(function (response) {
        console.log(response);

        // Prints only the messageUuid
        console.log(response.messageUuid);
    }, function (err) {
        console.error(err);
    });
})();

// Sample response:
// PlivoGenericResponse {
//     id: [ 'b6cf582e-c001-11e9-9d74-0242ac110005' ],
//     apiId: 'b6c83af8-c001-11e9-9d74-0242ac110005',
//     message: 'message(s) queued',
//     messageUuid: [ 'b6cf582e-c001-11e9-9d74-0242ac110005' ] }

// ===============================================================
// Prints only the messageUuid
// [ 'b6cf582e-c001-11e9-9d74-0242ac110005' ]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php

require 'vendor/autoload.php';
use Plivo\RestClient;
use Plivo\Exceptions\PlivoRestException;
$client = new RestClient("AUTH_ID", "AUTH_TOKEN");

try {
    $response = $client->messages->create(
        null, #Incase if no pwerpack, 'nil' to be replaced with -->"13644444296" as source number and remove the powerpack_uuid.
        ['17652348329'], #dst
        'Hello, this is a sample text', #text
        ["url"=>"http://foo.com/sms_status/", "method"=>"POST", "type"=>"sms","log"=> "true","log"=> "true"],
        '2dca8f70-1387-4cbd-b97f-796717a5784b' #powerpack_uuid
    );
    print_r($response);

    // Prints only the message_uuid
    print_r($response->getmessageUuid(0));

}
catch (PlivoRestException $ex) {
    print_r($ex);
}

// Sample Response:
// Plivo\Resources\Message\MessageCreateResponse Object
// (
//     [messageUuid] => Array
//         (
//             [0] => 03ae74ec-c000-11e9-b306-0242ac110004
//         )

//     [_message] => message(s) queued
//     [apiId] => 03a86c32-c000-11e9-b306-0242ac110004
//     [statusCode] => 202
// )

// ===============================================================
// Print only the message_uuid
// Array
// (
//     [0] => 03ae74ec-c000-11e9-b306-0242ac110004
// )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.io.IOException;
import java.net.URL;
import java.util.Collections;

import com.plivo.api.Plivo;
import com.plivo.api.exceptions.PlivoRestException;
import com.plivo.api.models.message.Message;
import com.plivo.api.models.message.MessageCreateResponse;
import com.plivo.api.models.message.MessageType;

/**
 * Example for Message create
 */
class Sendsms
{
    public static void main(String [] args)
    {
        Plivo.init("AUTH_ID","AUTH_TOKEN");
        try
        {
            MessageCreateResponse response = Message.creator(Collections.singletonList("17652348362"),
                    "Hello, this is test message","2dca8f70-1387-4cbd-b97f-796717a5784b")
            //Incase of no powerpack, replace the above with below;
            //MessageCreateResponse response = Message.creator("13644444296",Collections.singletonList("17652348362"),
            //"Hello, this is test message")
                    .url(new URL("http://foo.com/sms_status/") )
                    .method("GET")
                    .type(MessageType.SMS)
                    .log(true)
                    .trackable(false)
                    .create();

            System.out.println(response);
            System.out.println(response.getMessageUuid());
        }

        catch (PlivoRestException | IOException e)
        {
            e.printStackTrace();
        }
    }
}


//Sample Response:
//INFO: {
//    "   "api_id": "5db0792a-c002-11e9-b157-0242ac110004",
//        "message": "message(s) queued",
//        "message_uuid": ["5db241c4-c002-11e9-b157-0242ac110004"]
//      }

// ===============================================================
//Prints only the message_uuid:
//[5db241c4-c002-11e9-b157-0242ac110004]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main

import "fmt"
import "github.com/plivo/plivo-go"

func main() {
	client, err := plivo.NewClient("AUTH_ID", "AUTH_TOKEN", &plivo.ClientOptions{})
	if err != nil {
		panic(err)
	}
	response, err := client.Messages.Create(
		plivo.MessageCreateParams{
			Dst:           "17652348329",
			Text:          "Hello, this is a sample text",
			Type:          "sms",
			URL:           "http://foo.com/sms_status/",
			Method:        "POST",
			Trackable:     true,
			Log:           "false",
			PowerpackUUID: "2dca8f70-1387-4cbd-b97f-796717a5784b",
			// Incase of no powerpack, replace powerpack_uuid with --> Src:"13644444296"
		},
	)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Response: %#v\n", response)

	// Prints only the message_uuid
	fmt.Printf("Response: %#v\n", response.MessageUUID)
}

// Sample Response:
// Response: &plivo.MessageCreateResponseBody
// {Message:"message(s) queued",
//  ApiID:"d7fb3582-c005-11e9-86d6-0242ac110006",
// MessageUUID:[]string{"d7fcec60-c005-11e9-86d6-0242ac110006"},
// Error:""}

// ===============================================================
//Prints only the message_uuid:
// Response: []string{"d7fcec60-c005-11e9-86d6-0242ac110006"}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Collections.Generic;
using Plivo;
using Plivo.Exception;

namespace PlivoExamples
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            var api = new PlivoApi("AUTH_ID", "AUTH_TOKEN");
            try
            {
                var response = api.Message.Create(
                    dst:new List<String>{"17652348373"},
                    text:"Hello, this is sample text",
                    url:"http://foo.com/sms_status/",
                    method:"GET",
                    log:false,
                    trackable:true,
                    type:"sms",
                    powerpack_uuid:"2dca8f70-1387-4cbd-b97f-796717a5784b"
                    // Incase of no powerpack, replace powerpack_uuid with --> Src:"13644444296"
                );
                Console.WriteLine(response);

                // Prints the message_uuid
                Console.WriteLine(response.MessageUuid[0]);
            }
            catch (PlivoRestException e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}

// Sample Response:
// Api Id: ba00870c-c006-11e9-8db4-0242ac110005
// Message: message(s) queued
// StatusCode: 202
// Message Uuid: ba0cb7d4-c006-11e9-8db4-0242ac110005Username:
// Alias:

// ===============================================================
// Prints only the messageuuid
// 9ffa5e40-c007-11e9-9d74-0242ac110005
1
2
3
4
curl -i --user AUTH_ID:AUTH_TOKEN \
    -H "Content-Type: application/json" \
    -d '{"src": "1111111111","dst": "2222222222", "text": "Hi, text from Plivo"}' \
    https://api.plivo.com/v1/Account/{auth_id}/Message/

Next Steps