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.

Prerequisites

  • 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/

Prerequisites

  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
# -*- coding: utf-8 -*-
import plivo

client = plivo.RestClient()
response = client.messages.create(
    src='from_number',
    dst='to_number',
    text='Test Message', )
print(response)
        
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#
# Example for Message Create
#
require 'rubygems'
require 'plivo'

include Plivo
include Plivo::Exceptions

api = RestClient.new("YOUR_AUTH_ID", "YOUR_AUTH_TOKEN")

begin
  response = api.messages.create(
    '14153336666',
    ['14156667777', 123_123_123_123],
    'Test Message'
  )
  puts response
rescue PlivoRESTError => e
  puts 'Exception: ' + e.message
end
        
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Example for Message create

var plivo = require('plivo');

(function main() {
    'use strict';

    // As the auth_id and auth_token are unspecified, Plivo will fetch them from the PLIVO_AUTH_ID and PLIVO_AUTH_TOKEN environment variables.
    var client = new plivo.Client();
    client.messages.create(
        "14153336666", // src
        "14156667777", // dst
        "Test Message", // text
    ).then(function (response) {
        console.log(response);
    }, function (err) {
        console.error(err);
    });
})();
        
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
/**
* Example for Message create
*/
require 'vendor/autoload.php';
use Plivo\RestClient;
$client = new RestClient("YOUR_AUTH_ID", "YOUR_AUTH_TOKEN");
try {
    $response = $client->messages->create(
        '14153336666',
        [14156667777],
        'Test Message'
    );
    print_r($response);
}
catch (PlivoRestException $ex) {
    print_r(ex);
}
      
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
package com.plivo.api.samples.message;

import java.io.IOException;
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;

/**
* Example for Message create
*/
class MessageCreate {
    public static void main(String [] args) {
        Plivo.init();
        try {
            MessageCreateResponse response = Message.creator("14153336666", Collections.singletonList("14156667777"), "Test Message")
                .create();

            System.out.println(response);
        } catch (PlivoRestException | IOException e) {
            e.printStackTrace();
        }
    }
}
        
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
/**
 * Example for Message Create
 */
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("YOUR_AUTH_ID", "YOUR_AUTH_TOKEN");
            try
            {
                var response = api.Message.Create(
                    src:"14153336666",
                    dst:new List<String>{"14156667777"},
                    text:"Test Message"

                );
                Console.WriteLine(response);
            }
            catch (PlivoRestException e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }
        }
    }
}
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Example for Message create
package main

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

func main() {
	client, err := plivo.NewClient("YOUR_AUTH_ID", "YOUR_AUTH_TOKEN", &plivo.ClientOptions{})
	if err != nil {
		panic(err)
	}
	response, err := client.Messages.Create(
		plivo.MessageCreateParams{
			Src: "14153336666",
			Dst: "14156667777",
			Text: "Test Message",
		},
	)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Response: %#v\n", response)
}
        
1
2
3
4
5
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 Steps