In this article I will explain with an example, how to send emails using SMTP Server in ASP.Net MVC.
This article will make use of GMAIL SMTP Server for sending emails in ASP.Net MVC.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 
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>
 
 
Model
Following is a Model class named EmailModel with the following properties.
public class EmailModel
{
    public string To { get; set; }
    public string Subject { get; set; }
    public string Body { get; set; }
    public HttpPostedFileBase Attachment { 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
This Action method handles the call made from the POST function from the View.
 
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).
 
When Send button is clicked, the posted values from their respective fields are captured through the EmailModel class object and are set into an object of MailMessage class.
Note: For more details on how to use Model class object for capturing Form field values, please refer my article ASP.Net MVC: Form Submit (Post) example.
 
If the HttpPostedFileBase has attachment then, the attachment is added to the Attachments List of the MailMessage Object.
Then, object of the SmtpClient class is created and the settings of the Mail Server such as Host, Port, DefaultCredentials and EnableSsl are fetched from the mailSettings section of the Web.Config file and are set in respective properties of the SmtpClient class object.
And Username and Password values are passed as parameter to NetworkCredential class using EmailModel class object.
Note: It is necessary to use the sender’s email address credentials while defining the Gmail SMTP Server Credentials as Gmail the sender’s email address must be same as the Gmail Username specified in credentials.
 
Finally, the email is sent using the Send function of the SmtpClient class object 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");
        using (MailMessage mm = new MailMessage(model.Email, model.To))
        {
            mm.Subject = model.Subject;
            mm.Body = model.Body;
            if (model.Attachment != null)
            {
                string fileName = Path.GetFileName(model.Attachment.FileName);
                mm.Attachments.Add(new Attachment(model.Attachment.InputStream, fileName));
            }
            mm.IsBodyHtml = false;
            using (SmtpClient smtp = new SmtpClient())
            {
                smtp.Host = smtpSection.Network.Host;
                smtp.EnableSsl = smtpSection.Network.EnableSsl;
                NetworkCredential networkCred = new NetworkCredential(model.Email, model.Password);
                smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials;
                smtp.Credentials = networkCred;
                smtp.Port = smtpSection.Network.Port;
                smtp.Send(mm);
 
            }
            ViewBag.Message = "Email Sent.";
            return View();
        }
    }       
}
 
 
View
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.
ActionNameName 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.
Inside the Form there is an HTML Table which consists of some TextBoxes created using the Html.TextBoxFor method in which one TextBox type is set to file.
The Table also consists of a TextArea created using Html.TextAreaFor method and a Submit button.
When the Submit Button is clicked, the Form gets submitted and the Model object is sent to the Controller.
@model Send_Email_MVC.Models.EmailModel
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        @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(model => model.To)</td>
                </tr>
                <tr>
                    <td>Subject:</td>
                    <td>@Html.TextBoxFor(model => model.Subject)</td>
                </tr>
                <tr>
                    <td valign="top">Body:</td>
                    <td>@Html.TextAreaFor(model => model.Body, new { rows = "3", cols = "20" })</td>
                </tr>
                <tr>
                    <td>File Attachment:</td>
                    <td>@Html.TextBoxFor(model => model.Attachment, new { type = "file" })</td>
                </tr>
                <tr>
                    <td>Gmail Email:</td>
                    <td>@Html.TextBoxFor(model => model.Email)</td>
                </tr>
                <tr>
                    <td>Gmail Password:</td>
                    <td>@Html.TextBoxFor(model => model.Password, new { type = "password" })</td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" value="Send" /></td>
                </tr>
            </table>
            <br/>
            <span style="color:green">@ViewBag.Message</span>
        }
    </div>
</body>
</html>
 
 
Possible Errors
The following error occurs when you try to send email using Gmail credentials in your application.
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
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.Mail.SmtpException: 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
 
Solution
 
 
Screenshots
Email Form
Send Email using SMTP Server in ASP.Net MVC
 
Received Email
Send Email using SMTP Server in ASP.Net MVC
 
 
Downloads