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 email 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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- namespace SendMailwithAttachment.Models
- {
- public class MailModel
- {
- 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.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Mail;
- using System.Web;
- using System.Web.Mvc;
- namespace SendMailwithAttachment.Controllers
- {
- public class SendMailerController : Controller
- {
-
-
- public ActionResult Index()
- {
- return View();
- }
-
-
-
-
-
-
- [HttpPost]
- public ActionResult Index(SendMailwithAttachment.Models.MailModel objModelMail, HttpPostedFileBase fileUploader)
- {
- if (ModelState.IsValid)
- {
- string from = "Your Gmail Id";
- using (MailMessage mail = new MailMessage(from, objModelMail.To))
- {
- mail.Subject = objModelMail.Subject;
- mail.Body = objModelMail.Body;
- if (fileUploader != null)
- {
- string fileName = Path.GetFileName(fileUploader.FileName);
- mail.Attachments.Add(new Attachment(fileUploader.InputStream, fileName));
- }
- mail.IsBodyHtml = false;
- SmtpClient smtp = new SmtpClient();
- smtp.Host = "smtp.gmail.com";
- smtp.EnableSsl = true;
- NetworkCredential networkCredential = new NetworkCredential(from, "Your Gmail Password");
- smtp.UseDefaultCredentials = true;
- smtp.Credentials = networkCredential;
- smtp.Port = 587;
- smtp.Send(mail);
- ViewBag.Message = "Sent";
- return View("Index", objModelMail);
- }
- }
- else
- {
- return View();
- }
- }
- }
- }
Index.cshtml
- @model SendMailwithAttachment.Models.MailModel
- @{
- ViewBag.Title = "Index";
- }
- <script src="~/Scripts/jquery-1.7.1.min.js"></script>
- <script>
- $(document).ready(function () {
- if ('@ViewBag.Message' == 'Sent') {
- alert('Mail has been sent successfully');
- }
- });
- </script>
- <h2>Index</h2>
- <fieldset>
- <legend>Send Email
- </legend>
- @using (@Html.BeginForm("Index", "SendMailer", FormMethod.Post, new { @id = "form1", @enctype = "multipart/form-data" }))
- {
- @Html.ValidationSummary()
- <input type="submit" value="Send" />
- <table>
- <tr>
- <td>To:
- </td>
- <td>
- @Html.TextBoxFor(m => m.To)
- </td>
- </tr>
- <tr>
- <td>Subject:
- </td>
- <td>
- @Html.TextBoxFor(m => m.Subject)
- </td>
- </tr>
- <tr>
- <td>Attachment
- </td>
- <td>
- <input type="file" name="fileUploader" />
- </td>
- </tr>
- <tr>
- <td>Body:
- </td>
- <td>
- @Html.TextAreaFor(m => m.Body)
- </td>
- </tr>
- </table>
- }
- </fieldset>
In the code above we have the following 4 fields:
- To
- Subject
- Message
- Attachment
When the user clicks the "Send" button, the mail will be sent to the specified mail address that you provide in the "To" TextBox.
That’s it. Press F5 to run your code.

Understanding the Code
In MVC, we can post our data in one of two ways. 1. Strongly typed 2. Ajax using jQuery
In the preceding example, we used the strongly typed solution, why? Because we have FileUploader. This fileupload needs an object HttpPostedFileBase, that gives you the FileName,Content Length, Content type properties of your selected files.
For posting attached file data from a View to a Controller, we need the following simple 3 steps.
Step 1: In every web based app we define a <form> tag, here we also define a <form> tag in razor style.
- @using (@Html.BeginForm("Index", "SendMailer", FormMethod.Post, new { @id = "form1", @enctype = "multipart/form-data" }))
As you have seen in the preceding line of code, here it is:
- @Html.BeginForm(“Action Method Name” , ”Controller Name”,Posting Method, new {@id=”form1”,@enctype=”multipart/form-data”}
Step 2: Define fileupload control
- <input type="file" name="fileUploader" />
Step 3:
- [HttpPost]
- public ActionResult Index(SendMailwithAttachment.Models.MailModel objModelMail, HttpPostedFileBase fileUploader)
In the code above:
- public ActionResult Index(SendMailwithAttachment.Models.MailModel objModelMail, HttpPostedFileBase fileUploader)
that uses a [httppost] action method. In this method, we have a parameter of our MailModel object and HttpPostedFileBase object.
Here remember one thing always.
In Step 2 you defined a fileupload control, here is the property name=”fileUploader”. So when you define an object of HttpPostedFileBase object variable, both names should be the same. In the code above name=”fileiploader” and in the ActionMethod HttpPostedFileBase fileUploader.
Now we create a MailMessage object.
- MailMessage mail = new MailMessage();
MailMessage is the main class for sending mail, this is the part of the System.Net.Mail namespace.
The MailMessage class has properties, the important ones are:
- To
- From
- Cc
- Bcc
- Subject
- Body
- Attachment
So we add our data into specified properties.
- string from = "Your Gmail Id";
- using (MailMessage mail = new MailMessage(from, objModelMail.To))
- {
- mail.Subject = objModelMail.Subject;
- mail.Body = objModelMail.Body;
- if (fileUploader != null)
- {
- string fileName = Path.GetFileName(fileUploader.FileName);
- mail.Attachments.Add(new Attachment(fileUploader.InputStream, fileName));
- }
- }
For sending mail we need a SMTP Server, so in ASP.Net we have the SmtpClient class, using that class object we set its properties for the SMTP settings.
- SmtpClient smtp = new SmtpClient();
The SMTPClient class has these basic properties:
- Host
- Port
- UseDefaultCredential
- Credentials
- EnableSsl
- Send
- smtp.Host = "smtp.gmail.com";
- smtp.EnableSsl = true;
- NetworkCredential networkCredential = new NetworkCredential(from, "Your Gmail Password");
- smtp.UseDefaultCredentials = true;
- smtp.Credentials = networkCredential;
- smtp.Port = 587;
Here in the code above:
- smtp.Host = "smtp.gmail.com";
This 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.
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 Crendentials 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, based on properties, your mail will be sent.
Mehmet eminPosted Oct 28, 2021, 7:28 AM
Hallo Sir, how can i post a file to backend via Jquery-Ajax and get that file using c# to add this file as an attachment for an e-mail? Can anyone help me?
-------Posted Nov 6, 2020, 4:14 AM
Very nice article sir thank you sir
Mark SmithPosted Oct 26, 2020, 4:40 PM
Thank you so much, this is the one example I have found that is clear and concise! Now I just need to extend this a little for multiple attachments.
archana kashidPosted Jul 13, 2020, 7:55 AM
Thanks sir, code is work ..successfully.
Hardik SharmaPosted Apr 18, 2020, 3:12 AM
Mail send but download file is corrupt.... please help
kasif ShaikhPosted Mar 26, 2019, 9:07 AM
How to make reset button to clear this form
shankar patelPosted Aug 20, 2018, 5:34 AM
How to send file in particular user are login in CRM project.
Starhack VickyPosted May 10, 2018, 7:14 AM
This code is working thank u sir
Starhack VickyPosted May 10, 2018, 7:04 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
Starhack VickyPosted May 10, 2018, 7:04 AM
Dear sir this code is not working in asp.net mvc and please help us
AttiePosted Oct 25, 2017, 12:49 PM
Good Day. Thanks for the Article. Can it be possible to automate the signature after writing in the BODY. "Instead of writing REGARDS SOURABH MISHRA" you then have a photo, initials and cell number by default ?
Md. NasirPosted Oct 24, 2017, 3:44 AM
Nice Article. Helpful, Thanks!
dhiraj kaushikPosted Aug 8, 2017, 2:25 AM
HTTP Error 405.0 - Method Not AllowedThe page you are looking for cannot be displayed because an invalid method (HTTP verb) is being used. PLS HELP
dhiraj kaushikPosted Aug 8, 2017, 2:24 AM
HTTP Error 405.0 - Method Not AllowedThe page you are looking for cannot be displayed because an invalid method (HTTP verb) is being used.
bestin SebastianPosted Mar 30, 2016, 1:59 AM
Its so much help full.Then how to set Outlook mail sending(ie..from Outlook)
kailas visapurePosted Nov 21, 2014, 8:06 AM
Good Keep It Up
Frane BloodriverPosted Sep 8, 2014, 1:38 PM
Hello, i get an exception saying the view "index"couldnt be found neither his master view. could you help me please?
Former memberPosted Apr 7, 2014, 4:44 AM
There is a .NET library for sending email message with attachments known as Aspose.Email for .NET, you can also do HTML formatting while sending email by using this library. Try it: http://www.aspose.com/.net/email-component.aspx
satyendra vatsPosted Dec 28, 2013, 4:54 AM
good i like it