Sending Emails In ASP.NET MVC From Razor View Using WebMail Helper

Background

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 ia  very successful series in terms of views and downloads. Now in this article we will learn how to send emails directly from razor view in ASP.NET MVC with the help of 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 the static class whicis  used to send emails directly from  Razor view as well controller class in ASP.NET MVC .

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 SendingEmailsWithWebMailInMVC.Models  
  4. {  
  5.     public class EmployeeModel  
  6.     {          
  7.          
  8.         [DataType(DataType.EmailAddress),Display(Name ="To")]  
  9.         [Required]  
  10.         public string ToEmail { getset; }  
  11.         [Display(Name ="Body")]  
  12.         [DataType(DataType.MultilineText)]  
  13.         public string EMailBody { getset; }  
  14.         [Display(Name ="Subject")]  
  15.         public string EmailSubject { getset; }  
  16.         [DataType(DataType.EmailAddress)]  
  17.         [Display(Name ="CC")]  
  18.         public string EmailCC { getset; }  
  19.         [DataType(DataType.EmailAddress)]  
  20.         [Display(Name ="BCC")]  
  21.         public string EmailBCC { getset; }  
  22.     }  

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 System.Web.Mvc;  
  2.   
  3. namespace SendingEmailsWithWebMailInMVC.Controllers  
  4. {  
  5.     public class HomeController : Controller  
  6.     {  
  7.         // GET: Index view  
  8.         public ActionResult Index()  
  9.         {             
  10.             return View();  
  11.         }  
  12.   
  13.         [HttpPost]  
  14.           
  15.         public ActionResult SendEmailView()  
  16.         {  
  17.             //call SendEmailView view to invoke webmail  
  18.             return View();  
  19.         }  
  20.     }  

 Step 4 : Creating strongly typed view named Index using employee model and SendEmailView .
 
Right click on View folder of created application and choose add view , select employee model class and scaffolding create template to create view to send emails
 
 
Now open the Index.cshtml view , Then following default code you will see which is generated by MVC scaffolding template as,

Index.cshtml
  1. @model SendingEmailsWithWebMailInMVC.Models.EmployeeModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "www.compilemode.com";  
  5. }  
  6. @*Send request to invoke SendEmailView view*@  
  7. @using (Html.BeginForm("SendEmailView","Home",FormMethod.Post))   
  8. {  
  9.     @Html.AntiForgeryToken()  
  10.     <div class="form-horizontal">      
  11.         <hr />  
  12.         @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
  13.         <div class="form-group">  
  14.             @Html.LabelFor(model => model.ToEmail, htmlAttributes: new { @class = "control-label col-md-2" })  
  15.             <div class="col-md-10">  
  16.                 @Html.EditorFor(model => model.ToEmail, new { htmlAttributes = new { @class = "form-control" } })  
  17.                 @Html.ValidationMessageFor(model => model.ToEmail, "", new { @class = "text-danger" })  
  18.             </div>  
  19.         </div>  
  20.   
  21.         <div class="form-group">  
  22.             @Html.LabelFor(model => model.EMailBody, htmlAttributes: new { @class = "control-label col-md-2" })  
  23.             <div class="col-md-10">  
  24.                 @Html.EditorFor(model => model.EMailBody, new { htmlAttributes = new { @class = "form-control" } })  
  25.                 @Html.ValidationMessageFor(model => model.EMailBody, "", new { @class = "text-danger" })  
  26.             </div>  
  27.         </div>  
  28.   
  29.         <div class="form-group">  
  30.             @Html.LabelFor(model => model.EmailSubject, htmlAttributes: new { @class = "control-label col-md-2" })  
  31.             <div class="col-md-10">  
  32.                 @Html.EditorFor(model => model.EmailSubject, new { htmlAttributes = new { @class = "form-control" } })  
  33.                 @Html.ValidationMessageFor(model => model.EmailSubject, "", new { @class = "text-danger" })  
  34.             </div>  
  35.         </div>  
  36.   
  37.         <div class="form-group">  
  38.             @Html.LabelFor(model => model.EmailCC, htmlAttributes: new { @class = "control-label col-md-2" })  
  39.             <div class="col-md-10">  
  40.                 @Html.EditorFor(model => model.EmailCC, new { htmlAttributes = new { @class = "form-control" } })  
  41.                 @Html.ValidationMessageFor(model => model.EmailCC, "", new { @class = "text-danger" })  
  42.             </div>  
  43.         </div>  
  44.   
  45.         <div class="form-group">  
  46.             @Html.LabelFor(model => model.EmailBCC, htmlAttributes: new { @class = "control-label col-md-2" })  
  47.             <div class="col-md-10">  
  48.                 @Html.EditorFor(model => model.EmailBCC, new { htmlAttributes = new { @class = "form-control" } })  
  49.                 @Html.ValidationMessageFor(model => model.EmailBCC, "", new { @class = "text-danger" })  
  50.             </div>  
  51.         </div>  
  52.   
  53.         <div class="form-group">  
  54.             <div class="col-md-offset-2 col-md-10">  
  55.                 <input type="submit" value="Send" class="btn btn-default" />  
  56.             </div>  
  57.         </div>  
  58.     </div>  
  59.      
  60. }  
  61.   
  62. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  63. <script src="~/Scripts/jquery.validate.min.js"></script>  
  64. <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 WebMail class.

SendEmailView.cshtml
  1. @{  
  2.     ViewBag.Title = "www.compilemode.com";  
  3. }  
  4.   
  5.   @{  
  6.       try  
  7.       {  
  8.           //parameters to send email  
  9.           string ToEmail, FromOrSenderEmail = "[email protected]", SubJect, Body, cc, Bcc;  
  10.   
  11.           //Reading values from form collection (Querystring) and assigning values to parameters  
  12.           ToEmail = Request["ToEmail"].ToString();  
  13.           SubJect = Request["EmailSubject"].ToString();  
  14.           Body = Request["EMailBody"].ToString();  
  15.           cc = Request["EmailCC"].ToString();  
  16.           Bcc = Request["EmailBCC"].ToString();  
  17.           //Configuring webMail class to send emails  
  18.           WebMail.SmtpServer = "smtp.gmail.com"//gmail smtp server  
  19.           WebMail.SmtpPort = 587; //gmail port to send emails  
  20.           WebMail.SmtpUseDefaultCredentials = true;  
  21.           WebMail.EnableSsl = true//sending emails with secure protocol  
  22.           WebMail.UserName = FromOrSenderEmail;//EmailId used to send emails from application  
  23.           WebMail.Password = "YourGmailPassword";  
  24.           WebMail.From = FromOrSenderEmail; //email sender email address.  
  25.   
  26.           //Sending email  
  27.           WebMail.Send(to: ToEmail, subject: SubJect, body: Body, cc: cc, bcc: Bcc, isBodyHtml: true);  
  28.         <hr />  
  29.         <div class="text-success">  
  30.             Email Sent Successfully.  
  31.         </div>  
  32.       }  
  33.       catch (Exception)  
  34.       {  
  35.         <div class="text-danger">  
  36.             Problem while sending email, please check gmail server details.  
  37.         </div>  
  38.       }  

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 it will redirect to the SendEmailView invoked the WebEmail class and send the email , 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 using WebMail helper class in ASP.NET MVC Razor view .

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.
  • 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:

Up Next
    Ebook Download
    View all
    Learn
    View all