Showing posts with label Send Email in Asp.net MVC. Show all posts
Showing posts with label Send Email in Asp.net MVC. Show all posts

Thursday, March 8, 2018

Part 51 - Send OTP ( One Time Password ) to any mobile number in Asp.net MVC



In this video you will be able to know how to send OTP ( One time password) to any mobile number.  You need to follow below steps

1. Visit  TextLocal  official website and Register yourself
2. Generate API Key as show in video

3. Use your API key in C# MVC to send OTP via textlocal API 

Please copy below codes after generating API key.

# View Page (Index.cshtml)
Right click on your controller' s Index method and add a view. After adding view, replace content with below code. 

@model MVCTutorial.Models.EmployeeViewModel
@{
    ViewBag.Title = "Index";
    // Layout = null;
}

        <div class="well">
           
            <a href="#" class="btn btn-success" onclick="SendOTP()">Send OTP</a>

        </div>

<script>


    var SendOTP = function () {
        
        $.ajax({
            url: "/Test/SendOTP",
            type: "post",
            success: function (data) {
                if (data == "success") {
                    
                    alert("OTP sent successfully");
                    window.location = "/Test/EnterOTP";
                }
                else {
                    alert("failed");
                }
            }


        })

    }

</script>




# Controller Code (TestController.cs)
Create a Test controller and copy below code into this. 

using ASPSnippets.SmsAPI;
using MVCTutorial.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace MVCTutorial.Controllers
{
    public class TestController : Controller
    {
        public ActionResult Index()
        {         

            return View();
        }

      
        public JsonResult SendOTP()
        {
            int otpValue = new Random().Next(100000, 999999);
            var status = "";
            try
            {
                string recipient =  ConfigurationManager.AppSettings["RecipientNumber"].ToString();
                string APIKey = ConfigurationManager.AppSettings["APIKey"].ToString();

                string message = "Your OTP Number is " + otpValue + " ( Sent By : Technotips-Ashish )";
                String encodedMessage = HttpUtility.UrlEncode(message);

                using (var webClient = new WebClient())
                {
                    byte[] response = webClient.UploadValues("https://api.textlocal.in/send/", new NameValueCollection(){
                                        
                                         {"apikey" , APIKey},
                                         {"numbers" , recipient},
                                         {"message" , encodedMessage},
                                         {"sender" , "TXTLCL"}});

                    string result = System.Text.Encoding.UTF8.GetString(response);

                    var jsonObject = JObject.Parse(result);

                    status = jsonObject["status"].ToString();

                    Session["CurrentOTP"] = otpValue;
                }


                return Json(status, JsonRequestBehavior.AllowGet);


            }
            catch (Exception e)
            {

                throw (e);

            }

        }

        public ActionResult EnterOTP()
        {
            return View();
        }
        
        [HttpPost]
        public JsonResult VerifyOTP(string otp)
        {
            bool result = false;

            string sessionOTP = Session["CurrentOTP"].ToString();

            if (otp == sessionOTP)
            {
                result = true;

            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

    }
}




#Web.Config file
Add two keys into your web.config file . In first key, Enter Your API key generated by textlocal.com website . In second key, Enter your mobile number as recipient  with country code. example: 919234567895 . You can get mobile number either from database or from the textbox in which user enter his mobile number.


  <add key="APIKey" value="Enter your API key here" />
  <add key="RecipientNumber" value="91XXXXXXXXXX" />
  



All Code Factory


Wednesday, August 9, 2017

Part 43 - How to send emails in Asp.net MVC | Step by step guide




In this video you will learn how to send emails in asp.net mvc. 

#Controller Code
Add a controller named "Test" and replace everything with below code. In below code, you will find three methods
a) SendMailToUser() : This method will call SendEmail() with required parameters
b) SendEmail() : This method will send emails via smtp client

using MVCTutorial.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace MVCTutorial.Controllers
{

    public class TestController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }
        
        public JsonResult SendMailToUser()
        {

            bool result = false;

            result = SendEmail("technotipstutorial@gmail.com", "Technotips email sending test", "<p>Hi Ashish,<br />This email is just for testing purpose. So dont be upset.<br />Regards Technotips</p>");

            return Json(result, JsonRequestBehavior.AllowGet);

        }

        public bool SendEmail(string toEmail, string subject, string emailBody)
        {

            try
            {
                string senderEmail = System.Configuration.ConfigurationManager.AppSettings["SenderEmail"].ToString();
                string senderPassword = System.Configuration.ConfigurationManager.AppSettings["SenderPassword"].ToString();

                SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                client.EnableSsl = true;
                client.Timeout = 100000;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential(senderEmail, senderPassword);

                MailMessage mailMessage = new MailMessage(senderEmail, toEmail, subject, emailBody);
                mailMessage.IsBodyHtml = true;
                mailMessage.BodyEncoding = UTF8Encoding.UTF8;
                client.Send(mailMessage);

                return true;

            }
            catch (Exception ex)
            {
                return false;

            }

        }


    }
}

  

 # Web.config file

Add app setting into web.config file.  

<appSettings>
    
    <add key="SenderEmail" value="youremailaddress@gmail.com" />
    <add key="SenderPassword" value="******" />
         
  </appSettings>


All Code Factory