Sending Emails In ASP.NET MVC From Controller Using WebMail Helper
Email communication is very important in today's modern applications and there are many ways to send emails through applications to users.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 which is used to send emails directly from Razor view as well controller class in ASP.NET MVC.
ASP.NET WebMail is a class, that works with the email stuff on your website. This class is a helper class, which as MSDN says, "is a component that simplifies web programming in ASP.NET Web Pages". It is a part of .NET Framework's Web Helpers class. You can access this class in many ways, if you're having a .cshtml page (the C# embedded HTML page) where all the classes and namespaces required are compiled within or you can also use this class using its direct class name and access it inside any .cs (C# Class) file.
System.Web.Helpers.WebMail;
This would enable this WebMail feature in your website. After this, you can easily access its properties and methods in your code and send the WebMail (email) from your website or your program software.
Like all other classes, WebMail also has some methods and properties that you can use and customize your service. The built-in members (properites) of the WebMail class are as follows:
One thing I want to make clear here. There is a difference between
From
and UserName
field. The difference is, UserName
is used to connect to the server, whereas From
field is just passed as a String
to the server to tell the From
field only. UserName
and Password
are used to login to the server, they're the same that were provided to you while signing up. For example, my Gmail account is: justinxxxxx@gmail.com password ******, I would pass this to the UserName
and Password
fields and the From
field can be my brother's email too or my company email, etc.
Do keep the above stated paragraph in mind!
Now let's talk about the methods provided by the
WebMail
class, as we know this is an email related class so there is only one method provided by it. It is:public static void Send(
string to,
string subject,
string body,
string from,
string cc,
IEnumerable<string> filesToAttach,
bool isBodyHtml,
IEnumerable<string> additionalHeaders,
string bcc,
string contentEncoding,
string headerEncoding,
string priority,
string replyTo
)
Send
method which is used to send the email. You don't need to configure this class or the instance you create like you did in the MailMessage
you just pass the parameters and WebMail handles it all.
The only required parameters would be discussed here, remaining are just optional. Whether you provide them or not,
WebMail
doesn't care about it. One more thing, and it is the most interesting is that you don't need to keep the sequence in mind. You can pass them in any order, just remember to pass the first three parameters in order. Since they're required.to
string
)
This is the email address of the receiver.subject
(string
)
The subject for the email being sent. A short message to describe the email.body
(string
)
This is the parameter that has all of the email body content. You pass the entire HTML that would form the email body of the web mail in this parameter. You can attach images to the document you can stylize the HTML content using the HTML codes for bold, italic, etc.isBodyHtml
bool
)
Used to indicate that the HTML inside the body parameter should be rendered as an HTML markup instead of plainstring
.
The remaining parameters are not as much required and the email would be sent using just these parameters. Even though the
isBodyHtml
parameter was also not required one, but I thought it was worth mentioning.
U Can Send Mail Using the Following Code
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".
- Go to File->New Project->ASP.NET Web Application , then provide the Project a name as you wish and click OK. After clicking, the following window will appear:
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 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 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 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();
- }
- }
- }
tep 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
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>
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 we have done all coding to send emails using WebMail class .
Step 5 : Now run the application.
Mind blowing sir...
ReplyDeleteNice
ReplyDeleteEverything Defined well....great blog
ReplyDeleteVery well sir......nice blog
ReplyDeleteBahut achha hai
Good explanation, it is easy to understand---great blog .Thank You Master.
ReplyDeleteHello sir,
ReplyDeleteThis blog is really great, thank you so much for sharing your knowledge.
nice blogs sir
ReplyDeletevery helpful and interesting blog.. easiest to learn. thank you sir
ReplyDelete