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. For detailed information on policy rules to ensure you remain compliant while using Twilio's services, please see our Acceptable Use Policy.
Looking for .NET Framework? We have a quickstart for that too!
With just a few lines of code, your .NET Core 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 Core.
In this Quickstart, you will learn how to:
Prefer to get started by watching a video? Check out our C# SMS Quickstart video on YouTube.
Already have a Twilio account? Go ahead and skip this section.
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 for details.
You can sign up for a free Twilio trial account here.
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 page, check the SMS box and click Search.
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.
We'll need to use the Twilio CLI (command line interface) for a few tasks, so let's install that next.
The suggested way to install twilio-cli
on macOS is to use Homebrew. If you don't already have it installed, visit the Homebrew site for installation instructions and then return here.
Once you have installed Homebrew, run the following command to install twilio-cli
:
brew tap twilio/brew && brew install twilio
For other installation methods, see the Twilio CLI Quickstart.
Run twilio login
to get the Twilio CLI connected to your account. Visit the Twilio Console, and under Account Info, you'll find your unique Account SID and Auth Token to provide to the CLI.
Next, we need to install .NET Core and the Twilio C# Helper Library.
You can check if you already have .NET Core installed on your machine by opening up a command prompt or terminal and running the following command:
dotnet --version
You should see something like 2.1.3
. If you receive an error message, you can download .NET Core from Microsoft and install it.
Run these commands to create a new .NET project and install the Twilio NuGet package:
1mkdir TwilioSend2cd TwilioSend3dotnet new console4dotnet add package Twilio
Now that we have .NET Core and the Twilio .NET NuGet package 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.
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}
1{2"account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",3"api_version": "2010-04-01",4"body": "Join Earth's mightiest heroes. Like Kevin Bacon.",5"date_created": "Thu, 24 Aug 2023 05:01:45 +0000",6"date_sent": "Thu, 24 Aug 2023 05:01:45 +0000",7"date_updated": "Thu, 24 Aug 2023 05:01:45 +0000",8"direction": "outbound-api",9"error_code": null,10"error_message": null,11"from": "+15017122661",12"num_media": "0",13"num_segments": "1",14"price": null,15"price_unit": null,16"messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",17"sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",18"status": "queued",19"subresource_uris": {20"media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json"21},22"tags": {23"campaign_name": "Spring Sale 2022",24"message_type": "cart_abandoned"25},26"to": "+15558675310",27"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:
Swap the placeholder values for accountSid
and authToken
with your personal Twilio credentials. Go to Twilio Console 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.
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've written blog posts on how to secure user secrets in a .NET Core Web App and a .NET Core Console App that should provide you with some good guidance.
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 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.
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.
Save your changes and run this code:
dotnet run
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.
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 Core.
Run these commands to create a new ASP.NET Core project and install the Twilio NuGet package:
1mkdir TwilioReceive2cd TwilioReceive3dotnet new mvc4dotnet add package Twilio.AspNet.Core
In the directory named Controllers
, create a new Controller called SmsController.cs
and use the following code to create a server that can handle incoming messages.
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).
1// Code sample for ASP.NET Core on .NET Core2// From command prompt, run:3// dotnet add package Twilio.AspNet.Core45using Twilio.AspNet.Common;6using Twilio.AspNet.Core;7using Twilio.TwiML;89namespace TwilioReceive.Controllers10{11public class SmsController : TwilioController12{13public TwiMLResult Index(SmsRequest incomingMessage)14{15var messagingResponse = new MessagingResponse();16messagingResponse.Message("The copy cat says: " +17incomingMessage.Body);1819return TwiML(messagingResponse);20}21}22}
Save the file, then return to the root folder in your project and run your application with:
dotnet run
In your favorite browser, open the URL http://localhost:5242/sms (the port may be different on your computer; check the output of the previous command to identify your port).
If all went well, you should see XML in your browser with the message we'd like to reply with to all our inbound texts. And, yes, that's all the code you need - there's just one more step before everything is wired up.
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.
Next, run this command to have ngrok set up a tunnel to your localhost:
ngrok http 5242
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:
Go to Phone Numbers > Active Numbers in the Twilio Console.
Select the SMS-enabled Twilio number you want to use.
For the A MESSAGE COMES IN webhook, enter the ngrok URL you copied down earlier. Append /sms
to the end of the URL.
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 Core SMS application!
Send an SMS from your mobile phone to your Twilio phone number that's configured with this webhook. Your ASP.NET Core 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!