Sending Emails In ASP.NET MVC From Controller Using WebMail Helper

Background

In my previous article on Sending Emails In ASP.NET MVC From Razor View, we have learned how to send emails from View using WebMail Class , Now in this article we will learn how to send emails in ASP.NET MVC from controller with the help WebMail helper class. So let's learn step by step so beginners can also learn how to send emails in ASP.NET MVC from controller.
 
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 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 Model class should be in 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 name or in a separate class library.
EmployeeModel.cs class code snippet: 
  1. using System.ComponentModel.DataAnnotations;  
  2.   
  3. namespace SendingEmailsFromController.Models  
  4. {  
  5.     public class EmployeeModel  
  6.     {  
  7.           
  8.          
  9.         [DataType(DataType.EmailAddress),Display(Name ="To")]  
  10.         [Required]  
  11.         public string ToEmail { getset; }  
  12.         [Display(Name ="Body")]  
  13.         [DataType(DataType.MultilineText)]  
  14.         public string EMailBody { getset; }  
  15.         [Display(Name ="Subject")]  
  16.         public string EmailSubject { getset; }  
  17.         [DataType(DataType.EmailAddress)]  
  18.         [Display(Name ="CC")]  
  19.         public string EmailCC { getset; }  
  20.         [DataType(DataType.EmailAddress)]  
  21.         [Display(Name ="BCC")]  
  22.         public string EmailBCC { getset; }  
  23.     }  

 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 be having suffix as 'Controller' after specifying the name of controller. Now the default code in HomeController.cs will look like as follows,

HomeController.cs
  1. using SendingEmailsFromController.Models;  
  2. using System;  
  3. using System.Web.Helpers;  
  4. using System.Web.Mvc;  
  5.   
  6. namespace SendingEmailsFromController.Controllers  
  7. {  
  8.     public class HomeController : Controller  
  9.     {  
  10.         // GET: Home  
  11.         public ActionResult SendEmail()  
  12.         {  
  13.              
  14.             return View();  
  15.         }  
  16.   
  17.         [HttpPost]  
  18.         public ActionResult SendEmail(EmployeeModel obj)  
  19.         {  
  20.               
  21.             try  
  22.             {  
  23.                 //Configuring webMail class to send emails  
  24.                 //gmail smtp server  
  25.                 WebMail.SmtpServer = "smtp.gmail.com";   
  26.                 //gmail port to send emails  
  27.                 WebMail.SmtpPort = 587;  
  28.                 WebMail.SmtpUseDefaultCredentials = true;  
  29.                 //sending emails with secure protocol  
  30.                 WebMail.EnableSsl = true;   
  31.                 //EmailId used to send emails from application  
  32.                 WebMail.UserName = "YourGamilId@gmail.com";  
  33.                 WebMail.Password = "YourGmailPassword";  
  34.                 
  35.                 //Sender email address.  
  36.                 WebMail.From = "SenderGamilId@gmail.com";   
  37.   
  38.                 //Send email  
  39.                 WebMail.Send(to: obj.ToEmail, subject: obj.EmailSubject, body: obj.EMailBody, cc: obj.EmailCC, bcc: obj.EmailBCC, isBodyHtml: true);  
  40.                 ViewBag.Status = "Email Sent Successfully.";  
  41.       }  
  42.       catch (Exception)  
  43.       {  
  44.                 ViewBag.Status = "Problem while sending email, Please check details.";  
  45.   
  46.        }  
  47.             return View();  
  48.         }  
  49.     }  

 Step 4 :

Create strongly typed view named SendEmail using EmployeeModel class.

Right click on View folder of created application and choose add view , select employee model class and scaffolding template as create . As shown in the following image,

 

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

SendEmail.cshtml
 
  1. @model SendingEmailsFromController.Models.EmployeeModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "www.compilemode.com";  
  5. }  
  6. @using (Html.BeginForm())  
  7. {  
  8.     @Html.AntiForgeryToken()  
  9.   
  10.   
  11.     <div class="form-horizontal">  
  12.         <hr />  
  13.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  14.         <div class="form-group">  
  15.             @Html.LabelFor(model => model.ToEmail, htmlAttributes: new { @class = "control-label col-md-2" })  
  16.             <div class="col-md-10">  
  17.                 @Html.EditorFor(model => model.ToEmail, new { htmlAttributes = new { @class = "form-control" } })  
  18.                 @Html.ValidationMessageFor(model => model.ToEmail, ""new { @class = "text-danger" })  
  19.             </div>  
  20.         </div>  
  21.   
  22.         <div class="form-group">  
  23.             @Html.LabelFor(model => model.EMailBody, htmlAttributes: new { @class = "control-label col-md-2" })  
  24.             <div class="col-md-10">  
  25.                 @Html.EditorFor(model => model.EMailBody, new { htmlAttributes = new { @class = "form-control" } })  
  26.                 @Html.ValidationMessageFor(model => model.EMailBody, ""new { @class = "text-danger" })  
  27.             </div>  
  28.         </div>  
  29.   
  30.         <div class="form-group">  
  31.             @Html.LabelFor(model => model.EmailSubject, htmlAttributes: new { @class = "control-label col-md-2" })  
  32.             <div class="col-md-10">  
  33.                 @Html.EditorFor(model => model.EmailSubject, new { htmlAttributes = new { @class = "form-control" } })  
  34.                 @Html.ValidationMessageFor(model => model.EmailSubject, ""new { @class = "text-danger" })  
  35.             </div>  
  36.         </div>  
  37.   
  38.         <div class="form-group">  
  39.             @Html.LabelFor(model => model.EmailCC, htmlAttributes: new { @class = "control-label col-md-2" })  
  40.             <div class="col-md-10">  
  41.                 @Html.EditorFor(model => model.EmailCC, new { htmlAttributes = new { @class = "form-control" } })  
  42.                 @Html.ValidationMessageFor(model => model.EmailCC, ""new { @class = "text-danger" })  
  43.             </div>  
  44.         </div>  
  45.   
  46.         <div class="form-group">  
  47.             @Html.LabelFor(model => model.EmailBCC, htmlAttributes: new { @class = "control-label col-md-2" })  
  48.             <div class="col-md-10">  
  49.                 @Html.EditorFor(model => model.EmailBCC, new { htmlAttributes = new { @class = "form-control" } })  
  50.                 @Html.ValidationMessageFor(model => model.EmailBCC, ""new { @class = "text-danger" })  
  51.             </div>  
  52.         </div>  
  53.   
  54.         <div class="form-group">  
  55.             <div class="col-md-offset-2 col-md-10">  
  56.                 <input type="submit" value="Send" class="btn btn-primary" />  
  57.             </div>  
  58.         </div>  
  59.         <div class="form-group">  
  60.             <div class="col-md-offset-2 col-md-10 text-success">  
  61.                 @ViewBag.Status  
  62.             </div>  
  63.         </div>  
  64.     </div>  
  65.   

 Now after adding the model , view and controller our application solution explorer will look as follows,
 
 
Now we have done all coding to send emails using WebMail class.

Step 5 : Now run the application.

After running the application initial screen will look as follows,
 
 
The preceding view is used to send the emails , now click on send button without entering To email address and invalid cc and Bcc email address it throws the following errors .
 
 
Now Enter the valid details as follows,
 
 

Now click on Send button , after successfully sending the email the following message will be shown, 
 
 
Now open the 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 in ASP.NET MVC from controller using WebMail helper class .

Note:
  • Download the Zip file of the sample application for a better understanding.
  • Since this is a demo, it might not be using proper standards, so improve it depending on your skills.
  • 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: