Send SMS and MMS Messages in Java

In this guide, we'll show you how to send SMS and MMS messages from Java using Twilio's Programmable SMS. The code snippets in this guide target Java SDK 7 or higher, and make use of the Twilio Java Helper Library.

Outgoing SMS Diagram

Sign up for a Twilio Account

To use the Twilio REST API, you need an account. Signing up for a free Twilio account is easy. Once you've signed up, head over to your Console and grab your Account SID and your Auth Token. You will need those for the code samples below.

Purchase an SMS Capable Phone Number

Sending SMS messages requires an SMS capable phone number. You can browse the available phone numbers in the Console. Be sure that the phone number you buy is SMS capable. When you search, you can check the box to filter available numbers to those that are SMS capable:

Search for SMS Capable Number

When viewing the search results, you can see the capability icons in the list of available numbers:

Buy SMS Capable Number

Armed with a Twilio phone number, you can now start sending messages to mobile devices.

Send an SMS Message via the REST API with the Java Helper Library

Sending an outgoing SMS message requires sending an HTTP POST to the Messages resource URI. Using the helper library, you can create a new instance of the Message resource and specify the To, From, and Body parameters for your message.

Loading Code Samples...
Language
SDK Version:
  • 6.x
  • 7.x
Format:
  • JSON
  • XML
// You may want to be more specific in your imports
import java.util.*;
import com.twilio.sdk.*;
import com.twilio.sdk.resource.factory.*;
import com.twilio.sdk.resource.instance.*;
import com.twilio.sdk.resource.list.*;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

public class TwilioTest {
 // Find your Account Sid and Token at twilio.com/user/account
 public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
 public static final String AUTH_TOKEN = "your_auth_token";

 public static void main(String[]args) throws TwilioRestException {
  TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);

   // Build the parameters
   List<NameValuePair> params = new ArrayList<NameValuePair>();
   params.add(new BasicNameValuePair("To", "+15558675309"));
   params.add(new BasicNameValuePair("From", "+15017250604"));
   params.add(new BasicNameValuePair("Body", "This is the ship that made the Kessel Run in fourteen parsecs?"));

   MessageFactory messageFactory = client.getAccount().getMessageFactory();
   Message message = messageFactory.create(params);
   System.out.println(message.getSid());
 }
}
// Install the Java helper library from twilio.com/docs/java/install
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;

public class Example {
  // Find your Account Sid and Token at twilio.com/user/account
  public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  public static final String AUTH_TOKEN = "your_auth_token";

  public static void main(String[] args) {
    Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

    Message message = Message.creator(new PhoneNumber("+15558675309"),
        new PhoneNumber("+15017250604"), "This is the ship that made the Kessel Run in fourteen parsecs?").create();

    System.out.println(message.getSid());
  }
}
{
  "sid": "MMc781610ec0b3400c9e0cab8e757da937",
  "date_created": "Mon, 19 Oct 2015 07:07:03 +0000",
  "date_updated": "Mon, 19 Oct 2015 07:07:03 +0000",
  "date_sent": null,
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "to": "+15558675309",
  "from": "+15017250604",
  "body": "This is the ship that made the Kessel Run in fourteen parsecs?",
  "status": "queued",
  "num_segments": "1",
  "num_media": "0",
  "direction": "outbound-api",
  "api_version": "2010-04-01",
  "price": null,
  "price_unit": "USD",
  "error_code": null,
  "error_message": null,
  "uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMc781610ec0b3400c9e0cab8e757da937.json",
}
<?xml version='1.0' encoding='UTF-8'?>
<TwilioResponse>
<Message>
  <Sid>MMc781610ec0b3400c9e0cab8e757da937</Sid>
  <DateCreated>Mon, 19 Oct 2015 07:09:09 +0000</DateCreated>
  <DateUpdated>Mon, 19 Oct 2015 07:09:09 +0000</DateUpdated>
  <DateSent/>
  <AccountSid>ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</AccountSid>
  <To>+15558675309</To>
  <From>+15017250604</From>
  <Body>This is the ship that made the Kessel Run in fourteen parsecs?</Body>
  <Status>queued</Status>
  <NumSegments>1</NumSegments>
  <NumMedia>0</NumMedia>
  <Direction>outbound-api</Direction>
  <ApiVersion>2010-04-01</ApiVersion>
  <Price/>
  <PriceUnit>USD</PriceUnit>
  <ErrorCode/>
  <ErrorMessage/>
  <Uri>/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMf1150fe5baf04104a39c3f311a053e4e.xml</Uri>
  <SubresourceUris/>
</Message>
</TwilioResponse>
Send an SMS using the Programmable SMS API

If you want to send a message to several recipients, you could simply create an array of recipients and iterate through each phone number in that array. You can send as many messages as you like, as fast as you like and Twilio will queue them up for delivery at your prescribed rate limit. See our guide on how to Send Bulk SMS Messages for more tips.

Send a Message in Java with Media (MMS)

It's also easy to send an outgoing MMS using Twilio. To send an MMS, you also make an HTTP POST request to the Messages resource but this time specify a parameter for the URL of media, such as an image.

MMS messages can only be sent and received by numbers with MMS capability. You can check the capabilities of numbers in the account portal or query the Available Phone Numbers resource to search for Twilio numbers that are MMS enabled.

Loading Code Samples...
Language
SDK Version:
  • 6.x
  • 7.x
Format:
  • JSON
  • XML
// You may want to be more specific in your imports
import java.util.*;
import com.twilio.sdk.*;
import com.twilio.sdk.resource.factory.*;
import com.twilio.sdk.resource.instance.*;
import com.twilio.sdk.resource.list.*;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

public class TwilioTest {
 // Find your Account Sid and Token at twilio.com/user/account
 public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
 public static final String AUTH_TOKEN = "your_auth_token";

 public static void main(String[]args) throws TwilioRestException {
  TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);

   // Build the parameters
   List<NameValuePair> params = new ArrayList<NameValuePair>();
   params.add(new BasicNameValuePair("To", "+15558675309"));
   params.add(new BasicNameValuePair("From", "+15017250604"));
   params.add(new BasicNameValuePair("Body", "This is the ship that made the Kessel Run in fourteen parsecs?"));
   params.add(new BasicNameValuePair("MediaUrl", "https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg"));

   MessageFactory messageFactory = client.getAccount().getMessageFactory();
   Message message = messageFactory.create(params);
   System.out.println(message.getSid());
 }
}
// Install the Java helper library from twilio.com/docs/java/install
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;

public class Example {
  // Find your Account Sid and Token at twilio.com/user/account
  public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  public static final String AUTH_TOKEN = "your_auth_token";

  public static void main(String[] args) {
    Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

    Message message = Message
        .creator(new PhoneNumber("+15558675309"), new PhoneNumber("+15017250604"),
            "This is the ship that made the Kessel Run in fourteen parsecs?")
        .setMediaUrl("https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg")
        .create();

    System.out.println(message.getSid());
  }
}
{
  "sid": "MMc781610ec0b3400c9e0cab8e757da937",
  "date_created": "Mon, 19 Oct 2015 07:07:03 +0000",
  "date_updated": "Mon, 19 Oct 2015 07:07:03 +0000",
  "date_sent": null,
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "to": "+15558675309",
  "from": "+15017250604",
  "body": "This is the ship that made the Kessel Run in fourteen parsecs?",
  "status": "queued",
  "num_segments": "1",
  "num_media": "1",
  "direction": "outbound-api",
  "api_version": "2010-04-01",
  "price": null,
  "price_unit": "USD",
  "error_code": null,
  "error_message": null,
  "uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMc781610ec0b3400c9e0cab8e757da937.json",
  "subresource_uris": {
    "media": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMc781610ec0b3400c9e0cab8e757da937/Media.json"
  }
}
<?xml version='1.0' encoding='UTF-8'?>
<TwilioResponse>
<Message>
  <Sid>MMc781610ec0b3400c9e0cab8e757da937</Sid>
  <DateCreated>Mon, 19 Oct 2015 07:09:09 +0000</DateCreated>
  <DateUpdated>Mon, 19 Oct 2015 07:09:09 +0000</DateUpdated>
  <DateSent/>
  <AccountSid>ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</AccountSid>
  <To>+15558675309</To>
  <From>+15017250604</From>
  <Body>This is the ship that made the Kessel Run in fourteen parsecs?</Body>
  <Status>queued</Status>
  <NumSegments>1</NumSegments>
  <NumMedia>1</NumMedia>
  <Direction>outbound-api</Direction>
  <ApiVersion>2010-04-01</ApiVersion>
  <Price/>
  <PriceUnit>USD</PriceUnit>
  <ErrorCode/>
  <ErrorMessage/>
  <Uri>/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMf1150fe5baf04104a39c3f311a053e4e.xml</Uri>
  <SubresourceUris>
    <Media>/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMf1150fe5baf04104a39c3f311a053e4e/Media.xml</Media>
  </SubresourceUris>
</Message>
</TwilioResponse>
Send a Message with an Image URL

For more information about sending SMS and MMS messages with Twilio, see the REST API Reference.

Send a Message During a Phone Call (Voice TwiML)

You can also send SMS when someone calls your Twilio number. The <Sms> verb is a valid TwiML response to an incoming call. Here's some code that generates the necessary TwiML instructions to send a text message when a phone call comes in:

Loading Code Samples...
Language
SDK Version:
  • 6.x
  • 7.x
Format:
  • XML
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.Say;
import com.twilio.sdk.verbs.Sms;

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();
        try {
            twiml.append(new Say("Hello! You will get an SMS message soon."));
            twiml.append(new Sms("This is the ship that made the Kessel Run in fourteen parsecs?"));
        } catch (TwiMLException e) {
            e.printStackTrace();
        }

        response.setContentType("application/xml");
        response.getWriter().print(twiml.toXML());
    }
}
import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.twilio.twiml.Say;
import com.twilio.twiml.Sms;
import com.twilio.twiml.TwiMLException;
import com.twilio.twiml.VoiceResponse;

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 {
    Say say = new Say.Builder("Hello! You will get an SMS message soon.").build();
    Sms sms = new Sms.Builder("This is the ship that made the Kessel Run in fourteen parsecs?").build();

    VoiceResponse twiml = new VoiceResponse.Builder().say(say).sms(sms).build();

    response.setContentType("application/xml");

    try {
      response.getWriter().print(twiml.toXml());
    } catch (TwiMLException e) {
      e.printStackTrace();
    }
  }
}
<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say>Hello! You will get an SMS message soon.</Say>
    <Sms>This is the ship that made the Kessel Run in fourteen parsecs?</Sms>
</Response>
Send SMS during voice call

If you were to visit that webhook url in your browser, you would see TwiML that looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say>Hello! You will get an SMS message soon.</Say>
    <Sms>This is the ship that made the Kessel Run in fourteen parsecs?</Sms>
</Response>

Save a publicly-accessible URL to return that XML. Then, configure that URL to be the Voice URL of your Twilio phone number.

Call that number from a mobile phone -- you should hear a message and get a text message in response.

Going Further with Java, MMSes and SMSes

Want to build more messaging functionality into your Java Application?  Also try our Java SMS Quickstart, and see how to receive and reply to messages in Java.

Agustin Camino
David Prothero
Jarod Reyes
Paul Kamp
Ricky Robinett

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:
  • 6.x
  • 7.x
Format:
  • JSON
  • XML
// You may want to be more specific in your imports
import java.util.*;
import com.twilio.sdk.*;
import com.twilio.sdk.resource.factory.*;
import com.twilio.sdk.resource.instance.*;
import com.twilio.sdk.resource.list.*;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

public class TwilioTest {
 // Find your Account Sid and Token at twilio.com/user/account
 public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
 public static final String AUTH_TOKEN = "your_auth_token";

 public static void main(String[]args) throws TwilioRestException {
  TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);

   // Build the parameters
   List<NameValuePair> params = new ArrayList<NameValuePair>();
   params.add(new BasicNameValuePair("To", "+15558675309"));
   params.add(new BasicNameValuePair("From", "+15017250604"));
   params.add(new BasicNameValuePair("Body", "This is the ship that made the Kessel Run in fourteen parsecs?"));

   MessageFactory messageFactory = client.getAccount().getMessageFactory();
   Message message = messageFactory.create(params);
   System.out.println(message.getSid());
 }
}
// Install the Java helper library from twilio.com/docs/java/install
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;

public class Example {
  // Find your Account Sid and Token at twilio.com/user/account
  public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  public static final String AUTH_TOKEN = "your_auth_token";

  public static void main(String[] args) {
    Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

    Message message = Message.creator(new PhoneNumber("+15558675309"),
        new PhoneNumber("+15017250604"), "This is the ship that made the Kessel Run in fourteen parsecs?").create();

    System.out.println(message.getSid());
  }
}
{
  "sid": "MMc781610ec0b3400c9e0cab8e757da937",
  "date_created": "Mon, 19 Oct 2015 07:07:03 +0000",
  "date_updated": "Mon, 19 Oct 2015 07:07:03 +0000",
  "date_sent": null,
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "to": "+15558675309",
  "from": "+15017250604",
  "body": "This is the ship that made the Kessel Run in fourteen parsecs?",
  "status": "queued",
  "num_segments": "1",
  "num_media": "0",
  "direction": "outbound-api",
  "api_version": "2010-04-01",
  "price": null,
  "price_unit": "USD",
  "error_code": null,
  "error_message": null,
  "uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMc781610ec0b3400c9e0cab8e757da937.json",
}
<?xml version='1.0' encoding='UTF-8'?>
<TwilioResponse>
<Message>
  <Sid>MMc781610ec0b3400c9e0cab8e757da937</Sid>
  <DateCreated>Mon, 19 Oct 2015 07:09:09 +0000</DateCreated>
  <DateUpdated>Mon, 19 Oct 2015 07:09:09 +0000</DateUpdated>
  <DateSent/>
  <AccountSid>ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</AccountSid>
  <To>+15558675309</To>
  <From>+15017250604</From>
  <Body>This is the ship that made the Kessel Run in fourteen parsecs?</Body>
  <Status>queued</Status>
  <NumSegments>1</NumSegments>
  <NumMedia>0</NumMedia>
  <Direction>outbound-api</Direction>
  <ApiVersion>2010-04-01</ApiVersion>
  <Price/>
  <PriceUnit>USD</PriceUnit>
  <ErrorCode/>
  <ErrorMessage/>
  <Uri>/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMf1150fe5baf04104a39c3f311a053e4e.xml</Uri>
  <SubresourceUris/>
</Message>
</TwilioResponse>
SDK Version:
  • 6.x
  • 7.x
Format:
  • JSON
  • XML
// You may want to be more specific in your imports
import java.util.*;
import com.twilio.sdk.*;
import com.twilio.sdk.resource.factory.*;
import com.twilio.sdk.resource.instance.*;
import com.twilio.sdk.resource.list.*;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

public class TwilioTest {
 // Find your Account Sid and Token at twilio.com/user/account
 public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
 public static final String AUTH_TOKEN = "your_auth_token";

 public static void main(String[]args) throws TwilioRestException {
  TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);

   // Build the parameters
   List<NameValuePair> params = new ArrayList<NameValuePair>();
   params.add(new BasicNameValuePair("To", "+15558675309"));
   params.add(new BasicNameValuePair("From", "+15017250604"));
   params.add(new BasicNameValuePair("Body", "This is the ship that made the Kessel Run in fourteen parsecs?"));
   params.add(new BasicNameValuePair("MediaUrl", "https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg"));

   MessageFactory messageFactory = client.getAccount().getMessageFactory();
   Message message = messageFactory.create(params);
   System.out.println(message.getSid());
 }
}
// Install the Java helper library from twilio.com/docs/java/install
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;

public class Example {
  // Find your Account Sid and Token at twilio.com/user/account
  public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  public static final String AUTH_TOKEN = "your_auth_token";

  public static void main(String[] args) {
    Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

    Message message = Message
        .creator(new PhoneNumber("+15558675309"), new PhoneNumber("+15017250604"),
            "This is the ship that made the Kessel Run in fourteen parsecs?")
        .setMediaUrl("https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg")
        .create();

    System.out.println(message.getSid());
  }
}
{
  "sid": "MMc781610ec0b3400c9e0cab8e757da937",
  "date_created": "Mon, 19 Oct 2015 07:07:03 +0000",
  "date_updated": "Mon, 19 Oct 2015 07:07:03 +0000",
  "date_sent": null,
  "account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "to": "+15558675309",
  "from": "+15017250604",
  "body": "This is the ship that made the Kessel Run in fourteen parsecs?",
  "status": "queued",
  "num_segments": "1",
  "num_media": "1",
  "direction": "outbound-api",
  "api_version": "2010-04-01",
  "price": null,
  "price_unit": "USD",
  "error_code": null,
  "error_message": null,
  "uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMc781610ec0b3400c9e0cab8e757da937.json",
  "subresource_uris": {
    "media": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMc781610ec0b3400c9e0cab8e757da937/Media.json"
  }
}
<?xml version='1.0' encoding='UTF-8'?>
<TwilioResponse>
<Message>
  <Sid>MMc781610ec0b3400c9e0cab8e757da937</Sid>
  <DateCreated>Mon, 19 Oct 2015 07:09:09 +0000</DateCreated>
  <DateUpdated>Mon, 19 Oct 2015 07:09:09 +0000</DateUpdated>
  <DateSent/>
  <AccountSid>ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</AccountSid>
  <To>+15558675309</To>
  <From>+15017250604</From>
  <Body>This is the ship that made the Kessel Run in fourteen parsecs?</Body>
  <Status>queued</Status>
  <NumSegments>1</NumSegments>
  <NumMedia>1</NumMedia>
  <Direction>outbound-api</Direction>
  <ApiVersion>2010-04-01</ApiVersion>
  <Price/>
  <PriceUnit>USD</PriceUnit>
  <ErrorCode/>
  <ErrorMessage/>
  <Uri>/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMf1150fe5baf04104a39c3f311a053e4e.xml</Uri>
  <SubresourceUris>
    <Media>/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MMf1150fe5baf04104a39c3f311a053e4e/Media.xml</Media>
  </SubresourceUris>
</Message>
</TwilioResponse>
SDK Version:
  • 6.x
  • 7.x
Format:
  • XML
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.Say;
import com.twilio.sdk.verbs.Sms;

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();
        try {
            twiml.append(new Say("Hello! You will get an SMS message soon."));
            twiml.append(new Sms("This is the ship that made the Kessel Run in fourteen parsecs?"));
        } catch (TwiMLException e) {
            e.printStackTrace();
        }

        response.setContentType("application/xml");
        response.getWriter().print(twiml.toXML());
    }
}
import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.twilio.twiml.Say;
import com.twilio.twiml.Sms;
import com.twilio.twiml.TwiMLException;
import com.twilio.twiml.VoiceResponse;

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 {
    Say say = new Say.Builder("Hello! You will get an SMS message soon.").build();
    Sms sms = new Sms.Builder("This is the ship that made the Kessel Run in fourteen parsecs?").build();

    VoiceResponse twiml = new VoiceResponse.Builder().say(say).sms(sms).build();

    response.setContentType("application/xml");

    try {
      response.getWriter().print(twiml.toXml());
    } catch (TwiMLException e) {
      e.printStackTrace();
    }
  }
}
<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say>Hello! You will get an SMS message soon.</Say>
    <Sms>This is the ship that made the Kessel Run in fourteen parsecs?</Sms>
</Response>