How to Send SMS in ASP.NET Core

How to Send SMS in ASP.NET Core

In this article, I will explain How to Send SMS in ASP.NET Core. Please read our previous article discussing Account Lockout in ASP.NET Core Identity.

How to Send SMS with ASP.NET Core?

Sending an SMS using ASP.NET Core typically involves integrating with an SMS gateway provider through their API. Here’s a general guideline of the steps you need to follow to send an SMS in ASP.NET Core:

  1. Choose an SMS Gateway Provider: First, select an SMS gateway provider like Twilio, Nexmo, or any other provider that offers an API for sending SMS messages.
  2. Set Up an Account and Get API Credentials: Sign up with the chosen provider and obtain the necessary API credentials (like API key and secret).
  3. Install Necessary Packages: Depending on the provider, you may need to install their .NET SDK or any other necessary NuGet package in your ASP.NET Core project.

Setting up a Twilio SMS Account

The first thing we need to do is create a Twilio account. When we create an account, we will be given a free trial account with 15.50 USD. We can use the trial balance to purchase a phone number and send and receive messages. Setting up a Twilio SMS account involves several steps. Here’s a general guide to help you through the process:

Sign Up for Twilio:
  • Visit the Twilio website: https://www.twilio.com/try-twilio
  • Click on the “Sign Up” button.
  • Fill in your details like First Name, Last Name, Email, and Password.
  • Verify your Email address.
Phone Number Verification:
  • After signing up, Twilio requires you to verify a personal phone number. This is a security measure.
  • Enter your phone number, and you will receive a verification code via SMS or a call.
  • Enter the received code to verify your number.
  • Once the Phone is verified, please save the Recovery code, which can be useful if you lose your phone or don’t have access to your verification device. 
Account Activation:
  • Some additional information might be required to activate your account.
  • You might be asked about your intended use of Twilio services.
Choosing a Twilio Phone Number:
  • Once your account is activated, you can choose a Twilio phone number.
  • This number will be used for sending and receiving SMS messages.
  • You can select a number based on your preferred country and features.

Setting up a Twilio SMS Account

Once you buy the Twilio phone number, if you go to your Twilio account, you will see the following information: Account SID, Auth Token, and Twilio Phone number.

Setting up a Twilio SMS Account

Note: In a trial account, you can only send messages and make calls to verified phone numbers. It is also possible to add multiple verified phone numbers as follows.

How to Send SMS with ASP.NET Core?

API Integration:
  • You’ll need to integrate Twilio’s API with your application for sending and receiving SMS.
  • Twilio provides documentation and SDKs in various programming languages for easier integration.

So, open the Manage NuGet Package for Solution and add the Twilio package, as shown in the image below.

API Integration

Next, add the following to the appsettings.json file. You will get the Account SID, Auth Token, and From Number (your Twilio Number) from your Twilio account.

"SMSSettings": {
    "AccountSID": "Your Account SID",
    "AuthToken": "Your Account Auth Token",
    "FromNumber": "Your Twilio Number"
}
Implement the SMS Sending Functionality:
  • Create a service class in your ASP.NET Core application to encapsulate the SMS-sending functionality.
  • Use the API credentials to authenticate with the SMS gateway.
  • Implement a method to send SMS messages using the provider’s API. This typically involves creating a request with the recipient’s phone number, your message, and any other required parameters and then sending this request to the API endpoint.
  • Implement error handling to manage any issues that might occur while sending messages. Also, add logging to track the status of sent messages.

Create a class file named SMSSender.cs and copy and paste the following code. The following code is self-explained, so please go through the comment line for a better understanding.

using Twilio.Types;
using Twilio;
using Twilio.Rest.Api.V2010.Account;

namespace ASPNETCoreIdentityDemo.Models
{
    public interface ISMSSender
    {
        Task<bool> SendSmsAsync(string to, string message);
    }

    public class SMSSender : ISMSSender
    {
        private readonly IConfiguration _configuration;
        private readonly string AccountSID;
        private readonly string AuthToken;
        private readonly string FromNumber;

        public SMSSender(IConfiguration configuration)
        {
            _configuration = configuration;

            AccountSID = _configuration["SMSSettings:AccountSID"];
            AuthToken = _configuration["SMSSettings:AuthToken"];
            FromNumber = _configuration["SMSSettings:FromNumber"];
        }

        public Task<bool> SendSmsAsync(string to, string message)
        {
            try
            {
                //Initialize base client with AccountSID and AuthToken
                TwilioClient.Init(AccountSID, AuthToken);

                //Construct a new CreateMessageOptions
                var messageOptions = new CreateMessageOptions(new PhoneNumber(to))
                {
                    From = new PhoneNumber(FromNumber),
                    Body = message
                };

                //Send a message
                var msg = MessageResource.Create(messageOptions);

                //Return true if no error
                return Task.FromResult(true);
            }
            catch (Exception ex)
            {
                //Log the Error Message and Return false
                return Task.FromResult(false);
            }
        }
    }
}
Here are the Important Methods:
TwilioClient.Init(AccountSID, AuthToken):

In ASP.NET Core, when integrating Twilio for functionalities like sending SMS or making phone calls, you need to initialize the Twilio client with your Twilio account credentials. The TwilioClient.Init method is used to initialize the Twilio client with your account SID and auth token. It’s recommended to store these credentials securely, such as in an app settings file or environment variables, rather than hardcoding them in your application.

CreateMessageOptions:

Using CreateMessageOptions is a common way to send SMS messages in an ASP.NET Core application. This class is part of the Twilio SDK. It allows you to specify various parameters for an outgoing SMS, such as the recipient’s phone number, the sender’s phone number (or a Twilio number), and the message body.

MessageResource.Create:

The MessageResource.Create method from the Twilio SDK in ASP.NET Core is used to send SMS messages. This method is part of the Twilio REST API library and is a primary way to send text messages programmatically via your Twilio account.

Registering the SMSSender Service:

Next, we must register the SMSSender Service to the built-in dependency injection container. To do so, please add the following code to the Main method of the Program class.

builder.Services.AddTransient<ISMSSender, SMSSender>();

In the next article, I will discuss how to Add and Verify Phone Numbers in ASP.NET Core Identity. In this article, I explain how to send SMS with ASP.NET Core. I hope you enjoy this How to Send SMS with ASP.NET Core article.

Leave a Reply

Your email address will not be published. Required fields are marked *