Tuesday, May 10, 2016

How to send SMS in asp.net using Twilio

In this article I am going to explain how to send SMS in asp.net using Twilio.


Description:
I am using Twilio API to send sms.

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.

Why we need to configure a number?
We can’t use the verified number to send SMS.

HTML Markup:
  <table>
    <tr><td>Number :</td><td>
        <asp:TextBox ID="txtnumber" runat="server" Width="180px"></asp:TextBox></td></tr>
         <tr><td></td><td></td></tr>
     <tr><td>Message :</td><td>
         <asp:TextBox ID="txtmessage" runat="server" TextMode="MultiLine" Width="180px" Height="200px"></asp:TextBox></td></tr>
          <tr><td></td><td></td></tr>
      <tr><td></td><td>
          <asp:Button ID="btnsend" runat="server" Text="Send Message"/></td></tr>

       <tr><td></td><td></td></tr>
    </table>

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

Import the namespace
C# Code:
using Twilio;

VB.net Code:
Imports Twilio

Send SMS
Write the below code on button click to send SMS.

C# Code:
protected void btnsend_Click(object sender, EventArgs e)
    {
        try
        {
            string AccountSID = "Account SID";
            string Token = "AUTH TOKEN";
            var twilio = new TwilioRestClient(AccountSID, Token);
            string number = "+91" + txtnumber.Text;
            var message = twilio.SendMessage("+13183901909", number, txtmessage.Text);
        }
        catch (Exception ex)
        { }
    }

VB.net Code:
   Protected Sub btnsend_Click(sender As Object, e As System.EventArgs) Handles btnsend.Click
        Dim AccountSID As String = "Account SID"
        Dim Token As String = "AUTH TOKEN"
        Dim twilio = New TwilioRestClient(AccountSID, Token)
        Dim number As String = "+91" + txtnumber.Text
        Dim message = twilio.SendMessage("+13183901909", number, txtmessage.Text)
    End Sub

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: