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