Sending Emails in ASP.NET MVC

Email communication is very important in today's modern applications, and there are many ways to send emails through applications to users. I wrote a series of articles on email sending in ASP.NET, which has been a very successful series in terms of views and downloads. Now in this article we will learn how to send emails directly from the razor view in ASP.NET MVC with the help of the WebMail helper class .

So let's learn step by step, so beginners can also learn how to send emails in ASP.NET MVC.

What is WebMail Helper Class?

WebMail is a static class that is used in ASP.NET MVC to send emails directly from the Razor view as well as the controller class

Prerequisites
  • Active internet connection.
  • Email id of any provider such as Gmail, Yahoo or your organization to send emails. 
Now let's create a simple MVC application to demonstrate this.

Step 1: Create an ASP.NET MVC Application.


Now let us start with a step by step approach from the creation of a simple MVC application as in the following:
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:
 

3. As shown in the preceding screenshot, click on Empty template and check MVC option, then click OK. This will create an empty MVC web application whose Solution Explorer will look like the following:




Step 2: Create Model Class.


Now let us create the model class named EmployeeModel.cs by right clicking on model folder as in the following screenshot:


 

Note:

It is not mandatory that the Model class be in the Model folder, it is just for better readability. You can create this class anywhere in the solution explorer. This can be done by creating different folder names or without folder names, or in a separate class library.


EmployeeModel.cs class code snippet:
using System.ComponentModel.DataAnnotations;  
  
namespace SendingEmailsWithWebMailInMVC.Models  
{  
    public class EmployeeModel  
    {          
         
        [DataType(DataType.EmailAddress),Display(Name ="To")]  
        [Required]  
        public string ToEmail { get; set; }  
        [Display(Name ="Body")]  
        [DataType(DataType.MultilineText)]  
        public string EMailBody { get; set; }  
        [Display(Name ="Subject")]  
        public string EmailSubject { get; set; }  
        [DataType(DataType.EmailAddress)]  
        [Display(Name ="CC")]  
        public string EmailCC { get; set; }  
        [DataType(DataType.EmailAddress)]  
        [Display(Name ="BCC")]  
        public string EmailBCC { get; set; }  
    }  
}  

Step 3 : Add Controller Class.


Now let us add the MVC 5 controller as in the following screenshot:

 
After clicking on Add button it will show the window. specify the Controller name as Home with suffix Controller.

Note:

The controller name must have a suffix of 'Controller' after specifying the name of the controller. Now the default code in HomeController.cs will look like this.

HomeController.cs
using System.Web.Mvc;  
namespace SendingEmailsWithWebMailInMVC.Controllers  
{  
    public class HomeController : Controller  
    {  
        // GET: Index view  
        public ActionResult Index()  
        {             
            return View();  
        }  
  
        [HttpPost]  
          
        public ActionResult SendEmailView()  
        {  
            //call SendEmailView view to invoke webmail  
            return View();  
        }  
    }  
}  

Step 4 : Creating strongly typed view named Index using employee model and SendEmailView.

Right click on the View folder of the created application and choose Add View. Select employee model class and scaffolding to create a view to send emails.


Now open the Index.cshtml view. Then follow the default code and you will see which is generated by the MVC scaffolding template as,

Index.cshtml
@model SendingEmailsWithWebMailInMVC.Models.EmployeeModel  
  
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
@*Send request to invoke SendEmailView view*@  
@using (Html.BeginForm("SendEmailView","Home",FormMethod.Post))   
{  
    @Html.AntiForgeryToken()  
    <div class="form-horizontal">      
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.ToEmail, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.ToEmail, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.ToEmail, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.EMailBody, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.EMailBody, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.EMailBody, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.EmailSubject, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.EmailSubject, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.EmailSubject, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.EmailCC, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.EmailCC, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.EmailCC, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.EmailBCC, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.EmailBCC, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.EmailBCC, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Send" class="btn btn-default" />  
            </div>  
        </div>  
    </div>  
     
}  
  
<script src="~/Scripts/jquery-1.10.2.min.js"></script>  
<script src="~/Scripts/jquery.validate.min.js"></script>  
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>  

The preceding view is used to get the input email details from users. Now create the view named SendEmailView to configure the emails using the WebMail class..


SendEmailView.cshtml
@{  
    ViewBag.Title = "www.compilemode.com";  
}  
  
  @{  
      try  
      {  
          //parameters to send email  
          string ToEmail, FromOrSenderEmail = "YourGamilId@gmail.com", SubJect, Body, cc, Bcc;  
  
          //Reading values from form collection (Querystring) and assigning values to parameters  
          ToEmail = Request["ToEmail"].ToString();  
          SubJect = Request["EmailSubject"].ToString();  
          Body = Request["EMailBody"].ToString();  
          cc = Request["EmailCC"].ToString();  
          Bcc = Request["EmailBCC"].ToString();  
          //Configuring webMail class to send emails  
          WebMail.SmtpServer = "smtp.gmail.com"; //gmail smtp server  
          WebMail.SmtpPort = 587; //gmail port to send emails  
          WebMail.SmtpUseDefaultCredentials = true;  
          WebMail.EnableSsl = true; //sending emails with secure protocol  
          WebMail.UserName = FromOrSenderEmail;//EmailId used to send emails from application  
          WebMail.Password = "YourGmailPassword";  
          WebMail.From = FromOrSenderEmail; //email sender email address.  
  
          //Sending email  
          WebMail.Send(to: ToEmail, subject: SubJect, body: Body, cc: cc, bcc: Bcc, isBodyHtml: true);  
        <hr />  
        <div class="text-success">  
            Email Sent Successfully.  
        </div>  
      }  
      catch (Exception)  
      {  
        <div class="text-danger">  
            Problem while sending email, please check gmail server details.  
        </div>  
      }  
}  
Now, after adding the model , view, and controller, our application solution explorer will look as follows:




Now we have done all the coding to send emails using the WebMail class.

 
Step 5 : Now run the application.

After running the application, the initial screen will look like this:





The preceding view is used to send the emails. Now click on the send button without entering It throws the following errors to email addresses and invalid cc and bcc email addresses. 


 

Now enter the valid details as follows.



After clicking on the Send button, it will redirect to the SendEmailView, which invokes the WebEmail class and sends the email. After successfully sending the email, the following message will be shown.


Now open your Gmail inbox and see the details which we have used to send the email as,


 
Now open the email. It will show the email content as follows.




I hope from all the preceding examples we have learned how to send email using the WebMail helper class in ASP.NET MVC Razor view.

Note:

  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
  • This application is created completely focusing on beginners.
  • You need an active internet connection to send the email .
Summary

I hope this article is useful for all readers. If you have any suggestions please contact me.
Read more articles on ASP.NET MVC:

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode