Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Programmable Messaging Quickstart for C# with .NET Framework


(information)

Info

Ahoy there! All messaging transmitted using Twilio's messaging channels is treated as Application-to-Person (A2P) messaging and subject to Twilio's Messaging Policy(link takes you to an external page). For detailed information on policy rules to ensure you remain compliant while using Twilio's services, please see our Acceptable Use Policy(link takes you to an external page).

(warning)

Warning

Looking for .NET Core? We have a quickstart for that too!

With just a few lines of code, your .NET Framework application can send and receive text messages with Twilio Programmable SMS.

This C# SMS Quickstart will teach you how to do this using our Communications REST API and the Twilio helper library for .NET.

In this Quickstart, you will learn how to:

  1. Sign up for Twilio and get your first SMS-enabled Twilio phone number
  2. Set up your development environment to send and receive messages
  3. Send your first SMS
  4. Receive inbound text messages
  5. Reply to incoming messages with an SMS

Prefer to get started by watching a video? Check out our C# SMS Quickstart video on Youtube(link takes you to an external page).


Sign up for - or sign in to - Twilio

sign-up-for---or-sign-in-to---twilio page anchor
(information)

Info

Already have a Twilio account? Go ahead and skip this section.

(warning)

Warning

If you are sending SMS to the U.S. or Canada, before proceeding further please be aware of updated restrictions on the use of Toll-Free numbers for messaging, including TF numbers obtained through Free Trial. Please click here(link takes you to an external page) for details.

You can sign up for a free Twilio trial account here(link takes you to an external page).

  • When you sign up, you'll be asked to verify your personal phone number. This helps Twilio verify your identity and also allows you to send test messages to your phone from your Twilio account while in trial mode.
  • Once you verify your number, you'll be asked a series of questions to customize your experience.
  • Once you finish the onboarding flow, you'll arrive at your project dashboard in the Twilio Console(link takes you to an external page) . This is where you'll be able to access your Account SID, authentication token, find a Twilio phone number, and more.

If you don't currently own a Twilio phone number with SMS functionality, you'll need to purchase one. After navigating to the Buy a Number(link takes you to an external page) page, check the SMS box and click Search.

Buy a twilio phone number.

You'll then see a list of available phone numbers and their capabilities. Find a number that suits your fancy and click Buy to add it to your account.

Select an SMS-enabled phone number.

We'll need to use the Twilio CLI (command line interface) for a few tasks, so let's install that next.

macOSWindowsLinux

The suggested way to install twilio-cli on macOS is to use Homebrew(link takes you to an external page). If you don't already have it installed, visit the Homebrew site(link takes you to an external page) for installation instructions and then return here.

Once you have installed Homebrew, run the following command to install twilio-cli:


_10
brew tap twilio/brew && brew install twilio

(information)

Info

For other installation methods, see the Twilio CLI Quickstart.

Run twilio login to get the Twilio CLI connected to your account. Visit https://www.twilio.com/console(link takes you to an external page), and you'll find your unique Account SID and Auth Token to provide to the CLI.

Next, we need to install Visual Studio and the Twilio C# Helper Library.


Create a new project and add the Twilio NuGet package

create-a-new-project-and-add-the-twilio-nuget-package page anchor

If you have Visual Studio(link takes you to an external page) installed, you are ready to get going. Otherwise, you should download and install it now.

Visual Studio 2019Visual Studio 2017

Once you have Visual Studio, open it up and create a new Console project. Click the Create a new project button:

CS2019-Create-a-new-project.

And then choose Console App (.NET Framework) from the list of project templates:

VS2019-New-Console-Framework.

Install the Twilio REST API helper library

install-the-twilio-rest-api-helper-library page anchor

Then use the NuGet Package Manager(link takes you to an external page) to find and install the Twilio REST API helper library.

Twilio REST API helper library in Nuget Package Manager (Visual Studio).

Send an Outbound SMS Message with C#

send-an-outbound-sms-message-with-c page anchor

Now that we have .NET and the Twilio .NET library installed, we can send an outbound text message from the Twilio phone number we just purchased with a single API request. Open the file in your new project called Program.cs and type or paste in this code sample, replacing the template code that's already there.

Send an SMS Using Twilio with C#

send-an-sms-using-twilio-with-c page anchor

This code creates a new instance of the Message resource and sends an HTTP POST to the Messages resource URI.

C#

_24
// Install the C# / .NET helper library from twilio.com/docs/csharp/install
_24
_24
using System;
_24
using Twilio;
_24
using Twilio.Rest.Api.V2010.Account;
_24
using System.Threading.Tasks;
_24
_24
class Program {
_24
public static async Task Main(string[] args) {
_24
// Find your Account SID and Auth Token at twilio.com/console
_24
// and set the environment variables. See http://twil.io/secure
_24
string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
_24
string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");
_24
_24
TwilioClient.Init(accountSid, authToken);
_24
_24
var message = await MessageResource.CreateAsync(
_24
body: "Join Earth's mightiest heroes. Like Kevin Bacon.",
_24
from: new Twilio.Types.PhoneNumber("+15017122661"),
_24
to: new Twilio.Types.PhoneNumber("+15558675310"));
_24
_24
Console.WriteLine(message.Body);
_24
}
_24
}

Output

_28
{
_28
"account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_28
"api_version": "2010-04-01",
_28
"body": "Join Earth's mightiest heroes. Like Kevin Bacon.",
_28
"date_created": "Thu, 24 Aug 2023 05:01:45 +0000",
_28
"date_sent": "Thu, 24 Aug 2023 05:01:45 +0000",
_28
"date_updated": "Thu, 24 Aug 2023 05:01:45 +0000",
_28
"direction": "outbound-api",
_28
"error_code": null,
_28
"error_message": null,
_28
"from": "+15017122661",
_28
"num_media": "0",
_28
"num_segments": "1",
_28
"price": null,
_28
"price_unit": null,
_28
"messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
_28
"sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
_28
"status": "queued",
_28
"subresource_uris": {
_28
"media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json"
_28
},
_28
"tags": {
_28
"campaign_name": "Spring Sale 2022",
_28
"message_type": "cart_abandoned"
_28
},
_28
"to": "+15558675310",
_28
"uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json"
_28
}

You'll need to edit this file a little more before your message will send:

Replace the placeholder credential values

replace-the-placeholder-credential-values page anchor

Swap the placeholder values for accountSid and authToken with your personal Twilio credentials. Go to https://www.twilio.com/console(link takes you to an external page) and log in. On this page, you'll find your unique Account SID and Auth Token, which you'll need any time you send messages through the Twilio client like this.

Edit Program.cs and replace the values for accountSid and authToken with your unique values.

(error)

Danger

Please note: it's okay to hardcode your credentials when getting started, but you should use configuration to keep them secret before deploying to production. We recommend using environment variables to store your user secrets(link takes you to an external page).

Replace the "from" phone number

replace-the-from-phone-number page anchor

Remember that SMS-enabled phone number you bought just a few minutes ago? Go ahead and replace the existing from number with that one, making sure to use E.164 formatting:

[+][country code][phone number including area code]

Replace the "to" phone number

replace-the-to-phone-number page anchor

Replace the to phone number with your mobile phone number. This can be any phone number that can receive text messages, but it's a good idea to test with your own phone, so you can see the magic happen! As above, you should use E.164 formatting for this value.

(warning)

Warning

If you are on a Twilio Trial account, your outgoing SMS messages are limited to phone numbers that you have verified with Twilio. Phone numbers can be verified via your Twilio Console's Verified Caller IDs(link takes you to an external page).

Save your changes and run your project in Visual Studio.

That's it! In a few moments, you should receive an SMS from your Twilio number on your phone.

Are your customers in the U.S. or Canada? You can also send them MMS messages by adding just one line of code. Check out this sending MMS tutorial to see how it's done.


Receive and Reply to Inbound SMS Messages with ASP.NET MVC

receive-and-reply-to-inbound-sms-messages-with-aspnet-mvc page anchor

When your Twilio number receives an incoming message, Twilio will send an HTTP request to a server you control. This callback mechanism is known as a webhook. When Twilio sends your application a request, it expects a response in the TwiML XML format telling it how to respond to the message. Let's see how we would build this in C# using ASP.NET MVC for .NET Framework.

Create a New ASP.NET MVC Project in Visual Studio

create-a-new-aspnet-mvc-project-in-visual-studio page anchor
Visual Studio 2019Visual Studio 2017

In Visual Studio, click "Create a new project":

CS2019-Create-a-new-project.

Select "ASP.NET Web Application (.NET Framework)" from the list of templates:

VS2019-New-ASPNET-Framework.
Visual Studio 2019 0 Create a new ASP.NET Web Application.

When prompted, choose "MVC" as the project type:

Install the Twilio.AspNet.Mvc Package

install-the-twilioaspnetmvc-package page anchor

Following Microsoft's instructions(link takes you to an external page) for your version of Visual Studio, find and install the Twilio.AspNet.Mvc package.

Twilio.AspNet.Mvc in Nuget Package Manager (Visual Studio).

In the directory named Controllers, create a new Controller called SmsController.cs. (Right-click on the Controllers folder, then select Add > Controller... > MVC 5 Controller - Empty.)

Paste the following code into SmsController.cs. This creates an action that can handle incoming messages. Be sure to use the entire code sample (note, for example, how the SmsController inherits from TwilioController).

Respond to an incoming text message

respond-to-an-incoming-text-message page anchor

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


_22
// Code sample for ASP.NET MVC on .NET Framework 4.6.1+
_22
// In Package Manager, run:
_22
// Install-Package Twilio.AspNet.Mvc -DependencyVersion HighestMinor
_22
_22
using Twilio.AspNet.Common;
_22
using Twilio.AspNet.Mvc;
_22
using Twilio.TwiML;
_22
_22
namespace WebApplication1.Controllers
_22
{
_22
public class SmsController : TwilioController
_22
{
_22
public TwiMLResult Index(SmsRequest incomingMessage)
_22
{
_22
var messagingResponse = new MessagingResponse();
_22
messagingResponse.Message("The copy cat says: " +
_22
incomingMessage.Body);
_22
_22
return TwiML(messagingResponse);
_22
}
_22
}
_22
}

From Visual Studio, run the application (click the "play" arrow). This should open a web browser with the ASP.NET welcome page showing with a URL something like https://localhost:44360(link takes you to an external page). Note: your port number may be something other than 44360.

Configure ngrok and your webhook URL

configure-ngrok-and-your-webhook-url page anchor

We'll use ngrok to set up a tunnel from the public internet to your localhost. This will let us use a public URL as the webhook for your application.

First, download and configure ngrok(link takes you to an external page).

Next, run this command to have ngrok set up a tunnel to your localhost:


_10
ngrok http 44360

This will start an ngrok tunnel. Copy down the Forwarding URL that ends with ngrok.io.

Then, you need to configure your Twilio phone number to call your webhook URL whenever a new message comes in:

  1. Go to Phone Numbers > Active Numbers in the Twilio Console(link takes you to an external page) .
  2. Select the SMS-enabled Twilio number you want to use.
  3. For the A MESSAGE COMES IN webhook, enter the ngrok URL you copied down earlier. Append /sms to the end of the URL.
ngrok webhook configuration with SMS suffix.

Test your application with a text

test-your-application-with-a-text page anchor

Make sure your project is running and your ngrok tunnel is running.

With both of those servers running, we're ready for the fun part - testing our new ASP.NET SMS application!

Send an SMS from your mobile phone to your Twilio phone number that's configured with this webhook. Your ASP.NET app will process the text message, and you'll get your response back as an SMS.


Now that you know the basics of sending and receiving SMS and MMS text messages with C# and .NET, you might want to check out these resources.

Happy hacking!


Rate this page: