In this article I will explain with an example, how to send Email using HTML Templates in ASP.Net with C# and VB.Net.
HTML Template is nothing but an HTML File whose contents will be read, modified and sent as Email.
HTML Templates are used to send newsletters and promotional emails. Such emails contain Rich Text content, images and animations.
 
 
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.
Send Email using HTML Templates in ASP.Net with C# and VB.Net
 
 
Location of the EmailTemplate
The EmailTemplate is placed inside the Template Folder (Directory) in Project Folder.
Send Email using HTML Templates in ASP.Net with C# and VB.Net
 
 
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">&nbsp;</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>
 
 
HTML Markup
The following HTML Markup consists of an ASP.Net Button control.
The Button has been assigned with an OnClick event handler.
<asp:Button ID="btnSend" runat="server" Text="Send" OnClick="SendEmail" />
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Configuration;
 
VB.Net
Imports System.Configuration
Imports System.IO
Imports System.Net
Imports System.Net.Mail
Imports System.Net.Configuration
 
 
Sending the Formatted HTML email
When the Send Button is clicked, following event handler is executed.
Inside this event handler, the PopulateBody method is called.
Inside the PopulateBody method, the Body of the email is generated.
Next, the formatted HTML body is passed as parameter to the SendHtmlFormattedEmail method along with recipient’s email address and the subject.
C#
protected void SendEmail(object sender, EventArgs e)
{
    string body = this.PopulateBody("John",
        "Fetch multiple values as Key Value pair in ASP.Net AJAX AutoCompleteExtender",
        "https://www.aspsnippets.com/Articles/Fetch-multiple-values-as-Key-Value-pair-in-ASP.Net-AJAX-AutoCompleteExtender.aspx",
        "Here Mudassar Khan has explained with an example, how to fetch multiple column values i.e." +
        " ID and Text values in the ASP.Net AJAX Control Toolkit AutocompleteExtender" +
        " and also how to fetch the select text and value server side on postback.");
    this.SendHtmlFormattedEmail("recepient@gmail.com", "New article published!", body);
}
 
VB.Net
Protected Sub SendEmail(sender As Object, e As EventArgs)
    Dim body As String = Me.PopulateBody("John",
        "Fetch multiple values as Key Value pair in ASP.Net AJAX AutoCompleteExtender",
        "https://www.aspsnippets.com/Articles/Fetch-multiple-values-as-Key-Value-pair-in-ASP.Net-AJAX-AutoCompleteExtender.aspx",
        "Here Mudassar Khan has explained with an example, how to fetch multiple column values i.e." &
        " ID and Text values in the ASP.Net AJAX Control Toolkit AutocompleteExtender" &
        " and also how to fetch the select text and value server side on postback.")
    Me.SendHtmlFormattedEmail("recepient@gmail.com", "New article published!", body)
End Sub
 
 
Populating the HTML Formatted Body
Inside the PopulateBody method, 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.
Finally, the replaced values are returned.
C#
private string PopulateBody(string userName, string title, string url, string description)
{
    string body = string.Empty;
    using (StreamReader reader = new StreamReader(Server.MapPath("~/Template/EmailTemplate.htm")))
    {
        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;
}
 
VB.Net
Private Function PopulateBody(userName As String, title As String, url As String, description As String) As String
    Dim body As String = String.Empty
    Using reader As StreamReader = New StreamReader(Server.MapPath("~/Template/EmailTemplate.htm"))
        body = reader.ReadToEnd()
    End Using
    body = body.Replace("{UserName}", userName)
    body = body.Replace("{Title}", title)
    body = body.Replace("{Url}", url)
    body = body.Replace("{Description}", description)
    Return body
End Function
 
 
Send Email Method
The SendHtmlFormattedEmail method accepts email address (recepientEmail), Subject and Body parameters.
The Sender email address (from) is fetched from the SmtpSection of the Web.Config file.
Then, object of the SmtpClient class is created and the settings of the Mail Server such has Host, Port, EnableSsl, Username and Password are fetched from the mailSettings section of the Web.Config 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.
 
Finally, the email is being sent.
C#
private void SendHtmlFormattedEmail(string recepientEmail, string subject, string body)
{
    //Read SMTP section from Web.Config.
    SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
 
    using (MailMessage mm = new MailMessage(smtpSection.From, recepientEmail))
    {
        mm.Subject = subject;
        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 = true;
            smtp.Credentials = networkCred;
            smtp.Port = smtpSection.Network.Port;
            smtp.Send(mm);
        }
    }
}
 
VB.Net
Private Sub SendHtmlFormattedEmail(recepientEmail As String, subject As String, body As String)
    'Read SMTP section from Web.Config.
    Dim smtpSection As SmtpSection = CType(ConfigurationManager.GetSection("system.net/mailSettings/smtp"), SmtpSection)
    Using mm As MailMessage = New MailMessage(smtpSection.From, recepientEmail)
        mm.Subject = subject
        mm.Body = body
        mm.IsBodyHtml = True
        Using smtp As SmtpClient = New SmtpClient()
            smtp.Host = smtpSection.Network.Host
            smtp.EnableSsl = smtpSection.Network.EnableSsl
            Dim networkCred As NetworkCredential = New NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password)
            smtp.UseDefaultCredentials = True
            smtp.Credentials = networkCred
            smtp.Port = smtpSection.Network.Port
            smtp.Send(mm)
        End Using
    End Using
End Sub
 
 
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" from="sender@gmail.com">
            <network
                host="smtp.gmail.com"
                port="587"
                enableSsl="true"
                userName="sender@gmail.com"
                password="GMAILor2STEP-PASSWORD"
                defaultCredentials="true" />
        </smtp>
    </mailSettings>
</system.net>
 
 
Screenshot
Send Email using HTML Templates in ASP.Net with C# and VB.Net
 
 
Downloads