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

Prerequisites

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

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. Lets 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
37
38
from flask import Flask, request, make_response, Response
import plivo, 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)

    # Generate a Message XML with the details of the reply to be sent
    resp = plivoxml.Response()

    # The phone number to which the SMS has to be forwarded
    to_forward = '3333333333'
    body = 'Forwarded message : %s' % (text)
    params = {
        'src' : to_number, # Sender's phone number
        'dst' : to_forward, # Receiver's phone number
    }

    # Message added
    resp.addMessage(body, **params)

    # Prints the XML
    print resp.to_xml()
    # Returns the XML
    return Response(str(resp),mimetype='text/xml')

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80, 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
require 'rubygems'
require 'plivo'
require 'sinatra'
include Plivo

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 = '3333333333'
    params = {
        'src' => to_number, # Sender's phone number
        'dst' => to_forward # Receiver's phone Number
    }

    r = Response.new()
    r.addMessage(body,params)

    # Prints the XML
    puts r.to_xml()
    # Returns the XML
    content_type 'text/xml'
    return r.to_s()
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.plivo.test;

import java.io.IOException;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.plivo.helper.exception.PlivoException;
import com.plivo.helper.xml.elements.Message;
import com.plivo.helper.xml.elements.PlivoResponse;

public class forwardSms extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String from_number = req.getParameter("From");
        String to_number = req.getParameter("To");
        String text = req.getParameter("Text");
        System.out.println("Message received - From: " + from_number + ", To: " + to_number + ", Text: " + text);
        String to_forward = "3333333333";
        Message msg = new Message(text);
        msg.setSource(to_number);
        msg.setDestination(to_forward);
        try {
            PlivoResponse response = new PlivoResponse();
            response.append(msg);
            System.out.println(response.toXML());
            resp.addHeader("Content-Type", "text/xml");
            resp.getWriter().print(response.toXML());;
        } catch (PlivoException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        String port = System.getenv("PORT");
        if(port==null)
            port ="8080";
        Server server = new Server(Integer.valueOf(port));
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);
        context.addServlet(new ServletHolder(new forwardSms()),"/forward_sms/");
        server.start();
        server.join();
    }
}
 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
using System;
using System.Collections.Generic;
using System.Reflection;
using Nancy;
using RestSharp;
using Plivo.API;

namespace Forward_Incoming_Sms
{
    public class Program : NancyModule
    {
        public Program()
        {
            Post["/forward_sms/"] = x =>
            {
                String from_number = Request.Form["From"]; // Sender's phone number
                String to_number = Request.Form["To"]; // Receiver's phone number
                String text = Request.Form["Text"]; // The text which was received

                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
                resp.AddMessage(text, new Dictionary<string, string>() {
                    { "src", to_number },
                    { "dst", to_forward }
                });

                // Print the XML
                Console.WriteLine(resp.ToString());

                // Return the XML
                var output = resp.ToString();
                var res = (Nancy.Response)output;
                res.ContentType = "text/xml";
                return res;
            };
        }
    }
}

Create an Application

  1. Create an Application by visiting the Application Page and click on 'New Application' or by using Plivo’s Application API.
  2. Give your application a name. Lets call it 'Forward SMS'. Enter your server URL (e.g., http://example.com/forward_sms/) in the 'Message URL' field and set the method as 'POST'. See our Application API docs to learn how to modify your application through our APIs.
  3. Click on 'Create' to save your application.

Create Forward SMS Application

Assign a Plivo number to your app

  1. Navigate to the Numbers page and select the phone number you want to use for this app.
  2. Select 'Forward SMS' (name of the app) from the Plivo App dropdown list.
  3. Click on 'Update' to save.

Assign Phone Number to Forward SMS App

If you don’t have a number, go to the Buy Number page to purchase a Plivo phone number.

SMS Phone Number Search

Sample Response

Console Output when message received:

Message received - From: 1111111111, To: 2222222222, Text: Hello, from Plivo

XML response generated:

<Response>
    <Message dst="3333333333" src="2222222222">
        Forwarded message : Hello, from Plivo
    </Message>
</Response>

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. Get Details of all Messages
  8. Get Details of a Single Message
  9. Handling SMS Delivery Reports
  10. Forward SMS to Email