In this article I will explain with an example, how to Send
Email using
HTML Templates in ASP.Net MVC.
Mail Server Settings in Web.Config file
The following Mail Server settings need to be saved in the
Web.Config file.
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.
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="sender@gmail.com">
<network
host="smtp.gmail.com"
port="587"
enableSsl="true"
userName="sender@gmail.com"
password="SenderGmailPassword"
defaultCredentials="true"/>
</smtp>
</mailSettings>
</system.net>
Adding Email Template
The very first step is to Right Click the Project in the Solution Explorer and click Add and then New Item and then select HTML Page and name it as EmailTemplate.htm.
Location of the EmailTemplate
The Email Template is placed inside the Template Folder (Directory) in Project Folder.
Building HTML Template for Email Body
The
HTML Template of the Email will be built by generating an
HTML containing some placeholders which will be replaced with the actual content.
Advantage of creating templates instead of building
HTML using
String Builder class or
String concatenation in code is that, one can easily change the
HTML of the template without changing the code.
The following
HTML Email Template consists of four placeholders:
{UserName} – Name of the recipient.
{Url} – Url of the article.
{Title} – Title of the article.
{Description} – Description of the Article.
These placeholders will be replaced with the actual (real) values, when the email is being sent.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<img style="background:black;" src="https://www.aspsnippets.com/assets/img/logo_ns.png" /><br /><br />
<div style="border-top:3px solid #61028D"> </div>
<span style="font-family:Arial;font-size:10pt">
Hello<b>{UserName}</b>, <br /><br />
A new article has been published onASPSnippets.<br /><br />
<a style="color:#61028D" href="{Url}">{Title}</a><br />
{Description}
<br /><br />
Thanks<br />
ASPSnippets
</span>
</body>
</html>
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 the 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
PopulateBody method is called and the contents of the
HTML Email Template file are read using the
StreamReader class.
The placeholders are replaced with their respective values and finally the contents of the
HTML Email Template are returned.
Next, the formatted
HTML body, email address (recepientEmail) and Subject are set into the respective properties of the object of
MimeMessage class.
Setting Body of Email
For Body, an object of Builder class is created. The Body of the email is Text (Non HTML) hence it is set into the TextBody property of the Builder class object.
Sending Email
Then, object of the
SmtpClient class is created and the settings of the Mail Server such has
Host,
Port,
EnableSsl,
Username,
Password,
Sender email address (from) and
DefaultCredentials are fetched from the
mailSettings section of the
Web.Config file and are set in respective properties of the
SmtpClient class object.
And, the email is being sent using
Send method of the
SmtpClient class and success message is set to a
ViewBag object.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult SendEmail()
{
string userName = "John";
string title = "ASP.Net MVC Hello World Tutorial with Sample Program example";
string url = "https://www.aspsnippets.com/Articles/1620/ASPNet-MVC-Hello-World-Tutorial-with-Sample-Program-example/";
string description = "Here Mudassar Khan has explained with an example, how to use and develop applications in ASP.Net MVC for the first time.";
string body = this.PopulateBody(userName, title, url, description);
//Read SMTP section from Web.Config.
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
using (MailMessage mm = new MailMessage(smtpSection.From, "recepient@gmail.com"))
{
mm.Subject = "New article published!";
mm.Body = body;
mm.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = smtpSection.Network.Host;
smtp.EnableSsl = smtpSection.Network.EnableSsl;
NetworkCredential networkCred = new NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials;
smtp.Credentials = networkCred;
smtp.Port = smtpSection.Network.Port;
smtp.Send(mm);
}
}
return View("Index");
}
private string PopulateBody(string userName, string title, string url, string description)
{
string body = string.Empty;
using (StreamReader reader = new StreamReader(Server.MapPath("~/Template/EmailTemplate.html")))
{
body = reader.ReadToEnd();
}
body = body.Replace("{UserName}",userName);
body = body.Replace("{Title}", title);
body = body.Replace("{Url}", url);
body = body.Replace("{Description}", description);
return body;
}
}
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 SendEmail.
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
HTML Form, there is a
Submit Button, which when clicked the form is submitted.
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.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("SendEmail", "Home", FormMethod.Post))
{
<input type="submit" value="Send" />
}
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewBag.Message");
};
</script>
}
</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
Screenshot
Downloads