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:
- "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
- "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:
- using System.ComponentModel.DataAnnotations;
-
- namespace SendingEmailsFromController.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 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
- using SendingEmailsFromController.Models;
- using System;
- using System.Web.Helpers;
- using System.Web.Mvc;
-
- namespace SendingEmailsFromController.Controllers
- {
- public class HomeController : Controller
- {
-
- public ActionResult SendEmail()
- {
-
- return View();
- }
-
- [HttpPost]
- public ActionResult SendEmail(EmployeeModel obj)
- {
-
- try
- {
-
-
- WebMail.SmtpServer = "smtp.gmail.com";
-
- WebMail.SmtpPort = 587;
- WebMail.SmtpUseDefaultCredentials = true;
-
- WebMail.EnableSsl = true;
-
- WebMail.UserName = "[email protected]";
- WebMail.Password = "YourGmailPassword";
-
-
- WebMail.From = "[email protected]";
-
-
- WebMail.Send(to: obj.ToEmail, subject: obj.EmailSubject, body: obj.EMailBody, cc: obj.EmailCC, bcc: obj.EmailBCC, isBodyHtml: true);
- ViewBag.Status = "Email Sent Successfully.";
- }
- catch (Exception)
- {
- ViewBag.Status = "Problem while sending email, Please check details.";
-
- }
- return View();
- }
- }
- }
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
- @model SendingEmailsFromController.Models.EmployeeModel
-
- @{
- ViewBag.Title = "www.compilemode.com";
- }
- @using (Html.BeginForm())
- {
- @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-primary" />
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10 text-success">
- @ViewBag.Status
- </div>
- </div>
- </div>
-
- }
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: