Introduction
Sending email is a very common task in any web application for many purposes. In daily development we need to add some mail functionality to our project to send e-mail to the customer or another in our web site.
Using the code
For sending mail from ASP.NET MVC we use the "System.Net.Mail" namespace. Let's see how to do this.
- Open Visual Studio
- "File" -> "New" -> "Project..."
- Choose Visual C#- Web then select ASP.NET MVC4 Web Application
- Add a new Internet Application then click OK
Step 1
Create a new Model Class in the model folder.
The following is the code for the new Model.
MailModel.cs
- public class MailModel {
- public string From {
- get;
- set;
- }
- public string To {
- get;
- set;
- }
- public string Subject {
- get;
- set;
- }
- public string Body {
- get;
- set;
- }
- }
Step 2
Create a New SendMailerController in the Controller folder.
The following is the code for the design of the new Controller.
SendMailerController.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Mail;
- using System.Web;
- using System.Web.Mvc;
- namespace SendMail.Controllers {
- public class SendMailerController: Controller {
-
-
- public ActionResult Index() {
- return View();
- }
- [HttpPost]
- public ViewResult Index(SendMail.Models.MailModel _objModelMail) {
- if (ModelState.IsValid) {
- MailMessage mail = new MailMessage();
- mail.To.Add(_objModelMail.To);
- mail.From = new MailAddress(_objModelMail.From);
- mail.Subject = _objModelMail.Subject;
- string Body = _objModelMail.Body;
- mail.Body = Body;
- mail.IsBodyHtml = true;
- SmtpClient smtp = new SmtpClient();
- smtp.Host = "smtp.gmail.com";
- smtp.Port = 587;
- smtp.UseDefaultCredentials = false;
- smtp.Credentials = new System.Net.NetworkCredential("username", "password");
- smtp.EnableSsl = true;
- smtp.Send(mail);
- return View("Index", _objModelMail);
- } else {
- return View();
- }
- }
- }
- }
Index.cshtml
- @model SendMail.Models.MailModel
- @{
- ViewBag.Title = "Index";
- }
- <h2>Index</h2>
- <fieldset>
- <legend>
- Send Email
- </legend>
- @using (Html.BeginForm())
- {
- @Html.ValidationSummary()
- <p>From: </p>
- <p>@Html.TextBoxFor(m=>m.From)</p>
- <p>To: </p>
- <p>@Html.TextBoxFor(m=>m.To)</p>
- <p>Subject: </p>
- <p>@Html.TextBoxFor(m=>m.Subject)</p>
- <p>Body: </p>
- <p>@Html.TextAreaFor(m=>m.Body)</p>
- <input type ="submit" value ="Send" />
- } </fieldset>
In the code above we have the following 3 fields:
When the user clicks the "Send" button, the mail will be sent to the specified mail address that you provide in the To TextBox. So add the following code for the [HttpPost] Method for the send button click.
SendMailerController.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Mail;
- using System.Web;
- using System.Web.Mvc;
- namespace SendMail.Controllers {
- public class SendMailerController: Controller {
-
-
- public ActionResult Index() {
- return View();
- }
- [HttpPost]
- public ViewResult Index(SendMail.Models.MailModel _objModelMail) {
- if (ModelState.IsValid) {
- MailMessage mail = new MailMessage();
- mail.To.Add(_objModelMail.To);
- mail.From = new MailAddress(_objModelMail.From);
- mail.Subject = _objModelMail.Subject;
- string Body = _objModelMail.Body;
- mail.Body = Body;
- mail.IsBodyHtml = true;
- SmtpClient smtp = new SmtpClient();
- smtp.Host = "smtp.gmail.com";
- smtp.Port = 587;
- smtp.UseDefaultCredentials = false;
- smtp.Credentials = new System.Net.NetworkCredential("username", "password");
- smtp.EnableSsl = true;
- smtp.Send(mail);
- return View("Index", _objModelMail);
- } else {
- return View();
- }
- }
- }
- }
Understanding the Code
In the code above we have a,
- ViewResult Index(SendMail.Models.MailModel _objModelMail)
user defined method. In this method, we have a parameter of our MailModel object. Now we create a MailMessage object.
- MailMessage mail = new MailMessage();
MailMessage is the main class for sending mail, it is in the System.Net.Mail namespace.
The MailMessage class has properties, the important ones are:
- To
- From
- Cc
- Bcc
- Subject
- Body
So we add our data into specified properties.
- mail.To.Add(_objModelMail.To);
-
- mail.From = new MailAddress(_objModelMail.From);
- mail.Subject = _objModelMail.Subject;
- string Body = _objModelMail.Body;
- mail.Body = Body;
For sending mail we need a SMTP Server, so in ASP.Net we have the SmtpClient class, we set the SMTP settings using the properties of that class.
- SmtpClient smtp = new SmtpClient();
The SMTPClient class has these basic properties:
- Host
- Port
- UseDefaultCredential
- Credentials
- EnableSsl
- Send
- smtp.Host = "smtp.gmail.com";
- smtp.Port = 587;
- smtp.UseDefaultCredentials = false;
- smtp.Credentials = new System.Net.NetworkCredential("username", "password");
- smtp.EnableSsl = true;
In the code above is,
- smtp.Host = "smtp.gmail.com";
That is the SMTP Host address of Gmail, if you want to use any other SMTP host service then please add a different SMTP host protocol, for example for Hotmail it is smtp.live.com.
For example, in,
Smtp.Port=587
587 is the port for Gmail, so for any other service port you need to change the port correspondingly.
- smtp.Credentials = new System.Net.NetworkCredential("username", "password");
Smtp.Credentials specifies the Network Credentials of your Gmail id so please add your username and password instead of ("username", "password");
The following is for a secure mail server, so you enable your SSL layer.
Smtp.Send sends the mail so please add your MailMesssage object here. Then, based on the properties, your mail will be sent.
Mahdieh FarzinPosted Dec 5, 2022, 9:06 AM
Thanks for your code, but I face this error " The server response was: 5.7.0 Authentication Required." wouldyou please help me?
Melissa Garro ValverdePosted Mar 23, 2021, 4:32 PM
Thank you very much, it worked perfectly!
Jack LakesPosted Jun 19, 2019, 7:45 PM
How do you add an attachment to the email?
Arti RathodPosted Oct 23, 2018, 5:48 AM
How to clear out fields after submission??
Arti RathodPosted Oct 19, 2018, 8:23 AM
How can insert message on mvc after email has been sent?? can any one please help me??
prasad uplenchwarPosted Nov 24, 2017, 11:42 AM
Smtp.send(msg) is entpException was unhandle by user Code
Jamil HallalPosted Aug 12, 2016, 5:01 PM
Try this free email delivery service:http://zender.sharptag.com First of all you need to get new API Key by registering & confirming your email in Zender In your Visual Studio project, Install the package from Nuget. This package will add a reference to Zender.Mail in your .NET application. Zender.Mail is the client library that is built to consume Zender Web API (Alternatively, you can also download and add the Zender.Mail.dll (1.0.0.0) reference manually): PM> install-package Zender.Mail The code to send a new email: ZenderMessage message = new ZenderMessage("Your zender API Key"); MailAddress from = new MailAddress("[email protected]"); MailAddress to = new MailAddress("[email protected]"); message.From = from; message.To.Add(to); message.Subject = "Welcome!"; message.Body = "<p><b>Lorem ipsum</b> dolor sit amet, consectetur adipiscing elit.</p>"; message.IsBodyHtml = true; message.SendMailAsync();
Hugh SPosted Jun 16, 2016, 12:19 PM
Hi Sourabh - will you have a tutorial for Word Mail Merge from MVC View soon?
Dr.Ajay KashyapPosted Jun 12, 2016, 10:22 AM
i use your code in my application for email...but it show The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required error
Rama chandranPosted May 7, 2016, 2:14 AM
which username and password will be put??
Rama chandranPosted May 7, 2016, 2:12 AM
//smtp.Credentials = new System.Net.NetworkCredential("username", "password");
Victor UsoroPosted Jan 21, 2016, 4:50 PM
This is great, please how can i send bulk sms from my mvc 4 app also
Kamlesh TiwariPosted Oct 28, 2015, 10:27 AM
Nice Artical Sourabh
Ajeet MishraPosted Sep 18, 2015, 7:28 AM
nice
Jomer MercadoPosted Jun 2, 2015, 12:20 PM
hi i do not use yahoo or gmail or hotmail, i use a hosting site with ssl. how can i make this work? it sayas i need a secured connection...
Al MorrisPosted Apr 5, 2015, 7:02 AM
Thank you! Works great for me.
Chirag GardhariyaPosted Oct 9, 2014, 3:29 AM
Hi, In local host it works fine. But when I upload the code to the server, it gives me this error "An error occurred while processing your request." I don't the details of the error.
Sajid AliPosted Sep 12, 2014, 2:18 AM
im using this code but this give an error -The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required please solve this error.
Former memberPosted Apr 7, 2014, 4:22 AM
You can send email messages with HTML formatting and attachment by using Aspose.Email for .NET Library. Try it: http://www.aspose.com/.net/email-component.aspx
Anubhav ChaudharyPosted Feb 21, 2014, 2:22 AM
Also if you are using this application on your Local Server then change the port from "587" to "25".
Anubhav ChaudharyPosted Feb 21, 2014, 2:20 AM
Hey Shaik, you are getting that error because the mail Id you are using is not authenticated by the Gmail(Google) or you are not using the Gmail Id, if you are using the Yahoo Id then SMTPClient will be "smtp.mail.yahoo.com" and if you are using Hotmail account then SMTPClient will be "smtp.live.com".
shaik layeeqPosted Feb 21, 2014, 1:49 AM
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
shaik layeeqPosted Feb 21, 2014, 1:49 AM
------------------------------------------------------------------------------------------The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
shaik layeeqPosted Feb 21, 2014, 1:49 AM
hello i am getting this error
Dev DevPosted Feb 2, 2014, 2:56 PM
Hi Sourabh,I tried your instructions and it has worked well, thank you. I was wondering though, isn’t it a security risk to have the credentials hardcoded into the source code, considering that the code can be inspected using disassemblers? Dev
Larry OslundPosted Jan 9, 2014, 2:17 PM
Here is my error:Error 1 The type or namespace name 'Models' does not exist in the namespace 'SendMail' (are you missing an assembly reference?) \\nc\z\users\larry.oslund\documents\visual studio 2013\Projects\Emailer1\Emailer1\Controllers\SendMailController.cs 19 42 Emailer1
Larry OslundPosted Jan 9, 2014, 2:17 PM
I am trying to code and run your example. I am using VS2013, and am getting this error: