Send SMS and MMS messages
In this tutorial, you'll learn to use Twilio Programmable Messaging to programmatically send SMS and Multimedia Messaging Service (MMS) messages using your web application. This tutorial makes HTTP POST
requests to the Message resource and the Media resource in the Twilio REST API, using the Twilio helper libraries to simplify requests in your programming language.
To send messages without writing code, use Twilio Studio (our low-code application builder).
Select your programming language and complete the prerequisites:
- Install Python.
- Install the Twilio Python module. To install using pip, run:
pip install twilio
-
On the Twilio Console landing page:
- To acquire a phone number, click Get phone number.
- Copy your Account SID and Auth Token and paste them in a temporary local file for use later in this tutorial.
-
Complete any applicable verification or registration requirements.
- If you get a toll-free number, you must complete toll-free verification before you can send SMS messages to mobile phones in the US and Canada.
- To send an SMS message from a US 10DLC number to a US recipient, register the Twilio phone number for A2P 10DLC in the Twilio Console. To learn more, see What is A2P 10DLC?.
- To send an SMS message from a UK long code number to a UK recipient, you must submit a Regulatory Compliance (RC) bundle. To learn more, see Know Your Customer (KYC) in the United Kingdom.
While you wait for verification or registration, you can test with the Twilio Virtual Phone. To learn more, see the SMS developer quickstart.
- Install Node.js.
- Install the Twilio Node.js helper library:
npm install twilio
-
On the Twilio Console landing page:
- To acquire a phone number, click Get phone number.
- Copy your Account SID and Auth Token and paste them in a temporary local file for use later in this tutorial.
-
Complete any applicable verification or registration requirements.
- If you get a toll-free number, you must complete toll-free verification before you can send SMS messages to mobile phones in the US and Canada.
- To send an SMS message from a US 10DLC number to a US recipient, register the Twilio phone number for A2P 10DLC in the Twilio Console. To learn more, see What is A2P 10DLC?.
- To send an SMS message from a UK long code number to a UK recipient, you must submit a Regulatory Compliance (RC) bundle. To learn more, see Know Your Customer (KYC) in the United Kingdom.
While you wait for verification or registration, you can test with the Twilio Virtual Phone. To learn more, see the SMS developer quickstart.
- Install PHP.
- Install dependencies with Composer:
- Install Composer.
- Install the Twilio PHP helper library:
1composer require twilio/sdk2composer install
-
On the Twilio Console landing page:
- To acquire a phone number, click Get phone number.
- Copy your Account SID and Auth Token and paste them in a temporary local file for use later in this tutorial.
-
Complete any applicable verification or registration requirements.
- If you get a toll-free number, you must complete toll-free verification before you can send SMS messages to mobile phones in the US and Canada.
- To send an SMS message from a US 10DLC number to a US recipient, register the Twilio phone number for A2P 10DLC in the Twilio Console. To learn more, see What is A2P 10DLC?.
- To send an SMS message from a UK long code number to a UK recipient, you must submit a Regulatory Compliance (RC) bundle. To learn more, see Know Your Customer (KYC) in the United Kingdom.
While you wait for verification or registration, you can test with the Twilio Virtual Phone. To learn more, see the SMS developer quickstart.
-
On the Twilio Console landing page:
- To acquire a phone number, click Get phone number.
- Copy your Account SID and Auth Token and paste them in a temporary local file for use later in this tutorial.
-
Complete any applicable verification or registration requirements.
- If you get a toll-free number, you must complete toll-free verification before you can send SMS messages to mobile phones in the US and Canada.
- To send an SMS message from a US 10DLC number to a US recipient, register the Twilio phone number for A2P 10DLC in the Twilio Console. To learn more, see What is A2P 10DLC?.
- To send an SMS message from a UK long code number to a UK recipient, you must submit a Regulatory Compliance (RC) bundle. To learn more, see Know Your Customer (KYC) in the United Kingdom.
While you wait for verification or registration, you can test with the Twilio Virtual Phone. To learn more, see the SMS developer quickstart.
-
On the Twilio Console landing page:
- To acquire a phone number, click Get phone number.
- Copy your Account SID and Auth Token and paste them in a temporary local file for use later in this tutorial.
-
Complete any applicable verification or registration requirements.
- If you get a toll-free number, you must complete toll-free verification before you can send SMS messages to mobile phones in the US and Canada.
- To send an SMS message from a US 10DLC number to a US recipient, register the Twilio phone number for A2P 10DLC in the Twilio Console. To learn more, see What is A2P 10DLC?.
- To send an SMS message from a UK long code number to a UK recipient, you must submit a Regulatory Compliance (RC) bundle. To learn more, see Know Your Customer (KYC) in the United Kingdom.
While you wait for verification or registration, you can test with the Twilio Virtual Phone. To learn more, see the SMS developer quickstart.
- Install Java Standard Edition (SE) Development Kit.
- Download the Twilio Java Helper library 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
.
-
On the Twilio Console landing page:
- To acquire a phone number, click Get phone number.
- Copy your Account SID and Auth Token and paste them in a temporary local file for use later in this tutorial.
-
Complete any applicable verification or registration requirements.
- If you get a toll-free number, you must complete toll-free verification before you can send SMS messages to mobile phones in the US and Canada.
- To send an SMS message from a US 10DLC number to a US recipient, register the Twilio phone number for A2P 10DLC in the Twilio Console. To learn more, see What is A2P 10DLC?.
- To send an SMS message from a UK long code number to a UK recipient, you must submit a Regulatory Compliance (RC) bundle. To learn more, see Know Your Customer (KYC) in the United Kingdom.
While you wait for verification or registration, you can test with the Twilio Virtual Phone. To learn more, see the SMS developer quickstart.
-
On the Twilio Console landing page:
- To acquire a phone number, click Get phone number.
- Copy your Account SID and Auth Token and paste them in a temporary local file for use later in this tutorial.
-
Complete any applicable verification or registration requirements.
- If you get a toll-free number, you must complete toll-free verification before you can send SMS messages to mobile phones in the US and Canada.
- To send an SMS message from a US 10DLC number to a US recipient, register the Twilio phone number for A2P 10DLC in the Twilio Console. To learn more, see What is A2P 10DLC?.
- To send an SMS message from a UK long code number to a UK recipient, you must submit a Regulatory Compliance (RC) bundle. To learn more, see Know Your Customer (KYC) in the United Kingdom.
While you wait for verification or registration, you can test with the Twilio Virtual Phone. To learn more, see the SMS developer quickstart.
- Install Ruby.
- Install the Twilio Ruby helper library:
gem install twilio-ruby
-
On the Twilio Console landing page:
- To acquire a phone number, click Get phone number.
- Copy your Account SID and Auth Token and paste them in a temporary local file for use later in this tutorial.
-
Complete any applicable verification or registration requirements.
- If you get a toll-free number, you must complete toll-free verification before you can send SMS messages to mobile phones in the US and Canada.
- To send an SMS message from a US 10DLC number to a US recipient, register the Twilio phone number for A2P 10DLC in the Twilio Console. To learn more, see What is A2P 10DLC?.
- To send an SMS message from a UK long code number to a UK recipient, you must submit a Regulatory Compliance (RC) bundle. To learn more, see Know Your Customer (KYC) in the United Kingdom.
While you wait for verification or registration, you can test with the Twilio Virtual Phone. To learn more, see the SMS developer quickstart.
Follow these steps to send an SMS message from your Twilio phone number.
-
Create and open a new file called
send_message.py
anywhere on your machine and paste in the following code:1# Download the helper library from https://www.twilio.com/docs/python/install2import os3from twilio.rest import Client45# Find your Account SID and Auth Token at twilio.com/console6# and set the environment variables. See http://twil.io/secure7account_sid = os.environ["TWILIO_ACCOUNT_SID"]8auth_token = os.environ["TWILIO_AUTH_TOKEN"]9client = Client(account_sid, auth_token)1011message = client.messages.create(12body="Join Earth's mightiest heroes. Like Kevin Bacon.",13from_="+15017122661",14to="+15558675310",15)1617print(message.body)To learn all of the API response values that you can return with
print()
, see the response for Send an SMS Message in the API documentation. Precede the response value withmessage.
(for example:print(message.status)
returns thestatus
value). -
Set the environment variables for your Account SID and Auth Token.
(warning)Improve security with API keys
To better control access, use API keys instead of the Account SID and Auth Token when you deploy to production. To learn more, see Why you should use API keys.
On Mac or Linux:
-
Run the following commands to add your credentials as environment variables in a
twilio.env
file and source them. ReplaceACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
with your Account SID and replaceyour_auth_token
with your Auth Token.1echo "export TWILIO_ACCOUNT_SID='ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'" > twilio.env2echo "export TWILIO_AUTH_TOKEN='your_auth_token'" >> twilio.env3source ./twilio.env -
If you're committing code with git, run the following command to add the
twilio.env
file to.gitignore
to avoid uploading your credentials in plain text:echo "twilio.env" >> .gitignore
On Windows command line (cmd.exe), run the following commands. Replace
ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
with your Account SID and replaceyour_auth_token
with your Auth Token.1set TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX2set TWILIO_AUTH_TOKEN=your_auth_tokenTo learn more, see Store your Twilio credentials safely.
-
-
In the
send_message.py
file, replace the value forto
with the recipient phone number in E.164 format.To send a message to multiple recipients:
-
Add a statement below
client
to define the array of phone numbers. Replace the phone numbers with your recipients' phone numbers in E.164 format.numbers = ["+15558675310", "+12345678901", "+10987654321"] -
Replace the
message =
andprint()
statements with the following code that iterates through each phone number in thenumbers
list and returns the message sent to each number. Twilio makes one API call for each number.1for number in numbers:2message = client.messages.create(3body="This is the ship that made the Kessel Run in fourteen parsecs?",4from_="+15017122661",5to=number,6)7print(f"Sent to {number}: {message.body}")
(information)Limits on message cadence
Message delivery performance to wireless carrier networks has limits. To learn more, see Understanding Twilio Rate Limits and Message Queues.
-
-
Replace the value for
from
with your Twilio phone number in E.164 format. -
Save your changes and run this command from your terminal in the directory that contains
send_message.py
:python send_message.pyAfter a few moments, you receive an SMS from your Twilio number.
-
Create and open a new file called
send_message.js
anywhere on your machine and paste in the following code:1// Download the helper library from https://www.twilio.com/docs/node/install2const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";34// Find your Account SID and Auth Token at twilio.com/console5// and set the environment variables. See http://twil.io/secure6const accountSid = process.env.TWILIO_ACCOUNT_SID;7const authToken = process.env.TWILIO_AUTH_TOKEN;8const client = twilio(accountSid, authToken);910async function createMessage() {11const message = await client.messages.create({12body: "This is the ship that made the Kessel Run in fourteen parsecs?",13from: "+15017122661",14to: "+15558675310",15});1617console.log(message.body);18}1920createMessage();To learn all of the API response values that you can return with
console.log()
, see the response for Send an SMS Message in the API documentation. Precede the response value withmessage.
(for example:console.log(message.status)
returns thestatus
value). -
Set the environment variables for your Account SID and Auth Token.
(warning)Improve security with API keys
To better control access, use API keys instead of the Account SID and Auth Token when you deploy to production. To learn more, see Why you should use API keys.
On Mac or Linux:
-
Run the following commands to add your credentials as environment variables in a
twilio.env
file and source them. ReplaceACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
with your Account SID and replaceyour_auth_token
with your Auth Token.1echo "export TWILIO_ACCOUNT_SID='ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'" > twilio.env2echo "export TWILIO_AUTH_TOKEN='your_auth_token'" >> twilio.env3source ./twilio.env -
If you're committing code with git, run the following command to add the
twilio.env
file to.gitignore
to avoid uploading your credentials in plain text:echo "twilio.env" >> .gitignore
On Windows command line (cmd.exe), run the following commands. Replace
ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
with your Account SID and replaceyour_auth_token
with your Auth Token.1set TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX2set TWILIO_AUTH_TOKEN=your_auth_tokenTo learn more, see Store your Twilio credentials safely.
-
-
In the
send_message.js
file, replace the value forto
with the recipient phone number in E.164 format.To send a message to multiple recipients:
-
Add a
const
statement after the existingconst
statements to define the array of phone numbers. Replace the phone numbers with your recipients' phone numbers in E.164 format.const numbers = ["+15558675310", "+12345678901", "+10987654321"]; -
Replace the
async function createMessage()
block with the following code that iterates through each phone number in thenumbers
list and returns the message sent to each number. Twilio makes one API call for each number.1async function createMessage() {2for (const number of numbers) {3const message = await client.messages.create({4body: "This is the ship that made the Kessel Run in fourteen parsecs?",5from: "+15017122661",6to: number,7});89console.log(`Sent to ${number}: ${message.body}`);10}11}
(information)Limits on message cadence
Message delivery performance to wireless carrier networks has limits. To learn more, see Understanding Twilio Rate Limits and Message Queues.
-
-
Replace the value for
from
with your Twilio phone number in E.164 format. -
Save your changes and run this command from your terminal in the directory that contains
send_message.js
:node send_message.jsAfter a few moments, you receive an SMS from your Twilio number.
-
Create and open a new file called
send_message.php
in the project directory and paste in the following code:1<?php23// Update the path below to your autoload.php,4// see https://getcomposer.org/doc/01-basic-usage.md5require_once "/path/to/vendor/autoload.php";67use Twilio\Rest\Client;89// Find your Account SID and Auth Token at twilio.com/console10// and set the environment variables. See http://twil.io/secure11$sid = getenv("TWILIO_ACCOUNT_SID");12$token = getenv("TWILIO_AUTH_TOKEN");13$twilio = new Client($sid, $token);1415$message = $twilio->messages->create(16"+15558675310", // To17[18"body" =>19"This is the ship that made the Kessel Run in fourteen parsecs?",20"from" => "+15017122661",21]22);2324print $message->body;To learn all of the API response values that you can return with
print
, see the response for Send an SMS Message in the API documentation. Precede the response value with$message->
(for example:print $message->status;
returns thestatus
value). -
Set the environment variables for your Account SID and Auth Token.
(warning)Improve security with API keys
To better control access, use API keys instead of the Account SID and Auth Token when you deploy to production. To learn more, see Why you should use API keys.
On Mac or Linux:
-
Run the following commands to add your credentials as environment variables in a
twilio.env
file and source them. ReplaceACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
with your Account SID and replaceyour_auth_token
with your Auth Token.1echo "export TWILIO_ACCOUNT_SID='ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'" > twilio.env2echo "export TWILIO_AUTH_TOKEN='your_auth_token'" >> twilio.env3source ./twilio.env -
If you're committing code with git, run the following command to add the
twilio.env
file to.gitignore
to avoid uploading your credentials in plain text:echo "twilio.env" >> .gitignore
On Windows command line (cmd.exe), run the following commands. Replace
ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
with your Account SID and replaceyour_auth_token
with your Auth Token.1set TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX2set TWILIO_AUTH_TOKEN=your_auth_tokenTo learn more, see Store your Twilio credentials safely.
-
-
In the
send_message.php
file, replace the value forto
with the recipient phone number in E.164 format.To send a message to multiple recipients:
-
Add a statement after the
$twilio
to define the array of phone numbers. Replace the phone numbers with your recipients' phone numbers in E.164 format.$numbers = ["+15558675310", "+12345678901", "+10987654321"]; -
Replace the
$message =
andprint
statements with the following code that iterates through each phone number in thenumbers
list and returns the message sent to each number. Twilio makes one API call for each number.1foreach ($numbers as $to) {2$message = $twilio->messages->create(3$to, // To4[5"body" =>6"This is the ship that made the Kessel Run in fourteen parsecs?",7"from" => "+15017122661",8]9);1011print "Sent to $to: " . $message->body . "\n";12}
(information)Limits on message cadence
Message delivery performance to wireless carrier networks has limits. To learn more, see Understanding Twilio Rate Limits and Message Queues.
-
-
Replace the value for
from
with your Twilio phone number in E.164 format. -
Update line 5 of
send_message.php
torequire __DIR__ . '/vendor/autoload.php';
-
Save your changes and run this command from your terminal in the directory that contains
send_message.php
:php send_message.phpAfter a few moments, you receive an SMS from your Twilio number.
-
Set the environment variables for your Account SID and Auth Token and start Visual Studio with the inherited variables.
(warning)Improve security with API keys
To better control access, use API keys instead of the Account SID and Auth Token when you deploy to production. To learn more, see Why you should use API keys.
On Windows command line (cmd.exe), run the following commands. Replace
ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
with your Account SID and replaceyour_auth_token
with your Auth Token.1set TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX2set TWILIO_AUTH_TOKEN=your_auth_token3start devenvTo learn more, see Store your Twilio credentials safely.
-
Create and set up a new project in Visual Studio:
- In Visual Studio, click Create a new project.
- Click Console App (.NET Framework).
- Use the NuGet Package Manager to install the Twilio REST API helper library.
-
Open the file in your new Visual Studio project called
Program.cs
and paste in the following code, replacing the existing template code:1// Install the C# / .NET helper library from twilio.com/docs/csharp/install23using System;4using Twilio;5using Twilio.Rest.Api.V2010.Account;6using System.Threading.Tasks;78class Program {9public static async Task Main(string[] args) {10// Find your Account SID and Auth Token at twilio.com/console11// and set the environment variables. See http://twil.io/secure12string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");13string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");1415TwilioClient.Init(accountSid, authToken);1617var message = await MessageResource.CreateAsync(18body: "Join Earth's mightiest heroes. Like Kevin Bacon.",19from: new Twilio.Types.PhoneNumber("+15017122661"),20to: new Twilio.Types.PhoneNumber("+15558675310"));2122Console.WriteLine(message.Body);23}24}To learn all of the API response values that you can return with
Console.WriteLine()
, see the response for Send an SMS Message in the API documentation. Precede the response value withmessage.
and capitalize the first letter of the response value (for example:Console.WriteLine(message.Status)
returns thestatus
value). -
In the
Program.cs
file, replace the value forto: new Twilio.Types.PhoneNumber
with the recipient phone number in E.164 format.To send a message to multiple recipients, replace the
class Program
statement with the following code that iterates through each phone number in thenumbers
list and returns the message sent to each number. Replace the phone numbers with your recipients' phone numbers in E.164 format. Twilio makes one API call for each number.1class Program {2public static async Task Main(string[] args) {3// Find your Account SID and Auth Token at twilio.com/console4// and set the environment variables. See http://twil.io/secure5string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");6string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");78TwilioClient.Init(accountSid, authToken);910string[] numbers = { "+15558675310", "+12345678901", "+10987654321" };1112foreach (var number in numbers) {13var message = await MessageResource.CreateAsync(14body: "Join Earth's mightiest heroes. Like Kevin Bacon.",15from: new Twilio.Types.PhoneNumber("+15017122661"),16to: new Twilio.Types.PhoneNumber(number));1718Console.WriteLine(message.Body);19}20}21}(information)Limits on message cadence
Message delivery performance to wireless carrier networks has limits. To learn more, see Understanding Twilio Rate Limits and Message Queues.
-
Replace the value for
from: new Twilio.Types.PhoneNumber
with your Twilio phone number in E.164 format. -
Save your changes and run your project in Visual Studio.
After a few moments, you receive an SMS from your Twilio number.
-
Run the following commands to create a new .NET project and install the Twilio NuGet package:
1mkdir TwilioSend2cd TwilioSend3dotnet new console4dotnet add package Twilio -
Open the file in your new project called
Program.cs
and paste in the following code, replacing the existing template code:1// Install the C# / .NET helper library from twilio.com/docs/csharp/install23using System;4using Twilio;5using Twilio.Rest.Api.V2010.Account;6using System.Threading.Tasks;78class Program {9public static async Task Main(string[] args) {10// Find your Account SID and Auth Token at twilio.com/console11// and set the environment variables. See http://twil.io/secure12string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");13string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");1415TwilioClient.Init(accountSid, authToken);1617var message = await MessageResource.CreateAsync(18body: "Join Earth's mightiest heroes. Like Kevin Bacon.",19from: new Twilio.Types.PhoneNumber("+15017122661"),20to: new Twilio.Types.PhoneNumber("+15558675310"));2122Console.WriteLine(message.Body);23}24}To learn all of the API response values that you can return with
Console.WriteLine()
, see the response for Send an SMS Message in the API documentation. Precede the response value withmessage.
and capitalize the first letter of the response value (for example:Console.WriteLine(message.Status)
returns thestatus
value). -
Set the environment variables for your Account SID and Auth Token.
(warning)Improve security with API keys
To better control access, use API keys instead of the Account SID and Auth Token when you deploy to production. To learn more, see Why you should use API keys.
On Mac or Linux:
-
Run the following commands to add your credentials as environment variables in a
twilio.env
file and source them. ReplaceACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
with your Account SID and replaceyour_auth_token
with your Auth Token.1echo "export TWILIO_ACCOUNT_SID='ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'" > twilio.env2echo "export TWILIO_AUTH_TOKEN='your_auth_token'" >> twilio.env3source ./twilio.env -
If you're committing code with git, run the following command to add the
twilio.env
file to.gitignore
to avoid uploading your credentials in plain text:echo "twilio.env" >> .gitignore
On Windows command line (cmd.exe), run the following commands. Replace
ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
with your Account SID and replaceyour_auth_token
with your Auth Token.1set TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX2set TWILIO_AUTH_TOKEN=your_auth_tokenTo learn more, see Store your Twilio credentials safely.
-
-
In the
Program.cs
file, replace the value forto: new Twilio.Types.PhoneNumber
with the recipient phone number in E.164 format.To send a message to multiple recipients, replace the
class Program
statement with the following code that iterates through each phone number in thenumbers
list and returns the message sent to each number. Replace the phone numbers with your recipients' phone numbers in E.164 format. Twilio makes one API call for each number.1class Program {2public static async Task Main(string[] args) {3// Find your Account SID and Auth Token at twilio.com/console4// and set the environment variables. See http://twil.io/secure5string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");6string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");78TwilioClient.Init(accountSid, authToken);910string[] numbers = { "+15558675310", "+12345678901", "+10987654321" };1112foreach (var number in numbers) {13var message = await MessageResource.CreateAsync(14body: "Join Earth's mightiest heroes. Like Kevin Bacon.",15from: new Twilio.Types.PhoneNumber("+15017122661"),16to: new Twilio.Types.PhoneNumber(number));1718Console.WriteLine(message.Body);19}20}21}(information)Limits on message cadence
Message delivery performance to wireless carrier networks has limits. To learn more, see Understanding Twilio Rate Limits and Message Queues.
-
Replace the value for
from: new Twilio.Types.PhoneNumber
with your Twilio phone number in E.164 format. -
Save your changes and run this command in the directory that contains
Program.cs
:dotnet runAfter a few moments, you receive an SMS from your Twilio number.
-
Create and open a new file called
Example.java
in the same directory as the fat jar file and paste in the following code:1// Install the Java helper library from twilio.com/docs/java/install23import com.twilio.type.PhoneNumber;4import com.twilio.Twilio;5import com.twilio.rest.api.v2010.account.Message;67public class Example {8// Find your Account SID and Auth Token at twilio.com/console9// and set the environment variables. See http://twil.io/secure10public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");11public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");1213public static void main(String[] args) {14Twilio.init(ACCOUNT_SID, AUTH_TOKEN);15Message message = Message16.creator(new com.twilio.type.PhoneNumber("+15558675310"),17new com.twilio.type.PhoneNumber("+15017122661"),18"This is the ship that made the Kessel Run in fourteen parsecs?")19.create();2021System.out.println(message.getBody());22}23}To learn all of the API response values that you can return with
System.out.println();
, see the response for Send an SMS Message in the API documentation. Precede the response value withmessage.get
, capitalize the response value, and add parentheses after the response value (for example:System.out.println(message.getStatus());
returns thestatus
value). -
Set the environment variables for your Account SID and Auth Token.
(warning)Improve security with API keys
To better control access, use API keys instead of the Account SID and Auth Token when you deploy to production. To learn more, see Why you should use API keys.
On Mac or Linux:
-
Run the following commands to add your credentials as environment variables in a
twilio.env
file and source them. ReplaceACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
with your Account SID and replaceyour_auth_token
with your Auth Token.1echo "export TWILIO_ACCOUNT_SID='ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'" > twilio.env2echo "export TWILIO_AUTH_TOKEN='your_auth_token'" >> twilio.env3source ./twilio.env -
If you're committing code with git, run the following command to add the
twilio.env
file to.gitignore
to avoid uploading your credentials in plain text:echo "twilio.env" >> .gitignore
On Windows command line (cmd.exe), run the following commands. Replace
ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
with your Account SID and replaceyour_auth_token
with your Auth Token.1set TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX2set TWILIO_AUTH_TOKEN=your_auth_tokenTo learn more, see Store your Twilio credentials safely.
-
-
In the
Example.java
file, replace the value for the first phone number with the recipient phone number in E.164 format.To send a message to multiple recipients:
-
Replace the contents of the
public static void main(String[] args)
block with the following code that iterates through each phone number in anumbers
list and returns the message sent to each number. Twilio makes one API call for each number.1Twilio.init(ACCOUNT_SID, AUTH_TOKEN);23String[] numbers = {"+15558675310", "+12345678901", "+10987654321"};45for (String to : numbers) {6Message message = Message7.creator(new PhoneNumber(to),8new PhoneNumber("+15017122661"),9"This is the ship that made the Kessel Run in fourteen parsecs?")10.create();1112System.out.println(message.getBody());13} -
Replace the phone numbers in the
numbers
list with your recipients' phone numbers in E.164 format.
(information)Limits on message cadence
Message delivery performance to wireless carrier networks has limits. To learn more, see Understanding Twilio Rate Limits and Message Queues.
-
-
Replace the value for the second
new PhoneNumber()
with your Twilio phone number in E.164 format. -
Save your changes and compile the Java from your terminal in the directory that contains
Example.java
. Replace10.9.0
with 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.0
with the version of your fat jar file. On Linux or macOS, run:java -cp .:twilio-10.9.0-jar-with-dependencies.jar ExampleOn Windows, run:
java -cp ".;twilio-10.9.0-jar-with-dependencies.jar" ExampleAfter a few moments, you receive an SMS from your Twilio number.
-
Create and set up your Go project.
-
Create a new Go project by running the following command:
go mod init twilio-example -
Install the Twilio Go helper library:
go get github.com/twilio/twilio-go
-
-
Create and open a new file called
send_message.go
in your Go project directory and paste in the following code:1// Download the helper library from https://www.twilio.com/docs/go/install2package main34import (5"fmt"6"github.com/twilio/twilio-go"7api "github.com/twilio/twilio-go/rest/api/v2010"8"os"9)1011func main() {12// Find your Account SID and Auth Token at twilio.com/console13// and set the environment variables. See http://twil.io/secure14// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment15client := twilio.NewRestClient()1617params := &api.CreateMessageParams{}18params.SetBody("Join Earth's mightiest heroes. Like Kevin Bacon.")19params.SetFrom("+15017122661")20params.SetTo("+15558675310")2122resp, err := client.Api.CreateMessage(params)23if err != nil {24fmt.Println(err.Error())25os.Exit(1)26} else {27if resp.Body != nil {28fmt.Println(*resp.Body)29} else {30fmt.Println(resp.Body)31}32}33}To learn all of the API response values that you can return with
fmt.Println()
, see the response for Send an SMS Message in the API documentation. Precede the response value with*resp.
and capitalize the first letter of the response value (for example:fmt.Println(*resp.Status)
returns thestatus
value). -
Set the environment variables for your Account SID and Auth Token.
(warning)Improve security with API keys
To better control access, use API keys instead of the Account SID and Auth Token when you deploy to production. To learn more, see Why you should use API keys.
On Mac or Linux:
-
Run the following commands to add your credentials as environment variables in a
twilio.env
file and source them. ReplaceACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
with your Account SID and replaceyour_auth_token
with your Auth Token.1echo "export TWILIO_ACCOUNT_SID='ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'" > twilio.env2echo "export TWILIO_AUTH_TOKEN='your_auth_token'" >> twilio.env3source ./twilio.env -
If you're committing code with git, run the following command to add the
twilio.env
file to.gitignore
to avoid uploading your credentials in plain text:echo "twilio.env" >> .gitignore
On Windows command line (cmd.exe), run the following commands. Replace
ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
with your Account SID and replaceyour_auth_token
with your Auth Token.1set TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX2set TWILIO_AUTH_TOKEN=your_auth_tokenTo learn more, see Store your Twilio credentials safely.
-
-
In the
send_message.go
file, replace the value forto
with the recipient phone number in E.164 format.To send a message to multiple recipients:
-
Add a statement below
client
to define the array of phone numbers. Replace the phone numbers with your recipients' phone numbers in E.164 format.numbers := []string{"+15558675310", "+12345678901", "+10987654321"} -
Replace the
params
statements with the following code that iterates through each phone number in thenumbers
list. Twilio makes one API call for each number.1for _, number := range numbers {2params := &api.CreateMessageParams{}3params.SetBody("Join Earth's mightiest heroes. Like Kevin Bacon.")4params.SetFrom("+15017122661")5params.SetTo(number) -
Add an additional closing bracket
}
to the end of the file.
(information)Limits on message cadence
Message delivery performance to wireless carrier networks has limits. To learn more, see Understanding Twilio Rate Limits and Message Queues.
-
-
Replace the value for
params.SetFrom
with your Twilio phone number in E.164 format. -
Save your changes and run this command in the directory that contains
send_message.go
:go run send_message.goAfter a few moments, you receive an SMS from your Twilio number.
-
Create and open a new file called
send_message.rb
anywhere on your machine and paste in the following code:1# Download the helper library from https://www.twilio.com/docs/ruby/install2require 'rubygems'3require 'twilio-ruby'45# Find your Account SID and Auth Token at twilio.com/console6# and set the environment variables. See http://twil.io/secure7account_sid = ENV['TWILIO_ACCOUNT_SID']8auth_token = ENV['TWILIO_AUTH_TOKEN']9@client = Twilio::REST::Client.new(account_sid, auth_token)1011message = @client12.api13.v201014.messages15.create(16body: 'Join Earth\'s mightiest heroes. Like Kevin Bacon.',17from: '+15017122661',18to: '+15558675310'19)2021puts message.bodyTo learn all of the API response values that you can return with
puts
, see the response for Send an SMS Message in the API documentation. Precede the response value withmessage.
(for example:puts message.status
returns thestatus
value). -
Set the environment variables for your Account SID and Auth Token.
(warning)Improve security with API keys
To better control access, use API keys instead of the Account SID and Auth Token when you deploy to production. To learn more, see Why you should use API keys.
On Mac or Linux:
-
Run the following commands to add your credentials as environment variables in a
twilio.env
file and source them. ReplaceACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
with your Account SID and replaceyour_auth_token
with your Auth Token.1echo "export TWILIO_ACCOUNT_SID='ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'" > twilio.env2echo "export TWILIO_AUTH_TOKEN='your_auth_token'" >> twilio.env3source ./twilio.env -
If you're committing code with git, run the following command to add the
twilio.env
file to.gitignore
to avoid uploading your credentials in plain text:echo "twilio.env" >> .gitignore
On Windows command line (cmd.exe), run the following commands. Replace
ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
with your Account SID and replaceyour_auth_token
with your Auth Token.1set TWILIO_ACCOUNT_SID=ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX2set TWILIO_AUTH_TOKEN=your_auth_tokenTo learn more, see Store your Twilio credentials safely.
-
-
In the
send_message.rb
file, replace the value forto
with the recipient phone number in E.164 format.To send a message to multiple recipients:
-
Add a statement below
@client
to define the array of phone numbers. Replace the phone numbers with your recipients' phone numbers in E.164 format.numbers = ['+15558675310', '+12345678901', '+10987654321'] -
Replace the
message =
andputs
statements with the following code that iterates through each phone number in thenumbers
list. Twilio makes one API call for each number.1numbers.each do |number|2message = @client3.api4.v20105.messages6.create(7body: 'Join Earth\'s mightiest heroes. Like Kevin Bacon.',8from: '+15017122661',9to: number10)11puts message.body12end
(information)Limits on message cadence
Message delivery performance to wireless carrier networks has limits. To learn more, see Understanding Twilio Rate Limits and Message Queues.
-
-
Replace the value for
from
with your Twilio phone number in E.164 format. -
Save your changes and run this command from your terminal in the directory that contains
send_message.rb
:ruby send_message.rbAfter a few moments, you receive an SMS from your Twilio number.
Info
To learn which countries support MMS messages, see Sending and receiving MMS messages.
To send an MMS message, follow the steps to send an SMS message, adding the media URL to the code as shown in the following example. The media URL tells Twilio where to get the media you want to include.
The media URL must be a publicly accessible URL. Twilio can't reach any hidden URLs or URLs that require authentication.
When the Twilio REST API creates your new Message resource, it saves the image found at the specified in the media URL as a Media resource. Once you create a resource, you can access it at any time by using the API.
Set the media_url
parameter:
1# Download the helper library from https://www.twilio.com/docs/python/install2import os3from twilio.rest import Client45# Find your Account SID and Auth Token at twilio.com/console6# and set the environment variables. See http://twil.io/secure7account_sid = os.environ["TWILIO_ACCOUNT_SID"]8auth_token = os.environ["TWILIO_AUTH_TOKEN"]9client = Client(account_sid, auth_token)1011message = client.messages.create(12body="This is the ship that made the Kessel Run in fourteen parsecs?",13from_="+15017122661",14media_url=[15"https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg"16],17to="+15558675310",18)1920print(message.body)
Set the mediaUrl
parameter:
1// Download the helper library from https://www.twilio.com/docs/node/install2const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";34// Find your Account SID and Auth Token at twilio.com/console5// and set the environment variables. See http://twil.io/secure6const accountSid = process.env.TWILIO_ACCOUNT_SID;7const authToken = process.env.TWILIO_AUTH_TOKEN;8const client = twilio(accountSid, authToken);910async function createMessage() {11const message = await client.messages.create({12body: "This is the ship that made the Kessel Run in fourteen parsecs?",13from: "+15017122661",14mediaUrl: [15"https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg",16],17to: "+15558675310",18});1920console.log(message.body);21}2223createMessage();
Set the mediaUrl
parameter:
1<?php23// Update the path below to your autoload.php,4// see https://getcomposer.org/doc/01-basic-usage.md5require_once "/path/to/vendor/autoload.php";67use Twilio\Rest\Client;89// Find your Account SID and Auth Token at twilio.com/console10// and set the environment variables. See http://twil.io/secure11$sid = getenv("TWILIO_ACCOUNT_SID");12$token = getenv("TWILIO_AUTH_TOKEN");13$twilio = new Client($sid, $token);1415$message = $twilio->messages->create(16"+15558675310", // To17[18"body" =>19"This is the ship that made the Kessel Run in fourteen parsecs?",20"from" => "+15017122661",21"mediaUrl" => [22"https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg",23],24]25);2627print $message->body;
Set the mediaUrl
parameter:
1// Install the C# / .NET helper library from twilio.com/docs/csharp/install23using System;4using Twilio;5using Twilio.Rest.Api.V2010.Account;6using System.Threading.Tasks;7using System.Collections.Generic;89class Program {10public static async Task Main(string[] args) {11// Find your Account SID and Auth Token at twilio.com/console12// and set the environment variables. See http://twil.io/secure13string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");14string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");1516TwilioClient.Init(accountSid, authToken);1718var message = await MessageResource.CreateAsync(19body: "This is the ship that made the Kessel Run in fourteen parsecs?",20from: new Twilio.Types.PhoneNumber("+15017122661"),21mediaUrl: new List<Uri> { new Uri(22"https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg") },23to: new Twilio.Types.PhoneNumber("+15558675310"));2425Console.WriteLine(message.Body);26}27}
Set the mediaUrl
parameter:
1// Install the C# / .NET helper library from twilio.com/docs/csharp/install23using System;4using Twilio;5using Twilio.Rest.Api.V2010.Account;6using System.Threading.Tasks;7using System.Collections.Generic;89class Program {10public static async Task Main(string[] args) {11// Find your Account SID and Auth Token at twilio.com/console12// and set the environment variables. See http://twil.io/secure13string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");14string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");1516TwilioClient.Init(accountSid, authToken);1718var message = await MessageResource.CreateAsync(19body: "This is the ship that made the Kessel Run in fourteen parsecs?",20from: new Twilio.Types.PhoneNumber("+15017122661"),21mediaUrl: new List<Uri> { new Uri(22"https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg") },23to: new Twilio.Types.PhoneNumber("+15558675310"));2425Console.WriteLine(message.Body);26}27}
Add the required import statements for java.net.URI
and java.util.Arrays
and add the .setMediaUrl()
statement:
1// Install the Java helper library from twilio.com/docs/java/install23import com.twilio.type.PhoneNumber;4import java.net.URI;5import java.util.Arrays;6import com.twilio.Twilio;7import com.twilio.rest.api.v2010.account.Message;89public class Example {10// Find your Account SID and Auth Token at twilio.com/console11// and set the environment variables. See http://twil.io/secure12public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");13public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");1415public static void main(String[] args) {16Twilio.init(ACCOUNT_SID, AUTH_TOKEN);17Message message = Message18.creator(new com.twilio.type.PhoneNumber("+15558675310"),19new com.twilio.type.PhoneNumber("+15017122661"),20"This is the ship that made the Kessel Run in fourteen parsecs?")21.setMediaUrl(Arrays.asList(22URI.create("https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg")))23.create();2425System.out.println(message.getBody());26}27}
Add the params.SetMediaUrl()
statement:
1// Download the helper library from https://www.twilio.com/docs/go/install2package main34import (5"fmt"6"github.com/twilio/twilio-go"7api "github.com/twilio/twilio-go/rest/api/v2010"8"os"9)1011func main() {12// Find your Account SID and Auth Token at twilio.com/console13// and set the environment variables. See http://twil.io/secure14// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment15client := twilio.NewRestClient()1617params := &api.CreateMessageParams{}18params.SetBody("This is the ship that made the Kessel Run in fourteen parsecs?")19params.SetFrom("+15017122661")20params.SetMediaUrl([]string{21"https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg",22})23params.SetTo("+15558675310")2425resp, err := client.Api.CreateMessage(params)26if err != nil {27fmt.Println(err.Error())28os.Exit(1)29} else {30if resp.Body != nil {31fmt.Println(*resp.Body)32} else {33fmt.Println(resp.Body)34}35}36}
Set the media_url
parameter:
1# Download the helper library from https://www.twilio.com/docs/ruby/install2require 'rubygems'3require 'twilio-ruby'45# Find your Account SID and Auth Token at twilio.com/console6# and set the environment variables. See http://twil.io/secure7account_sid = ENV['TWILIO_ACCOUNT_SID']8auth_token = ENV['TWILIO_AUTH_TOKEN']9@client = Twilio::REST::Client.new(account_sid, auth_token)1011message = @client12.api13.v201014.messages15.create(16body: 'This is the ship that made the Kessel Run in fourteen parsecs?',17from: '+15017122661',18media_url: [19'https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg'20],21to: '+15558675310'22)2324puts message.body
- View more Messaging tutorials
- Sending high-volume messages? Learn more about messaging services
- Browse the following developer resources: