-
Notifications
You must be signed in to change notification settings - Fork 0
Home
In this quickstart, you'll build your first application to programmatically send and receive text messages with Twilio Programmable Messaging. This quickstart uses the Programmable Messaging REST API, the Twilio SDKs, and the Twilio Virtual Phone.
For a no-code quickstart, see No-code programmable messaging quickstart with Twilio Studio.
Select your programming language and complete the prerequisites:
-
Install Flask and Twilio's Python SDK. To install using pip, run:
pip install flask twilio
-
Install the Twilio Node.js SDK:
npm install twilio
-
Install dependencies with Composer:
-
Install the Twilio PHP SDK:
composer require twilio/sdk composer install
- Install Java Standard Edition (SE) Development Kit.
- Install and set up ngrok.
- Download the Twilio Java SDK fat jar file with all dependencies:
- Navigate to the Maven repository.
- Click the most recent version number.
- In the Files row, click View All.
- Click the file ending in
jar-with-dependencies.jar.
- Install IntelliJ IDEA Community Edition.
- Sign up for Twilio. When prompted to select a plan, click Continue with trial.
- To get a phone that has SMS capabilities, do either of the following:
- In the Account Dashboard, click Get a phone number.
- In the navigation menu, go to Phone Numbers > Manage > Buy a number.
- In the Account Dashboard, copy your Account SID and Auth Token and paste them in a temporary local file for use later in this quickstart.
The Twilio Virtual Phone lets you try Twilio quickly regardless of your country's regulations for messaging mobile handsets. To message a mobile handset, see Send SMS and MMS messages.
- Open the Send an SMS page in the Twilio Console.
- On the Send to Virtual Phone tab, select the number that Twilio gave you from the Phone number list.
- Click Virtual Phone. Messages you send with your application display on the Virtual Phone.
Follow these steps to send an SMS message from your Twilio phone number.
-
Create and open a new file called
send_sms.pyanywhere on your machine and paste in the following code:Send an SMS Using Twilio with Python
# Download the helper library from https://www.twilio.com/docs/python/install import os from twilio.rest import Client # Find your Account SID and Auth Token at twilio.com/console # and set the environment variables. See http://twil.io/secure account_sid = os.environ["TWILIO_ACCOUNT_SID"] auth_token = os.environ["TWILIO_AUTH_TOKEN"] client = Client(account_sid, auth_token) message = client.messages.create( body="Join Earth's mightiest heroes. Like Kevin Bacon.", from_="+15017122661", to="+15558675310", ) print(message.body)
-
In the
send_sms.pyfile, replace the values foraccount_sidandauth_tokenwith your Account SID and Auth Token surrounded by quotation marks.[!CAUTION]
This quickstart hardcodes your credentials for faster setup. To keep credentials secret and control access when you deploy to production, use environment variables and API keys.
-
Replace the value for
fromwith the phone number that Twilio gave you in E.164 format. -
Replace the value for
towith the Twilio Virtual Phone number (+18777804236). -
Save your changes and run this command from your terminal in the directory that contains
send_sms.py:python send_sms.py
After a few moments, you receive an SMS from your Twilio number on the Twilio Virtual Phone.
-
Create and open a new file called
send_sms.jsanywhere on your machine and paste in the following code:Send an SMS Using Twilio with Node.js
// Download the helper library from https://www.twilio.com/docs/node/install const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio"; // Find your Account SID and Auth Token at twilio.com/console // and set the environment variables. See http://twil.io/secure const accountSid = process.env.TWILIO_ACCOUNT_SID; const authToken = process.env.TWILIO_AUTH_TOKEN; const client = twilio(accountSid, authToken); async function createMessage() { const message = await client.messages.create({ body: "This is the ship that made the Kessel Run in fourteen parsecs?", from: "+15017122661", to: "+15558675310", }); console.log(message.body); } createMessage();
-
In the
send_sms.jsfile, replace the values foraccountSidandauthTokenwith your Account SID and Auth Token surrounded by quotation marks.[!CAUTION]
This quickstart hardcodes your credentials for faster setup. To keep credentials secret and control access when you deploy to production, use environment variables and API keys.
-
Replace the value for
fromwith the phone number that Twilio gave you in E.164 format. -
Replace the value for
towith the Twilio Virtual Phone number (+18777804236). -
Save your changes and run this command from your terminal in the directory that contains
send_sms.js:node send_sms.js
After a few moments, you receive an SMS from your Twilio number on the Twilio Virtual Phone.
-
Create and open a new file called
send_sms.phpin the project directory and paste in the following code:Send an SMS Using Twilio with PHP
<?php // Update the path below to your autoload.php, // see https://getcomposer.org/doc/01-basic-usage.md require_once "/path/to/vendor/autoload.php"; use Twilio\Rest\Client; // Find your Account SID and Auth Token at twilio.com/console // and set the environment variables. See http://twil.io/secure $sid = getenv("TWILIO_ACCOUNT_SID"); $token = getenv("TWILIO_AUTH_TOKEN"); $twilio = new Client($sid, $token); $message = $twilio->messages->create( "+15558675310", // To [ "body" => "This is the ship that made the Kessel Run in fourteen parsecs?", "from" => "+15017122661", ] ); print $message->body;
-
In the
send_sms.phpfile, replace the values for$sidand$tokenwith your Account SID and Auth Token surrounded by quotation marks.[!CAUTION]
This quickstart hardcodes your credentials for faster setup. To keep credentials secret and control access when you deploy to production, use environment variables and API keys.
-
Replace the value for
fromwith the phone number that Twilio gave you in E.164 format. -
Replace the value for
Towith the Twilio Virtual Phone number (+18777804236). -
Update line 5 of
send_sms.phptorequire __DIR__ . '/vendor/autoload.php'; -
Save your changes and run this command from your terminal in the directory that contains
send_sms.php:php send_sms.php
After a few moments, you receive an SMS from your Twilio number on the Twilio Virtual Phone.
-
Create and set up a new project in Visual Studio:
- Open Visual Studio and click Create a new project.
- Click Console App (.NET Framework).
- Use the NuGet Package Manager to install the Twilio REST API SDK.
-
Open the file in your new Visual Studio project called
Program.csand paste in the following code, replacing the existing template code:Send an SMS Using Twilio with C# (.NET Framework)
// Install the C# / .NET helper library from twilio.com/docs/csharp/install using System; using Twilio; using Twilio.Rest.Api.V2010.Account; using System.Threading.Tasks; class Program { public static async Task Main(string[] args) { // Find your Account SID and Auth Token at twilio.com/console // and set the environment variables. See http://twil.io/secure string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID"); string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN"); TwilioClient.Init(accountSid, authToken); var message = await MessageResource.CreateAsync( body: "Join Earth's mightiest heroes. Like Kevin Bacon.", from: new Twilio.Types.PhoneNumber("+15017122661"), to: new Twilio.Types.PhoneNumber("+15558675310")); Console.WriteLine(message.Body); } }
-
In the
Program.csfile, replace the values foraccountSidandauthTokenwith your Account SID and Auth Token surrounded by quotation marks.[!CAUTION]
This quickstart hardcodes your credentials for faster setup. To keep credentials secret and control access when you deploy to production, use environment variables and API keys.
-
Replace the value for
from: new Twilio.Types.PhoneNumberwith the phone number that Twilio gave you in E.164 format. -
Replace the value for
to: new Twilio.Types.PhoneNumberwith the Twilio Virtual Phone number (+18777804236). -
Save your changes and run your project in Visual Studio.
After a few moments, you receive an SMS from your Twilio number on the Twilio Virtual Phone.
-
Run the following commands to create a new .NET project and install the Twilio NuGet package:
mkdir TwilioSend cd TwilioSend dotnet new console dotnet add package Twilio -
Open the file in your new project called
Program.csand paste in the following code, replacing the existing template code:Send an SMS Using Twilio with C# (.NET Core)
// Install the C# / .NET helper library from twilio.com/docs/csharp/install using System; using Twilio; using Twilio.Rest.Api.V2010.Account; using System.Threading.Tasks; class Program { public static async Task Main(string[] args) { // Find your Account SID and Auth Token at twilio.com/console // and set the environment variables. See http://twil.io/secure string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID"); string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN"); TwilioClient.Init(accountSid, authToken); var message = await MessageResource.CreateAsync( body: "Join Earth's mightiest heroes. Like Kevin Bacon.", from: new Twilio.Types.PhoneNumber("+15017122661"), to: new Twilio.Types.PhoneNumber("+15558675310")); Console.WriteLine(message.Body); } }
-
In the
Program.csfile, replace the values foraccountSidandauthTokenwith your Account SID and Auth Token surrounded by quotation marks.[!CAUTION]
This quickstart hardcodes your credentials for faster setup. To keep credentials secret and control access when you deploy to production, use environment variables and API keys.
-
Replace the value for
from: new Twilio.Types.PhoneNumberwith the phone number that Twilio gave you in E.164 format. -
Replace the value for
to: new Twilio.Types.PhoneNumberwith the Twilio Virtual Phone number (+18777804236). -
Save your changes and run this command in the directory that contains
Program.cs:dotnet run
After a few moments, you receive an SMS from your Twilio number on the Twilio Virtual Phone.
-
Create and open a new file called
Example.javain the same directory as the fat jar file and paste in the following code:Send an SMS Using Twilio with Java
// Install the Java helper library from twilio.com/docs/java/install import com.twilio.type.PhoneNumber; import com.twilio.Twilio; import com.twilio.rest.api.v2010.account.Message; public class Example { // Find your Account SID and Auth Token at twilio.com/console // and set the environment variables. See http://twil.io/secure public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID"); public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN"); public static void main(String[] args) { Twilio.init(ACCOUNT_SID, AUTH_TOKEN); Message message = Message .creator(new com.twilio.type.PhoneNumber("+15558675310"), new com.twilio.type.PhoneNumber("+15017122661"), "This is the ship that made the Kessel Run in fourteen parsecs?") .create(); System.out.println(message.getBody()); } }
-
In the
Example.javafile, replace the values forACCOUNT_SIDandAUTH_TOKENwith your Account SID and Auth Token surrounded by quotation marks.[!CAUTION]
This quickstart hardcodes your credentials for faster setup. To keep credentials secret and control access when you deploy to production, use environment variables and API keys.
-
Replace the value for the first phone number with the Twilio Virtual Phone number (
+18777804236). -
Replace the value for the second phone number with the phone number that Twilio gave you in E.164 format.
-
Save your changes and compile the Java from your terminal in the directory that contains
Example.java. Replace10.9.0with the version of your fat jar file.javac -cp twilio-10.9.0-jar-with-dependencies.jar Example.java
-
Run the Java. Replace
10.9.0with the version of your fat jar file.On Linux or macOS, run:
java -cp .:twilio-10.9.0-jar-with-dependencies.jar Example
On Windows, run:
java -cp ".;twilio-10.9.0-jar-with-dependencies.jar" ExampleAfter a few moments, you receive an SMS from your Twilio number on the Twilio Virtual Phone.
-
Create and set up your Go project.
-
Create a new Go project by running the following command:
go mod init twilio-example
-
Install the Gin Framework:
go get -u github.com/gin-gonic/gin
-
Install the Twilio Go SDK:
go get github.com/twilio/twilio-go
-
Install the TwiML dependency:
go get github.com/twilio/twilio-go/twiml@latest
-
-
Create and open a new file called
send_sms.goin your Go project directory and paste in the following code:Send an SMS Using Twilio with Go
// Download the helper library from https://www.twilio.com/docs/go/install package main import ( "fmt" "github.com/twilio/twilio-go" api "github.com/twilio/twilio-go/rest/api/v2010" "os" ) func main() { // Find your Account SID and Auth Token at twilio.com/console // and set the environment variables. See http://twil.io/secure // Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment client := twilio.NewRestClient() params := &api.CreateMessageParams{} params.SetBody("Join Earth's mightiest heroes. Like Kevin Bacon.") params.SetFrom("+15017122661") params.SetTo("+15558675310") resp, err := client.Api.CreateMessage(params) if err != nil { fmt.Println(err.Error()) os.Exit(1) } else { if resp.Body != nil { fmt.Println(*resp.Body) } else { fmt.Println(resp.Body) } } }
-
Run the following command in the terminal to set your environment variables. Replace
<your-account-sid>and<your-auth-token>with your Account SID and Auth Token:export TWILIO_ACCOUNT_SID=<your-account-sid> export TWILIO_AUTH_TOKEN=<your-auth-token>
To learn more, see Store your Twilio credentials securely.
-
Replace the value for
params.SetFromwith the phone number that Twilio gave you in E.164 format. -
Replace the value for
params.SetTowith the Twilio Virtual Phone number (+18777804236). -
Save your changes and run this command in the directory that contains
send_sms.go:go run send_sms.go
After a few moments, you receive an SMS from your Twilio number on the Twilio Virtual Phone.
-
Create and open a new file called
send_sms.rbanywhere on your machine and paste in the following code:Send an SMS Using Twilio with Ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install require 'rubygems' require 'twilio-ruby' # Find your Account SID and Auth Token at twilio.com/console # and set the environment variables. See http://twil.io/secure account_sid = ENV['TWILIO_ACCOUNT_SID'] auth_token = ENV['TWILIO_AUTH_TOKEN'] @client = Twilio::REST::Client.new(account_sid, auth_token) message = @client .api .v2010 .messages .create( body: 'Join Earth\'s mightiest heroes. Like Kevin Bacon.', from: '+15017122661', to: '+15558675310' ) puts message.body
-
In the
send_sms.rbfile, replace the values foraccount_sidandauth_tokenwith your Account SID and Auth Token surrounded by single quotation marks.[!CAUTION]
This quickstart hardcodes your credentials for faster setup. To keep credentials secret and control access when you deploy to production, use environment variables and API keys.
-
Replace the value for
fromwith the phone number that Twilio gave you in E.164 format. -
Replace the value for
towith the Twilio Virtual Phone number (+18777804236). -
Save your changes and run this command from your terminal in the directory that contains
send_sms.rb:ruby send_sms.rb
After a few moments, you receive an SMS from your Twilio number on the Twilio Virtual Phone.
Follow these steps to reply to an SMS message sent to your Twilio phone number.
-
Create and open a new file called
reply_sms.pyanywhere on your machine and paste in the following code:from flask import Flask, request, Response from twilio.twiml.messaging_response import MessagingResponse app = Flask(__name__) @app.route("/reply_sms", methods=['POST']) def reply_sms(): # Create a new Twilio MessagingResponse resp = MessagingResponse() resp.message("The Robots are coming! Head for the hills!") # Return the TwiML (as XML) response return Response(str(resp), mimetype='text/xml') if __name__ == "__main__": app.run(port=3000)
Save the file.
-
In a new terminal window, run the following command to start the Python development server on port 3000:
python reply_sms.py
-
In a new terminal window, run the following command to start ngrok and create a tunnel to your localhost:
ngrok http 3000
[!WARNING]
Use ngrok only for testing because it creates a temporary URL that exposes your local development machine to the internet. Host your application with a cloud provider or your public server when you deploy to production.
-
Set up a webhook that triggers when your Twilio phone number receives an SMS message:
-
Click your Twilio phone number.
-
In the Messaging Configuration section, in the URL field for A message comes in, enter the temporary forwarding URL from your ngrok console with
/reply_smsappended to the end.For example, if your ngrok console shows
Forwarding https://1aaa-123-45-678-910.ngrok-free.app, enterhttps://1aaa-123-45-678-910.ngrok-free.app/reply_sms. -
Click Save configuration.
-
With the Python development server and ngrok running, send an SMS to your Twilio phone number:
- Enter a message in the Click here to reply field at the bottom of the Twilio Virtual Phone.
- Click the send icon.
An HTTP request shows in your ngrok console, and you get the response back as an SMS on the Twilio Virtual Phone.
-
Create and open a new file called
server.jsanywhere on your machine and paste in the following code:Respond to an Incoming Text Message with Node.js
const express = require('express'); const { MessagingResponse } = require('twilio').twiml; const app = express(); app.post('/sms', (req, res) => { const twiml = new MessagingResponse(); twiml.message('The Robots are coming! Head for the hills!'); res.type('text/xml').send(twiml.toString()); }); app.listen(3000, () => { console.log('Express server listening on port 3000'); });
-
In a new terminal window, start the Node.js development server on port 3000 by running this command in the directory that contains
server.js:node server.js
-
In a new terminal window, run the following command to start ngrok and create a tunnel to your localhost:
ngrok http 3000
[!WARNING]
Use ngrok only for testing because it creates a temporary URL that exposes your local development machine to the internet. Host your application with a cloud provider or your public server when you deploy to production.
-
Set up a webhook that triggers when your Twilio phone number receives an SMS message:
-
Click the phone number that Twilio gave you.
-
In the Messaging Configuration section, in the URL field for A message comes in, enter the temporary forwarding URL from your ngrok console with
/smsappended to the end.For example, if your ngrok console shows
Forwarding https://1aaa-123-45-678-910.ngrok-free.app, enterhttps://1aaa-123-45-678-910.ngrok-free.app/sms.
-
Click Save configuration.
-
With the Node.js development server and ngrok running, send an SMS to your Twilio phone number:
- Enter a message in the Click here to reply field at the bottom of the Twilio Virtual Phone.
- Click the send icon.
An HTTP request shows in your ngrok console, and you get the response back as an SMS on the Twilio Virtual Phone.
-
Create and open a new file called
reply_sms.phpin the same directory assend_sms.phpand paste in the following code:<?php require_once "vendor/autoload.php"; use Twilio\TwiML\MessagingResponse; // Set the content-type to XML to send back TwiML from the PHP SDK header("content-type: text/xml"); $response = new MessagingResponse(); $response->message( "The Robots are coming! Head for the hills!" ); echo $response;
Save the file.
-
In a new terminal window, start the PHP development server on port 3000 by running this command:
php -S localhost:3000
-
In a new terminal window, run the following command to start ngrok and create a tunnel to your localhost:
ngrok http 3000
[!WARNING]
Use ngrok only for testing because it creates a temporary URL that exposes your local development machine to the internet. Host your application with a cloud provider or your public server when you deploy to production.
-
Set up a webhook that triggers when your Twilio phone number receives an SMS message:
-
Click your Twilio phone number.
-
In the Messaging Configuration section, in the URL field for A message comes in, enter the temporary forwarding URL from your ngrok console with
/reply_sms.phpappended to the end.For example, if your ngrok console shows
Forwarding https://1aaa-123-45-678-910.ngrok-free.app, enterhttps://1aaa-123-45-678-910.ngrok-free.app/reply_sms.php. -
Click Save configuration.
-
With the PHP development server and ngrok running, send an SMS to your Twilio phone number:
- Enter a message in the Click here to reply field at the bottom of the Twilio Virtual Phone.
- Click the send icon.
An HTTP request shows in your ngrok console, and you get the response back as an SMS on the Twilio Virtual Phone.
-
Create a new ASP.NET MVC Project in Visual Studio:
- Open Visual Studio and click Create a new project.
- Click ASP.NET Web Application (.NET Framework).
- Click MVC to select the project type.
- Use the NuGet Package Manager to install the Twilio.AspNet.Mvc package.
-
Create a new controller:
- Open the project directory.
- Right-click on the
Controllersfolder - Select
Add>Controller...>MVC 5 Controller - Empty. - Name the file
SmsController.cs.
-
Paste the following code into
SmsController.cs:// Code sample for ASP.NET MVC on .NET Framework 4.6.1+ // In Package Manager, run: // Install-Package Twilio.AspNet.Mvc -DependencyVersion HighestMinor using Twilio.AspNet.Common; using Twilio.AspNet.Mvc; using Twilio.TwiML; namespace WebApplication1.Controllers { public class SmsController : TwilioController { public TwiMLResult Index(SmsRequest incomingMessage) { var messagingResponse = new MessagingResponse(); messagingResponse.Message("The copy cat says: " + incomingMessage.Body); return TwiML(messagingResponse); } } }
Save the file.
-
In Visual Studio, run the application by clicking the play arrow. Your web browser opens on a localhost URL. Note the port number; for example, if the URL opens on
https://localhost:44360, your port number is44360. -
In a new terminal window, run the following command to start ngrok and create a tunnel to your localhost. Replace
<port>with the port number from your application.ngrok http <port>
[!WARNING]
Use ngrok only for testing because it creates a temporary URL that exposes your local development machine to the internet. Host your application with a cloud provider or your public server when you deploy to production.
-
Set up a webhook that triggers when your Twilio phone number receives an SMS message:
-
Click your Twilio phone number.
-
In the Messaging Configuration section, in the URL field for A message comes in, enter the temporary forwarding URL from your ngrok console with
/smsappended to the end.For example, if your ngrok console shows
Forwarding https://1aaa-123-45-678-910.ngrok-free.app, enterhttps://1aaa-123-45-678-910.ngrok-free.app/sms. -
Click Save configuration.
-
With the application and ngrok running, send an SMS to your Twilio phone number:
- Enter a message in the Click here to reply field at the bottom of the Twilio Virtual Phone.
- Click the send icon.
An HTTP request shows in your ngrok console, and you get the response back as an SMS on the Twilio Virtual Phone.
-
Run the following commands to create a new ASP.NET Core project and install the Twilio NuGet package:
mkdir TwilioReceive cd TwilioReceive dotnet new mvc dotnet add package Twilio.AspNet.Core -
In the
Controllersdirectory, create a file namedSmsController.csand paste in the following code:// Code sample for ASP.NET Core on .NET Core // From command prompt, run: // dotnet add package Twilio.AspNet.Core using Twilio.AspNet.Common; using Twilio.AspNet.Core; using Twilio.TwiML; namespace TwilioReceive.Controllers { public class SmsController : TwilioController { public TwiMLResult Index(SmsRequest incomingMessage) { var messagingResponse = new MessagingResponse(); messagingResponse.Message("The copy cat says: " + incomingMessage.Body); return TwiML(messagingResponse); } } }
Save the file.
-
From the root of the project directory, run following command to start the application:
dotnet run
-
Check the command output for the localhost URL. Note the port number; for example, if the URL opens on
https://localhost:5242, your port number is5242. -
In a new terminal window, run the following command to start ngrok and create a tunnel to your localhost. Replace
<port>with the port number from your command output.ngrok http <port>
[!WARNING]
Use ngrok only for testing because it creates a temporary URL that exposes your local development machine to the internet. Host your application with a cloud provider or your public server when you deploy to production.
-
Set up a webhook that triggers when your Twilio phone number receives an SMS message:
-
Click your Twilio phone number.
-
In the Messaging Configuration section, in the URL field for A message comes in, enter the temporary forwarding URL from your ngrok console with
/smsappended to the end.For example, if your ngrok console shows
Forwarding https://1aaa-123-45-678-910.ngrok-free.app, enterhttps://1aaa-123-45-678-910.ngrok-free.app/sms. -
Click Save configuration.
-
With the application and ngrok running, send an SMS to your Twilio phone number:
- Enter a message in the Click here to reply field at the bottom of the Twilio Virtual Phone.
- Click the send icon.
An HTTP request shows in your ngrok console, and you get the response back as an SMS on the Twilio Virtual Phone.
-
Create and set up the IntelliJ project.
- Open IntelliJ IDEA Community Edition.
- Create a new project with either Maven or Gradle as the build system.
- Install the following dependencies with Maven or with Gradle:
com.twilio.sdk:twiliocom.sparkjava:sparkcore-
org.slf4jTo learn more about the dependencies, see SparkJava and Simple Logging Facade 4 Java (SLF4J).
- Select the
javafolder undersrc>main. - Click File > New> Java Class to create a new Java class. Name the class
SmsApp.
-
In the new
SmsApp.javafile that IntelliJ creates, paste in the following code:Respond to an Incoming Text Message with Java
import com.twilio.twiml.MessagingResponse; import com.twilio.twiml.messaging.Body; import com.twilio.twiml.messaging.Message; import static spark.Spark.*; public class SmsApp { public static void main(String[] args) { get("/", (req, res) -> "Hello Web"); post("/sms", (req, res) -> { res.type("application/xml"); Body body = new Body .Builder("The Robots are coming! Head for the hills!") .build(); Message sms = new Message .Builder() .body(body) .build(); MessagingResponse twiml = new MessagingResponse .Builder() .message(sms) .build(); return twiml.toXml(); }); } }
-
Right-click on the SmsApp class in the project outline and choose Run 'SmsApp.main()'.
The Java spark web application server starts listening on port 4567.
-
In a new terminal window, run the following command to start ngrok and create a tunnel to your localhost:
ngrok http 4567
[!WARNING]
Use ngrok only for testing because it creates a temporary URL that exposes your local development machine to the internet. Host your application with a cloud provider or your public server when you deploy to production.
-
Set up a webhook that triggers when your Twilio phone number receives an SMS message:
-
Click the phone number that Twilio gave you.
-
In the Messaging Configuration section, in the URL field for A message comes in, enter the temporary forwarding URL from your ngrok console with
/smsappended to the end.For example, if your ngrok console shows
Forwarding https://1aaa-123-45-678-910.ngrok-free.app, enterhttps://1aaa-123-45-678-910.ngrok-free.app/sms. -
Click Save configuration.
-
With the Java development server and ngrok running, send an SMS to your Twilio phone number:
- Enter a message in the Click here to reply field at the bottom of the Twilio Virtual Phone.
- Click the send icon.
An HTTP request shows in your ngrok console, and you get the response back as an SMS on the Twilio Virtual Phone.
-
Create and open a new file called
server.goin your Go project directory and paste in the following code:Respond to an Incoming Text Message with Go
package main import ( "net/http" "github.com/gin-gonic/gin" "github.com/twilio/twilio-go/twiml" ) func main() { router := gin.Default() router.POST("/sms", func(context *gin.Context) { message := &twiml.MessagingMessage{ Body: "The Robots are coming! Head for the hills!", } twimlResult, err := twiml.Messages([]twiml.Element{message}) if err != nil { context.String(http.StatusInternalServerError, err.Error()) } else { context.Header("Content-Type", "text/xml") context.String(http.StatusOK, twimlResult) } }) router.Run(":3000") }
-
In a new terminal window, start the Go development server on port 3000 by running this command in the directory that contains
server.go:go run server.go
-
In a new terminal window, run the following command to start ngrok and create a tunnel to your localhost:
ngrok http 3000
[!WARNING]
Use ngrok only for testing because it creates a temporary URL that exposes your local development machine to the internet. Host your application with a cloud provider or your public server when you deploy to production.
-
Set up a webhook that triggers when your Twilio phone number receives an SMS message:
-
Click the phone number that Twilio gave you.
-
In the Messaging Configuration section, in the URL field for A message comes in, enter the temporary forwarding URL from your ngrok console with
/smsappended to the end.For example, if your ngrok console shows
Forwarding https://1aaa-123-45-678-910.ngrok-free.app, enterhttps://1aaa-123-45-678-910.ngrok-free.app/sms. -
Click Save configuration.
-
With the Go development server and ngrok running, send an SMS to your Twilio phone number:
- Enter a message in the Click here to reply field at the bottom of the Twilio Virtual Phone.
- Click the send icon.
An HTTP request shows in your ngrok console, and you get the response back as an SMS on the Twilio Virtual Phone.
-
To install Sinatra and the Twilio Ruby SDK, create and open a new file called
Gemfileanywhere on your machine and paste in the following code.If you prefer to use the Rails framework, see the How to Receive and Reply to an SMS in Rails with Twilio.
# Gemfile source 'https://rubygems.org' gem 'sinatra' gem 'twilio-ruby'
-
In the same directory as
Gemfile, run the following command from the terminal:bundle install
-
Create and open a new file called
reply_sms.rbin the same directory asGemfileand paste in the following code:require 'twilio-ruby' require 'sinatra' # disable HostAuthorization for development only configure :development do set :host_authorization, { permitted_hosts: [] } end post '/sms-quickstart' do twiml = Twilio::TwiML::MessagingResponse.new do |r| r.message(body: 'Ahoy! Thanks so much for your message.') end twiml.to_s end
Save the file.
-
In a new terminal window, start the Ruby development server on port 4567 by running this command:
ruby reply_sms.rb
-
In a new terminal window, run the following command to start ngrok and create a tunnel to your localhost:
ngrok http 4567
[!WARNING]
Use ngrok only for testing because it creates a temporary URL that exposes your local development machine to the internet. Host your application with a cloud provider or your public server when you deploy to production.
-
Set up a webhook that triggers when your Twilio phone number receives an SMS message:
-
Click your Twilio phone number.
-
In the Messaging Configuration section, in the URL field for A message comes in, enter the temporary forwarding URL from your ngrok console with
/sms-quickstartappended to the end.For example, if your ngrok console shows
Forwarding https://1aaa-123-45-678-910.ngrok-free.app, enterhttps://1aaa-123-45-678-910.ngrok-free.app/sms-quickstart. -
Click Save configuration.
-
With the Ruby development server and ngrok running, send an SMS to your Twilio phone number:
- Enter a message in the Click here to reply field at the bottom of the Twilio Virtual Phone.
- Click the send icon.
An HTTP request shows in your ngrok console, and you get the response back as an SMS on the Twilio Virtual Phone.
- Upgrade your account in the Twilio Console.
- Learn about toll-free verification and A2P 10DLC registration. Regulations require:
- Toll-free verification to send SMS messages from toll-free numbers to mobile phones in the US and Canada.
- A2P 10DLC registration to send SMS messages from local numbers to mobile phones in the US.
- Browse the following developer resources: