Saturday, May 14, 2016

How to send SMS from asp.net MVC appliction

In this article I am going to explain how to send SMS in asp.net MVC application.


Description:
To fulfill this requirement I am using Twilio restful API service.

Implementation:

First of all create a account on Twilio and verify your phone number. Now configure a number for messaging. You can also buy a preferred number.

Add Twilio DLL

Now add the Twilio DLL to project. Here I will add this to project through Nuget. Run the below command in Package manager console:
                  Install-package twilio

Add Controller

Now add a empty controller to project. Import the Twilio namespace and write the below given code to send SMS.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Twilio;

namespace MVC_Project.Controllers
{
    public class SendSMSController : Controller
    {
        //
        // GET: /SendSMS/

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult SendSMS()
        {
            return View();
        }
        [HttpPost]
        public ActionResult SendSMS(string phone,string message)

        {
            string AccountSid  = "Account ID";
            string Token = "Auth Token";
            var twilio = new TwilioRestClient(AccountSid , Token);
            string number = "+91" + phone;
            var send = twilio.SendSmsMessage("+13183901909", number, message);
            TempData["successful"] = "SMS send Successfully";
            return RedirectToAction("sendsms");
        }
    }
}

Add View

Add view for send SMS and design as code given below:

@{
    ViewBag.Title = "Send SMS";
    var message = TempData["successful"];
}

<h2>Send SMS</h2>
@using (Html.BeginForm())
{
    <table>
        <tr><td>Enter phone No. :</td><td>@Html.TextBox("phone","",new {@placeholder="Phone Number",style="width:200px"})</td></tr>
        <tr><td>Message</td><td>@Html.TextArea("message", "", new { @placeholder = "Message", style = "width:200px;height:150px" })</td></tr>
        <tr><td></td><td><input type="submit" value="Send Message" /></td></tr>
    </table>   
}
<script type="text/javascript">
    var message = '@message';
    if(message)
        alert(message);
</script>

You have done it. Now build and run the application. To test it send sms to your mobile number.

Note: Trial account will send SMS to verified phone number.



2 comments:

  1. SendSmsMessage this method is not exists in TwilioRestClient

    ReplyDelete