In this article I will explain with an example, how to send HTML formatted email using HTML Templates using
MailKit in ASP.Net Core MVC (.Net Core).
Installing MailKit package
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 wwwroot Folder (Directory).
Mail Server Settings in AppSettings.json file
The mail server settings are saved in the SMTP section as shown below.
{
"Smtp": {
"Server": "smtp.gmail.com",
"Port": 587,
"FromAddress": "sender@gmail.com",
"UserName": "sender@gmail.com",
"Password": "GMAILor2STEP-PASSWORD"
}
}
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.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<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 on ASPSnippets.<br /><br />
<a style="color:#61028D" href="{Url}">{Title}</a><br />
{Description}
<br /><br />
Thanks<br />
ASPSnippets
</span>
</body>
</html>
MimeKit MimeMessage and MailKit SmtpClient class
MimeMessage class properties
Following are the required properties of the MimeMessage 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.
Attachments – Attachments. (If any)
ReplyTo – ReplyTo Email address.
SmtpClient class methods
Following are the methods of the SmtpClient class.
Connect – The connection to the SMTP Server is established using the domain and the port number.
Authenticate – The username and password of the SMTP Server is authenticated.
Send – The MimeMessage object is passed to it and the email is sent.
Disconnect – Disconnects the connection with SMTP Server.
Namespaces
You will need to import the following namespaces.
using MimeKit;
using MailKit.Net.Smtp;
using MailKit.Security;
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, first the values of Host, Port, UserName, Password and Sender email address (from) fetched from the SMTP section of the AppSettings.json file.
Then, PopulateBody method is called and title, url, userName and description are passed as parameter to it.
PopulateBody
Inside the PopulateBody method, the path of the EmailTemplate file is read using IWebHostEnvironment interface.
Next, the contents of the HTML Email Template file are read into a String variable using the StreamReader class.
The placeholders are replaced with their respective values and content of the Template is returned as Body.
Then, all these values are set into the respective properties of an object of the MimeMessage class except Body.
Setting Body of Email
For Body, an object of Builder class is created. The Body of the email is HTML hence it is set into the HtmlBody property of the Builder class object.
Sending Email
Then, an object of the SmtpClient class is created and the values of Host and Port fetched from the SMTP section of the AppSettings.json file are passed as parameter to Connect method along with the SecureSocketOptions set to Auto.
Note: Setting
Auto allows
MailKit service to decide which
SSL or
TLS option to use. Hence, enabling
SSL is not required.
Also, the CheckCertificateRevocation is set to FALSE.
Note: This is optional and must be used only when Certificate errors are occurring.
Finally, the methods of the Mail Server such as
Connect,
Authenticate,
Send and
Disconnect are executed and a success message is set to a
ViewBag object.
public class HomeController : Controller
{
private IWebHostEnvironment Environment { get; set; }
public IConfiguration Configuration { get; set; }
public HomeController(IConfiguration _configuration, IWebHostEnvironment environment)
{
this.Configuration = _configuration;
this.Environment = environment;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult SendEmail()
{
//Read SMTP section from AppSettings.json.
string host = this.Configuration.GetValue<string>("Smtp:Server");
int port = this.Configuration.GetValue<int>("Smtp:Port");
string fromAddress = this.Configuration.GetValue<string>("Smtp:FromAddress");
string userName = this.Configuration.GetValue<string>("Smtp:UserName");
string password = this.Configuration.GetValue<string>("Smtp:Password");
string title = "ASP.Net Core 7: Hello World Tutorial with Sample Program example";
string url = "https://www.aspsnippets.com/Articles/4264/ASPNet-Core-7-Hello-World-Tutorial-with-Sample-Program-example/";
string description = "Here Mudassar Khan has provided a short Hello World Tutorial using a small Sample Program example on how to use and develop applications in ASP.Net MVC Core 7.0 for the first time.";
string body = this.PopulateBody("John", title, url, description);
using (MimeMessage mm = new MimeMessage())
{
mm.From.Add(new MailboxAddress("Sender", fromAddress));
mm.To.Add(new MailboxAddress("Recepient", "recepient@gmail.com"));
mm.Subject = "New article published!";
BodyBuilder builder = new BodyBuilder()
{
HtmlBody = body
};
mm.Body = builder.ToMessageBody();
using (SmtpClient smtp = new SmtpClient())
{
//Set to False to avoid Certificate verification
smtp.CheckCertificateRevocation = false;
smtp.Connect(host, port, SecureSocketOptions.Auto);
smtp.Authenticate(userName, password);
smtp.Send(mm);
smtp.Disconnect(true);
}
}
ViewBag.Message = "Email Sent.";
return View("Index");
}
private string PopulateBody(string userName, string title, string url, string description)
{
string body = string.Empty;
string path = Path.Combine(this.Environment.WebRootPath, "Template\\EmailTemplate.htm");
using (StreamReader reader = new StreamReader(path))
{
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
HTML Markup
The View consists of an HTML Form which has been created using the following TagHelpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – 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.
Submitting the Form
When the
Submit Button is clicked then, the
ViewBag object named Message is checked for NULL and if it is not NULL then the value of the object is displayed using
JavaScript Alert
MessageBox.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-controller="Home" asp-action="SendEmail">
<input type="submit" value="Send" />
</form>
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewBag.Message");
};
</script>
}
</body>
</html>
Possible Errors
The possible errors (exceptions) occurring while sending email with
MailKit in .Net are covered in the following article.
Screenshot
Downloads