Send a Single SMS

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/

Prerequisites

  1. Sign up for a Plivo trial account.
  2. Check out our Helper Libraries 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
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
55
56
57
58
59
# -*- coding: utf-8 -*-
import plivo

auth_id = "Your AUTH_ID"
auth_token = "Your Auth_TOKEN"

p = plivo.RestAPI(auth_id, auth_token)

params = {
    'src': '1111111111', # Sender's phone number with country code
    'dst' : '2222222222', # Receiver's phone Number with country code
    'text' : u"Hello, how are you?", # Your SMS Text Message - English
#   'text' : u"こんにちは、元気ですか?" # Your SMS Text Message - Japanese
#   'text' : u"Ce est texte généré aléatoirement" # Your SMS Text Message - French
    'url' : "http://example.com/report/", # The URL to which with the status of the message is sent
    'method' : 'POST' # The method used to call the url
}

response = p.send_message(params)

# Prints the complete response
print str(response)

# Sample successful output
# (202,
#       {
#               u'message': u'message(s) queued',
#               u'message_uuid': [u'b795906a-8a79-11e4-9bd8-22000afa12b9'],
#               u'api_id': u'b77af520-8a79-11e4-b153-22000abcaa64'
#       }
# )

# Prints only the status code
print str(response[0])

# Sample successful output
# 202

# Prints the message details
print str(response[1])

# Sample successful output
# {
#       u'message': u'message(s) queued',
#       u'message_uuid': [u'b795906a-8a79-11e4-9bd8-22000afa12b9'],
#       u'api_id': u'b77af520-8a79-11e4-b153-22000abcaa64'
# }

# Print the message_uuid
print str(response[1]['message_uuid'])

# Sample successful output
# [u'b795906a-8a79-11e4-9bd8-22000afa12b9']

# Print the api_id
print str(response[1]['api_id'])

# Sample successful output
# b77af520-8a79-11e4-b153-22000abcaa64
 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
# encoding: utf-8
require 'rubygems'
require 'plivo'
include Plivo

AUTH_ID = "Your AUTH_ID"
AUTH_TOKEN = "Your AUTH_TOKEN"

p = RestAPI.new(AUTH_ID, AUTH_TOKEN)

# Send SMS
params = {
    'src' => '1111111111', # Sender's phone number with country code
    'dst' => '2222222222', # Receiver's phone Number with country code
    'text' => 'Hi, from Plivo', # Your SMS Text Message - English
#   'text' => 'こんにちは、元気ですか?', # Your SMS Text Message - Japanese
#   'text' => 'Ce est texte généré aléatoirement', # Your SMS Text Message - French
    'url' => 'http://example.com/report/', # The URL to which with the status of the message is sent
    'method' => 'POST' # The method used to call the url
}
response = p.send_message(params)
puts response

# Sample Output
# [202,
#   {
#       "api_id"=>"492f5288-9f27-11e4-b153-22000abcaa64",
#       "message"=>"message(s) queued",
#       "message_uuid"=>["494b5c4e-9f27-11e4-b1a4-22000ac693b1"]
#   }
# ]

# Print the message message_uuid
puts response[1]['message_uuid']

# Sample successful output
# ["f58113a2-9fca-11e4-b1a4-22000ac693b1"]

# Print the api_id
puts response[1]['api_id']

# Sample successful output
# f566addc-9fca-11e4-ac1f-22000ac51de6
 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
var plivo = require('plivo');
var p = plivo.RestAPI({
  authId: 'Your AUTH_ID',
  authToken: 'Your AUTH_TOKEN'
});

var params = {
    'src': '1111111111', // Sender's phone number with country code
    'dst' : '2222222222', // Receiver's phone Number with country code
    'text' : "Hi, text from Plivo", // Your SMS Text Message - English
    //'text' : "こんにちは、元気ですか?", // Your SMS Text Message - Japanese
    //'text' : "Ce est texte généré aléatoirement", // Your SMS Text Message - French
    'url' : "http://example.com/report/", // The URL to which with the status of the message is sent
    'method' : "GET" // The method used to call the url
};

// Prints the complete response
p.send_message(params, function (status, response) {
    console.log('Status: ', status);
    console.log('API Response:\n', response);
    console.log('Message UUID:\n', response['message_uuid']);
    console.log('Api ID:\n', response['api_id']);
});

/*
Sample Output

Status:  202
API Response:
 { api_id: 'b91b8736-134b-11e5-b0d7-22000ac520cd',
  message: 'message(s) queued',
  message_uuid: [ '138ee55f-9efb-4fc3-8ad7-4d71219bf56c' ] }

Message UUID:
 [ '138ee55f-9efb-4fc3-8ad7-4d71219bf56c' ]
Api ID:
 b91b8736-134b-11e5-b0d7-22000ac520cd
*/
 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
<?php
    require 'vendor/autoload.php';
    use Plivo\RestAPI;
    $auth_id = "Your AUTH_ID";
    $auth_token = "Your AUTH_TOKEN";

    $p = new RestAPI($auth_id, $auth_token);

    // Set message parameters
    $params = array(
        'src' => '1111111111', // Sender's phone number with country code
        'dst' => '2222222222', // Receiver's phone number with country code
        'text' => 'Hi, Message from Plivo', // Your SMS text message
        // To send Unicode text
        //'text' => 'こんにちは、元気ですか?' # Your SMS Text Message - Japanese
        //'text' => 'Ce est texte généré aléatoirement' # Your SMS Text Message - French
        'url' => 'http://example.com/report/', // The URL to which with the status of the message is sent
        'method' => 'POST' // The method used to call the url
    );
    // Send message
    $response = $p->send_message($params);

    // Print the response
    echo "Response : ";
    print_r ($response['response']);

    // Print the Api ID
    echo "<br> Api ID : {$response['response']['api_id']} <br>";

    // Print the Message UUID
    echo "Message UUID : {$response['response']['message_uuid'][0]} <br>";

?>

<!--
Sample output
Response : Array
(
    [api_id] => 6debfaec-a25e-11e4-96e3-22000abcb9af
    [message] => message(s) queued
    [message_uuid] => Array ( [0] => 6dffe3ea-a25e-11e4-a6e4-22000afa12b0 )
)
Api ID : 6debfaec-a25e-11e4-96e3-22000abcb9af
Message UUID : 6dffe3ea-a25e-11e4-a6e4-22000afa12b0
-->
 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
package com.plivo.test;

import java.util.LinkedHashMap;
import com.plivo.helper.api.client.*;
import com.plivo.helper.api.response.message.MessageResponse;
import com.plivo.helper.exception.PlivoException;

public class SendMessage {
    public static void main(String[] args) {
        String authId = "Your AUTH_ID";
        String authToken = "Your AUTH_TOKEN";
        RestAPI api = new RestAPI(authId, authToken, "v1");

        LinkedHashMap<String, String> parameters = new LinkedHashMap<String, String>();
        parameters.put("src", "1111111111"); // Sender's phone number with country code
        parameters.put("dst", "2222222222"); // Receiver's phone number with country code
        parameters.put("text", "Hi, text from Plivo"); // Your SMS text message
        // Send Unicode text
        //parameters.put("text", "こんにちは、元気ですか?"); // Your SMS text message - Japanese
        //parameters.put("text", "Ce est texte généré aléatoirement"); // Your SMS text message - French
        parameters.put("url", "http://example.com/report/"); // The URL to which with the status of the message is sent
        parameters.put("method", "GET"); // The method used to call the url

        try {
            // Send the message
            MessageResponse msgResponse = api.sendMessage(parameters);

            // Print the response
            System.out.println(msgResponse);
            // Print the Api ID
            System.out.println("Api ID : " + msgResponse.apiId);
            // Print the Response Message
            System.out.println("Message : " + msgResponse.message);

            if (msgResponse.serverCode == 202) {
                // Print the Message UUID
                System.out.println("Message UUID : " + msgResponse.messageUuids.get(0).toString());
            } else {
                System.out.println(msgResponse.error);
            }
        } catch (PlivoException e) {
            System.out.println(e.getLocalizedMessage());
        }
    }
}
 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
using System;
using System.Collections.Generic;
using System.Reflection;
using RestSharp;
using Plivo.API;

namespace Send_Sms
{
    class Program
    {
        static void Main(string[] args)
        {
            RestAPI plivo = new RestAPI("Your AUTH_ID", "Your AUTH_TOKEN");

            IRestResponse<MessageResponse> resp = plivo.send_message(new Dictionary<string, string>()
            {
                { "src", "1111111111" }, // Sender's phone number with country code
                { "dst", "2222222222" }, // Receiver's phone number wiht country code
                { "text", "Hi, text from Plivo." }, // Your SMS text message
                // To send Unicode text
                // {"text", "こんにちは、元気ですか?"} // Your SMS text message - Japanese
                // {"text", "Ce est texte généré aléatoirement"} // Your SMS text message - French
                { "url", "http://example.com/report/"}, // The URL to which with the status of the message is sent
                { "method", "POST"} // Method to invoke the url
            });

            // Prints the message details
            Console.Write(resp.Content);

            // Print the message_uuid
            Console.WriteLine(resp.Data.message_uuid[0]);

            // Print the api_id
            Console.WriteLine(resp.Data.api_id);

            Console.ReadLine();
        }
    }
}

// Sample Output
/*
{
  "api_id": "e8f04d94-a0ae-11e4-b423-22000ac8a2f8",
  "message": "message(s) queued",
  "message_uuid": [
    "e908608c-a0ae-11e4-89de-22000ae885b8"
  ]
}
Message UUID : e908608c-a0ae-11e4-89de-22000ae885b8
Api ID : e8f04d94-a0ae-11e4-b423-22000ac8a2f8
*/
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/

Sample Response

(202,
    {
        u'message': u'message(s) queued',
        u'message_uuid': [u'b795906a-8a79-11e4-9bd8-22000afa12b9'],
        u'api_id': u'b77af520-8a79-11e4-b153-22000abcaa64'
    }
)

Next Step

Learn what happens when you send a Long SMS that’s over the character limit.

  1. Send a Long SMS
  2. Send Multiple (Bulk) SMS
  3. Send an SMS with Alphanumeric Sender ID
  4. Receive an SMS
  5. Reply to an Incoming SMS
  6. Forward an Incoming SMS
  7. Get Details of all Messages
  8. Get Details of a Single Message
  9. Handling SMS Delivery Reports
  10. Forward SMS to Email