In this article I will explain a simple tutorial with an example, how to send email in
ASP.Net MVC.
This example will illustrate how to send email in
ASP.Net MVC using
GMAIL SMTP server.
Mail Server Settings in Web.Config file
The following Mail Server settings need to be saved in the
Web.Config file.
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network
host="smtp.gmail.com"
port="587"
enableSsl="true"
defaultCredentials="true"/>
</smtp>
</mailSettings>
</system.net>
MailMessage Class Properties
Following are the required properties of the MailMessage class.
From – Sender’s email address.
To – Recipient(s) Email Address.
CC – Carbon Copies. (If any)
BCC – Blind Carbon Copies. (If any)
Subject – Subject of the Email.
Body – Body of the Email.
IsBodyHtml – Specify whether body contains text or HTML mark up.
Attachments – Attachments. (If any)
ReplyTo – ReplyTo Email address.
SMTP Class Properties
Following are the properties of the SMTP class.
Host – SMTP Server URL. (Gmail: smtp.gmail.com)
EnableSsl – Specify whether your host accepts SSL Connections. (Gmail: True)
UseDefaultCredentials – Set to True in order to allow authentication based on the Credentials of the Account used to send emails.
Credentials – Valid login credentials for the SMTP server. (Gmail: email address and password)
Port – Port Number of the SMTP server. (Gmail: 587)
Model
The Model class consists of the following properties.
public class EmailModel
{
public string To { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public List<HttpPostedFileBase> Attachments { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
Namespaces
You will need to import the following namespaces.
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Configuration;
using System.Net.Configuration;
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
Inside this Action method, the posted values are captured through the EmailModel class object. All the fetched values are set into an object of the MailMessage class.
Setting Body of Email
The Body of the email is Text (Non HTML) hence the IsBodyHtml property of MailMessage class is set to FALSE.
Attaching Files
A FOREACH loop is executed over the collection of the HttpPostedFileBase and added as Attachment to the MailMessage class object.
Sending Email
Then, an object of the
SmtpClient class is created and the values of
Host,
Port,
EnableSsl and
UseDefaultCredentials are fetched from the
SMTP section of the
Web.Config file and set to the respective properties of
SmtpClient class along with the Credentials.
Finally, the
Send method is executed which sends the
Email and a success message is set to a
ViewBag object.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(EmailModel model)
{
//Read SMTP section from Web.Config.
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
string host = smtpSection.Network.Host;
int port = smtpSection.Network.Port;
bool enableSsl = smtpSection.Network.EnableSsl;
bool defaultCredentials = smtpSection.Network.DefaultCredentials;
using (MailMessage mm = new MailMessage(model.Email, model.To))
{
mm.Subject = model.Subject;
mm.Body = model.Body;
mm.IsBodyHtml = false;
foreach (HttpPostedFileBase attachment in model.Attachments)
{
string fileName = Path.GetFileName(attachment.FileName);
mm.Attachments.Add(new Attachment(attachment.InputStream, fileName));
}
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = host;
smtp.Port = port;
smtp.EnableSsl = enableSsl;
smtp.UseDefaultCredentials = defaultCredentials;
NetworkCredential networkCred = new NetworkCredential(model.Email, model.Password);
smtp.Credentials = networkCred;
smtp.Send(mm);
}
}
ViewBag.Message = "Email sent.";
return View();
}
}
View
HTML Markup
Inside the View, in the very first line the EmailModel class is declared as model for the View.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
HtmlAttributes – This array allows to specify the additional Form Attributes. Here we need to specify enctype = “multipart/form-data” which is necessary for uploading files.
The Form consists of HTML TextBox, TextArea, FileUpload elements and a Submit Button. The FileUpload element has been assigned with multiple attribute which is required for selecting multiple files.
Note: For more details in creating HTML TextBox, TextArea, FileUpload element in ASP.Net MVC, please refer following articles.
When the Submit Button is clicked, the Form gets submitted and the Model object is sent to the Controller.
Finally, the
ViewBag object is checked for NULL and if it is not NULL then the value of the object is displayed using
JavaScript Alert Message Box.
@model Send_Email_Attachment_MVC.Models.EmailModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width:80px">To:</td>
<td>@Html.TextBoxFor(m => m.To)</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Subject:</td>
<td>@Html.TextBoxFor(m => m.Subject)</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td valign="top">Body:</td>
<td>@Html.TextAreaFor(m => m.Body, new { @rows = 10, @cols = 50 })</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>File Attachment:</td>
<td><input type="file" name="Attachments" multiple="multiple" /></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Gmail Email:</td>
<td>@Html.TextBoxFor(m => m.Email)</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Gmail Password:</td>
<td>@Html.PasswordFor(m => m.Password)</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Send" /></td>
</tr>
</table>
}
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewBag.Message");
};
</script>
}
</body>
</html>
Screenshots
Email Form
Received Email
Downloads