Send SMS Using Twilio In C#

This article will help you to send SMS from your application to the user’s phone number for a specific region. Generally Twilio is used to send/ receive a message from the US region.

First Step is to create an account in Twilio using the Sign-Up form here: https://www.twilio.com/try-twilio

Login to your Twilio account and get a number using the free Trial Balance. The trial account is restricted to one number only.

We will be using the following three things from the Twilio Dashboard

Here I have created a demo to send SMS with the message entered by the user to the number entered by the user.

So we will have a view something like this

<h2>
    SMS Sample
</h2>
<div class="container">
    <div class="col-md-6">
        <form method="post" id="textform">
            <div class="form-group">
                <label>Phone Number</label>
                <input type="number" name="txtphone" id="txtphone" class="form-control" required />
            </div>
            <div class="form-group">
                <label>Message</label>
                <textarea type="text" name="txtMessage" id="txtMessage" class="form-control" required></textarea>
            </div>
            <button type="button" class="btn btn-primary" id="btnsubmit">Submit</button>
        </form>
    </div>
</div>

The click event for the button will send the data to the controller

$("#btnsubmit").click(() => {

           if ($("#textform").valid()) {
               $.ajax({
                   url: '/Home/SendSMS',
                   dataType: 'JSON',
                   type: 'POST',
                   data: {
                       ToPhone: $("#txtphone").val(),
                       Message: $("#txtMessage").val()
                   },
                   success: function (result) {
                       if (result) {
                           alert(result.message);
                           $("#textform").get(0).reset()
                       }
                       else {
                           alert("Sorry Server is busy");
                       }
                   },
                   error: function (error) {
                       alert("Sorry Server is busy");
                   }

               });
           }
       });

Add the keys from Twilio account to your web.config

<add key="AccountSID" value="****************************" />   <!--Account SID of your Twilio account-->
<add key="AuthToken" value="****************************" />  <!--Auth Token of your Twilio account-->
<add key="TwilioPhone" value="+************" />    <!--TRIAL Number-->

Add Twilio Nuget Package. Search Twilio in Manage Nuget Package and click on Install.

The function used to send the SMS will be having the following code

[HttpPost]
     public JsonResult SendSMS(String ToPhone, string Message)
     {
         try
         {
             //Fetch all the keys in webconfig file
             string accountSid = ConfigurationManager.AppSettings["AccountSID"];   // Account SID of your Twilio account 
             string authToken = ConfigurationManager.AppSettings["AuthToken"];  // Auth Token of your Twilio account
             string PhoneNumber = ConfigurationManager.AppSettings["TwilioPhone"];  // TRIAL Number
             System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
             TwilioClient.Init(accountSid, authToken);

             ToPhone = ToPhone.Replace("(", "");
             ToPhone = ToPhone.Replace(")", "");
             ToPhone = ToPhone.Replace("-", "");
             ToPhone = ToPhone.Replace(" ", "");
             ToPhone = "+91" + ToPhone;

             var to = new PhoneNumber(ToPhone);
             var message = MessageResource.Create(
                 to: to,
                 from: new PhoneNumber(PhoneNumber),
                 body: Message
                 );

             return Json(new { Status = true, message = "Message Sent Successfully." }, JsonRequestBehavior.AllowGet);

         }
         catch (Exception ex)
         {
             return Json(new { Status = false, message = ex.Message }, JsonRequestBehavior.AllowGet);

         }

     }

Now your demo is ready to run. After sending the SMS you can check the logs in your Twilio portal here: https://www.twilio.com/console/sms/logs

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories