Forward an Incoming SMS

This tutorial will allow you to forward SMS text messages (sent to your Plivo number) to your another phone number. This is especially useful in use cases that involve message routing such as CRM softwares, sales teams, and help desk applications. The functionality behind forwarding text messages can be broken down into these two steps:

  1. Your friend sends you an SMS to your Plivo Number
  2. The SMS gets forwarded to another phone number

Getting Started

  1. Sign up for a free 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.

Set up a Web Server

Let’s assume your web server is located at http://example.com. Below is a snippet to set up a route on your webserver. Now when we send an HTTP request to http://example.com/forward_sms this route will be invoked.

Note: For PHP, the route will be example.com/forward_sms.php.
  1. Copy the relevant code below into a text file and save it. Let’s call it, 'forward_sms'.
  2. Configure the 'to_forward' parameter to the phone number you want to forward the SMS to. Be sure that all phone numbers include country code, area code, and phone number without spaces or dashes (e.g., 14153336666).
  3. Next, you will now have to configure this URL in your Plivo application.
    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.

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
from flask import Flask, request, make_response, Response
import plivo
from plivo import plivoxml

app = Flask(__name__)

@app.route('/forward_sms/', methods=['GET', 'POST'])
def inbound_sms():
    # Sender's phone number
    from_number = request.values.get('From')
    # Receiver's phone number - Plivo number
    to_number = request.values.get('To')
    # The text which was received
    text = request.values.get('Text')
    # Print the message
    print('Message received - From: %s, To: %s, Text: %s' %(from_number, to_number, text))

    # The phone number to which the SMS has to be forwarded
    to_forward = '17652348362'

    # send the details to generate an XML
    response = plivoxml.ResponseElement()
    response.add(
        plivoxml.MessageElement(
            text,  # body/The text which was received
            src=to_number,  # Sender's phone number
            dst=to_forward,  # Receiver's phone Number
            type='sms',
            callback_url='http://foo.com/sms status/',
            callback_method='POST'))
    print(response.to_string())  # Prints the XML
    # Returns the XML
    return Response(response.to_string(), mimetype='application/xml')

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
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
require "plivo"
require "sinatra"

include Plivo
include Plivo::XML
include Plivo::Exceptions

post "/forward_sms/" do
  # The phone number of the person who sent the SMS
  from_number = params[:From]
  # Your Plivo number that will receive the SMS
  to_number = params[:To]
  # The text which was received on your Plivo number
  text = params[:Text]

  # Output the text which was received, you could also store the text in a database.
  puts "Message received - From: #{from_number}, To: #{to_number}, Text: #{text}"

  body = "Forwarded message : #{text}"
  to_forward = "17652348362"
  begin
    response = Response.new

    params = {
      src: to_number,  # Sender's phone number
      dst: to_forward, # Receiver's phone Number
      type: "sms",
      callbackUrl: "https://www.foo.com/sms_status",
      callbackMethod: "POST",
    }

    message_body = body
    response.addMessage(message_body, params)

    xml = PlivoXML.new(response)

    puts xml.to_xml() # Prints the XML
    content_type "application/xml"
    return xml.to_s() # Returns the XML
  rescue PlivoXMLError => e
    puts "Exception: " + e.message
  end
end
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
var plivo = require('plivo');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.urlencoded({extended: true}));
app.set('port', (process.env.PORT || 5000));
app.all('/forward_sms/', function(request, response) {
    // Sender's phone number
    var from_number = request.body.From || request.query.From;
    // Receiver's phone number - Plivo number
    var to_number = request.body.To || request.query.To;
    // The text which was received
    var text = request.body.Text || request.query.Text;
    console.log ('Message received - From: ' + from_number + ', To: ' + to_number + ', Text: ' + text);

    // The phone number to which the SMS has to be forwarded
    var to_forward = '3333333333';
    var params = {
        'src' : to_number, // Sender's phone number
        'dst' : to_forward // Receiver's phone Number
    };
    var r = plivo.Response();
    r.addMessage(text, params);
    console.log (r.toXML());

    response.set({'Content-Type': 'text/xml'});
    response.end(r.toXML());
});

app.listen(app.get('port'), function() {
    console.log('Node app is running on port', app.get('port'));
});
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
<?php
    require 'vendor/autoload.php';
    use Plivo\Response;
    // Sender's phone numer
    $from_number = $_REQUEST["From"];
    // Receiver's phone number - Plivo number
    $to_number = $_REQUEST["To"];
    // The SMS text message which was received
    $text = $_REQUEST["Text"];
    // Output the text which was received, you could also store the text in a database.
    // echo("Message received - From $from_number, To: $to_number, Text: $text");
    // The phone number to which the SMS has to be forwarded
    $to_forward = '3333333333';
    $params = array(
        'src' => $to_number,
        'dst' => $to_forward
    );
    $body = $text;
    // Generate a Message XML with the details of
    // the reply to be sent.
    $r = new Response();
    $r->addMessage($body, $params);
    Header('Content-type: text/xml');
    echo($r->toXML());
?>
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
import static spark.Spark.*;
import com.plivo.api.xml.Message;
import com.plivo.api.xml.Response;

public class HelloWorld
{
    public static void main(String[] args)
    {
        get("/forward_sms", (request, response) -> {
            //Sender's phone number
            String from_number = request.queryParams("From");
            //Receiver's phone number - Plivo number
            String to_number = request.queryParams("To");
            //The text which was received
            String text = request.queryParams("Text");
            //Returns the response in application/xml type
            response.type("application/xml");
            //Print the message
            System.out.println(from_number +" "+to_number +" " + text);

            //The phone number to which the SMS has to be forwarded
            String to_forward = "17652348362";
            //send the details to generate an XML
            Response res = new Response()
                    .children(
                            //from_number.to_forward,text is being passed
                            new Message(from_number, to_forward, text)
                                    .callbackMethod("POST")
                                    .callbackUrl("http://foo.com/sms_status/")
                                    .type("sms")
                    );
            //Returns the XML
            return res.toXmlString();
        });
    }
}
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 (
	"net/http"

	"github.com/go-martini/martini"
	"github.com/plivo/plivo-go/xml"
)

func main() {
	m := martini.Classic()
	m.Get("/", func(w http.ResponseWriter, r *http.Request) string {
		w.Header().Set("Content-Type", "application/xml")
		// Sender's phone number
		fromnumber := r.FormValue("From")
		// Receiver's phone number - Plivo number
		tonumber := r.FormValue("To")
		// The text which was received
		text := r.FormValue("Text")
		// Print the message
		print("Message Received - ", fromnumber, " ", tonumber, " ", text)

		toforward := "17652348329"
		print(fromnumber)
		response := xml.ResponseElement{
			Contents: []interface{}{
				new(xml.MessageElement).
					SetCallbackMethod("POST").
					SetCallbackUrl("http://foo.com/sms status/").
					// Sender's phone number
					SetDst(toforward).
					// Receiver's phone number
					SetSrc(tonumber).
					SetType("sms").
					SetContents(text),
			},
		}
		print(response.String())
		return response.String()
	})
	m.Run()
}
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
using Nancy;
using System;
using System.Collections.Generic;
using System.Reflection;
using Plivo.XML;

namespace NancyStandalone
{
  public class FunctionsModule : NancyModule
  {
    public FunctionsModule()
    {
      Post("/delivery", parameters =>
      {
          // Sender's phone number
          String from_number = Request.Form["From"];
          // Receiver's phone number
          String to_number = Request.Form["To"];
          // The text which was received
          String text = Request.Form["Text"];
          // Print the message
          Console.WriteLine("Message received - From: {0}, To: {1}, Text: {2}", from_number, to_number, text);

          String to_forward = "1111111111"; // The phone number to which the sms has to be forwarded

          Plivo.XML.Response resp = new Plivo.XML.Response();

                // Generate the Message XML
                Plivo.XML.Response resp = new Plivo.XML.Response();
                resp.AddMessage(text,
                new Dictionary<string, string>()
                {
                  {"src", to_number},
                  {"dst", to_forward} ,
                  {"type", "sms"},
                  {"callbackUrl", "http://foo.com/sms_status/"},
                  {"callbackMethod", "POST"}
                  });
                  var output = resp.ToString();
                  var res = (Nancy.Response)output;
                  res.ContentType = "application/xml";
                  return res;
            };
        }
    }
}

Next Step

Learn how to get details of all your SMS messages.

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