In this article I will explain with an example, how to send
Email using
HTML Templates in
ASP.Net Core (.Net Core 8) Razor Pages.
Mail Server Settings in AppSettings.json file
The following Mail Server settings need to be saved in the
AppSettings.json file.
{
"Smtp": {
"Server": "smtp.gmail.com",
"Port": 587,
"EnableSsl": true,
"FromAddress": "sender@gmail.com",
"UserName": "sender@gmail.com",
"Password": "GMAILor2STEP-PASSWORD",
"DefaultCredentials": true
}
}
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.
<html>
<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 on ASPSnippets.<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.Net;
using System.Net.Mail;
Razor PageModel (Code-Behind)
The PageModel consists of the following Handler methods.
Handler method for handling GET operation
This Handler method is left empty as it is not required.
Handler method for handling POST operation
Inside this Handler method, the PopulateBody method is called.
Inside PopulateBody method, the path of the EmailTemplate file is read using HostingEnvironment interface.
Next, the contents of the
HTML Email Template file are read into a String variable using the StreamReader class.
Then, the placeholders will be replaced with their respective values and the replaced values are returned.
Next, SendHtmlFormattedEmail method is called.
The SendHtmlFormattedEmail method accepts email address (recepientEmail), Subject and Body parameters.
The Sender email address (from) is fetched from the
Smtp section of the
AppSettings.json file, the
Subject and
Body are set from the parameters.
Then, all these values are set into an object of the MailMessage class.
Finally, object of the
SmtpClient class is created and the settings of the Mail Server such as
Host,
Port,
Username and
Password are fetched from the Smtp section of the
AppSettings.json file and are set in respective properties of the
SmtpClient 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.
public class IndexModel : PageModel
{
private IWebHostEnvironment Environment { get; set; }
public IConfiguration Configuration { get; set; }
public IndexModel(IConfiguration _configuration, IWebHostEnvironment environment)
{
this.Configuration = _configuration;
this.Environment = environment;
}
public void OnGet()
{
}
public void OnPostSendEmail()
{
//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");
bool enableSsl = this.Configuration.GetValue<bool>("Smtp:EnableSsl");
bool defaultCredentials = this.Configuration.GetValue<bool>("Smtp:DefaultCredentials");
string name = "John";
string title = "ASP.Net Core 8 Razor Pages: Hello World Tutorial with Sample Program example";
string url = "https://www.aspsnippets.com/Articles/4385/ASPNet-Core-8-Razor-Pages-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 Razor Pages in ASP.Net Core 8.0 for the first time.";
string body = this.PopulateBody(name, title, url, description);
using (MailMessage mm = new MailMessage(fromAddress, "recepient@gmail.com"))
{
mm.Subject = "New article published!";
mm.Body = body;
mm.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = host;
smtp.EnableSsl = enableSsl;
NetworkCredential networkCred = new NetworkCredential(userName, password);
smtp.UseDefaultCredentials = defaultCredentials;
smtp.Credentials = networkCred;
smtp.Port = port;
smtp.Send(mm);
}
}
ViewData["Message"] = "Email sent.";
}
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;
}
}
Razor Page (HTML)
HTML Markup
Inside the Razor Page, the ASP.Net TagHelpers is inherited.
The HTML of Razor Page consists of:
Form - For sending Request.
The Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor
PageModel, the Handler method name is
OnPostSendEmail but here it will be specified as
SendEmail when calling from the Razor
HTML Page.
@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Send_Email_Template_Core_Razor.Pages.IndexModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post">
<input type="submit" value="Send" asp-page-handler="SendEmail" />
</form>
@if (ViewData["Message"] != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewData["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