Receive and Reply to SMS and MMS Messages

In this guide, we'll show you how to use Programmable SMS to respond to incoming SMS messages in your web application. Code on your server can decide what happens when someone texts the number you've bought or ported to Twilio.

Choose a language and let's get started!

Loading Code Samples...
Language
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 6.x
  • 7.x
SDK Version:
  • 2.x
  • 3.x
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 5.x
  • 6.x
SDK Version:
  • 4.x
  • 5.x
Format:
  • XML
var http = require('http');
var express = require('express');
var twilio = require('twilio');

var app = express();

app.post('/sms', function(req, res) {
  var twilio = require('twilio');
  var twiml = new twilio.TwimlResponse();
  twiml.message('The Robots are coming! Head for the hills!');
  res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});

http.createServer(app).listen(1337, function () {
  console.log("Express server listening on port 1337");
});
const http = require('http');
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;

const app = express();

app.post('/sms', (req, res) => {
  const twiml = new MessagingResponse();

  twiml.message('The Robots are coming! Head for the hills!');

  res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});

http.createServer(app).listen(1337, () => {
  console.log('Express server listening on port 1337');
});
// In Package Manager, run:
// Install-Package Twilio.Mvc -DependencyVersion HighestMinor

using System.Web.Mvc;
using Twilio.Mvc;
using Twilio.TwiML;
using Twilio.TwiML.Mvc;

public class SmsController : TwilioController
{
    [HttpPost]
    public ActionResult Index(SmsRequest request)
    {
        var response = new TwilioResponse();
        response.Message("The Robots are coming! Head for the hills!");
        return TwiML(response);
    }
}
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php

// this line loads the library 
require('/path/to/twilio-php/Services/Twilio.php'); 

$response = new Services_Twilio_Twiml;
$response->message("The Robots are coming! Head for the hills!");
print $response;
require 'twilio-ruby'
require 'sinatra'

post '/sms' do
  twiml = Twilio::TwiML::Response.new do |r|
    r.Message 'The Robots are coming! Head for the hills!'
  end

  content_type 'text/xml'
  twiml.text
end
// In Package Manager, run:
// Install-Package Twilio.AspNet.Mvc -DependencyVersion HighestMinor

using System.Web.Mvc;
using Twilio.AspNet.Mvc;
using Twilio.TwiML;

public class SmsController : TwilioController
{
    [HttpPost]
    public ActionResult Index()
    {
        var messagingResponse = new MessagingResponse();
        messagingResponse.Message("The Robots are coming! Head for the hills!");

        return TwiML(messagingResponse);
    }
}
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php

require_once '/path/to/vendor/autoload.php'; // Loads the library
use Twilio\Twiml;

$response = new Twiml;
$response->message("The Robots are coming! Head for the hills!");
print $response;
from flask import Flask, request, redirect
from twilio import twiml

app = Flask(__name__)

@app.route("/sms", methods=['GET', 'POST'])
def sms_reply():
    """Respond to incoming calls with a simple text message."""
    # Start our TwiML response
    resp = twiml.Response()

    # Add a message
    resp.message("The Robots are coming! Head for the hills!")

    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)
require 'twilio-ruby'
require 'sinatra'

# Respond to incoming calls with a simple text message
post '/sms' do
  twiml = Twilio::TwiML::MessagingResponse.new do |r|
    r.message body: 'The Robots are coming! Head for the hills!'
  end

  content_type 'text/xml'

  twiml.to_s
end
package com.twilio;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import com.twilio.sdk.verbs.TwiMLResponse;
import com.twilio.sdk.verbs.TwiMLException;
import com.twilio.sdk.verbs.Message;

public class TwilioServlet extends HttpServlet {
  // service() responds to both GET and POST requests.
  // You can also use doGet() or doPost()
  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    TwiMLResponse twiml = new TwiMLResponse();
    Message message = new Message("The Robots are coming! Head for the hills!");
    try {
        twiml.append(message);
    } catch (TwiMLException e) {
        e.printStackTrace();
    }

    response.setContentType("application/xml");
    response.getWriter().print(twiml.toXML());
  }
}
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse

app = Flask(__name__)

@app.route("/sms", methods=['GET', 'POST'])
def sms_reply():
    """Respond to incoming calls with a simple text message."""
    # Start our TwiML response
    resp = MessagingResponse()

    # Add a message
    resp.message("The Robots are coming! Head for the hills!")

    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import com.twilio.twiml.Body;
import com.twilio.twiml.Message;
import com.twilio.twiml.MessagingResponse;
import com.twilio.twiml.TwiMLException;

public class TwilioServlet extends HttpServlet {

  // service() responds to both GET and POST requests.
  // You can also use doGet() or doPost()
  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Message sms =
      new Message.Builder().body(new Body("The Robots are coming! Head for the hills!")).build();

    MessagingResponse twiml = new MessagingResponse.Builder().message(sms).build();

    response.setContentType("application/xml");

    try {
      response.getWriter().print(twiml.toXml());
    } catch (TwiMLException e) {
      e.printStackTrace();
    }
  }
}
testable: false
<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Message>The Robots are coming! Head for the hills!</Message>
</Response>
When your phone number receives an incoming message, Twilio will send an HTTP request to your server. This code shows how your server should respond to reply with a text message (using TwiML).
Respond to an incoming text message

When your phone number receives an incoming message, Twilio will send an HTTP request to your server. This code shows how your server should respond to reply with a text message (using TwiML).

Incoming SMS Diagram
Jarod Reyes
David Prothero
Mario Celi

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

1 / 1
Loading Code Samples...
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 6.x
  • 7.x
SDK Version:
  • 2.x
  • 3.x
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 5.x
  • 6.x
SDK Version:
  • 4.x
  • 5.x
Format:
  • XML
var http = require('http');
var express = require('express');
var twilio = require('twilio');

var app = express();

app.post('/sms', function(req, res) {
  var twilio = require('twilio');
  var twiml = new twilio.TwimlResponse();
  twiml.message('The Robots are coming! Head for the hills!');
  res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});

http.createServer(app).listen(1337, function () {
  console.log("Express server listening on port 1337");
});
const http = require('http');
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;

const app = express();

app.post('/sms', (req, res) => {
  const twiml = new MessagingResponse();

  twiml.message('The Robots are coming! Head for the hills!');

  res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});

http.createServer(app).listen(1337, () => {
  console.log('Express server listening on port 1337');
});
// In Package Manager, run:
// Install-Package Twilio.Mvc -DependencyVersion HighestMinor

using System.Web.Mvc;
using Twilio.Mvc;
using Twilio.TwiML;
using Twilio.TwiML.Mvc;

public class SmsController : TwilioController
{
    [HttpPost]
    public ActionResult Index(SmsRequest request)
    {
        var response = new TwilioResponse();
        response.Message("The Robots are coming! Head for the hills!");
        return TwiML(response);
    }
}
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php

// this line loads the library 
require('/path/to/twilio-php/Services/Twilio.php'); 

$response = new Services_Twilio_Twiml;
$response->message("The Robots are coming! Head for the hills!");
print $response;
require 'twilio-ruby'
require 'sinatra'

post '/sms' do
  twiml = Twilio::TwiML::Response.new do |r|
    r.Message 'The Robots are coming! Head for the hills!'
  end

  content_type 'text/xml'
  twiml.text
end
// In Package Manager, run:
// Install-Package Twilio.AspNet.Mvc -DependencyVersion HighestMinor

using System.Web.Mvc;
using Twilio.AspNet.Mvc;
using Twilio.TwiML;

public class SmsController : TwilioController
{
    [HttpPost]
    public ActionResult Index()
    {
        var messagingResponse = new MessagingResponse();
        messagingResponse.Message("The Robots are coming! Head for the hills!");

        return TwiML(messagingResponse);
    }
}
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php

require_once '/path/to/vendor/autoload.php'; // Loads the library
use Twilio\Twiml;

$response = new Twiml;
$response->message("The Robots are coming! Head for the hills!");
print $response;
from flask import Flask, request, redirect
from twilio import twiml

app = Flask(__name__)

@app.route("/sms", methods=['GET', 'POST'])
def sms_reply():
    """Respond to incoming calls with a simple text message."""
    # Start our TwiML response
    resp = twiml.Response()

    # Add a message
    resp.message("The Robots are coming! Head for the hills!")

    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)
require 'twilio-ruby'
require 'sinatra'

# Respond to incoming calls with a simple text message
post '/sms' do
  twiml = Twilio::TwiML::MessagingResponse.new do |r|
    r.message body: 'The Robots are coming! Head for the hills!'
  end

  content_type 'text/xml'

  twiml.to_s
end
package com.twilio;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import com.twilio.sdk.verbs.TwiMLResponse;
import com.twilio.sdk.verbs.TwiMLException;
import com.twilio.sdk.verbs.Message;

public class TwilioServlet extends HttpServlet {
  // service() responds to both GET and POST requests.
  // You can also use doGet() or doPost()
  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    TwiMLResponse twiml = new TwiMLResponse();
    Message message = new Message("The Robots are coming! Head for the hills!");
    try {
        twiml.append(message);
    } catch (TwiMLException e) {
        e.printStackTrace();
    }

    response.setContentType("application/xml");
    response.getWriter().print(twiml.toXML());
  }
}
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse

app = Flask(__name__)

@app.route("/sms", methods=['GET', 'POST'])
def sms_reply():
    """Respond to incoming calls with a simple text message."""
    # Start our TwiML response
    resp = MessagingResponse()

    # Add a message
    resp.message("The Robots are coming! Head for the hills!")

    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import com.twilio.twiml.Body;
import com.twilio.twiml.Message;
import com.twilio.twiml.MessagingResponse;
import com.twilio.twiml.TwiMLException;

public class TwilioServlet extends HttpServlet {

  // service() responds to both GET and POST requests.
  // You can also use doGet() or doPost()
  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Message sms =
      new Message.Builder().body(new Body("The Robots are coming! Head for the hills!")).build();

    MessagingResponse twiml = new MessagingResponse.Builder().message(sms).build();

    response.setContentType("application/xml");

    try {
      response.getWriter().print(twiml.toXml());
    } catch (TwiMLException e) {
      e.printStackTrace();
    }
  }
}
testable: false
<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Message>The Robots are coming! Head for the hills!</Message>
</Response>