In this article I will explain with an example, how to create and send HTML formatted emails in ASP.Net using C# and VB.Net.
HTML formatted emails are used to send newsletters and promotional emails. Such emails contain Rich Text content, images and animations.
 
 
HTML Page
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.
Create and send HTML Formatted Emails in ASP.Net using 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 src="http://www.aspsnippets.com/images/Blue/Logo.png" /><br />
    <br />
    <div style="border-top: 3px solid #22BCE5">
        &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: #22BCE5" href="{Url}">{Title}</a><br />
        {Description}
        <br />
        <br />
        Thanks<br />
        ASPSnippets </span>
</body>
</html>
 
 
HTML Markup
Following HTML Markup consists of an ASP.Net Button.
<form id="form1" runat="server">
<asp:Button ID="btnSend" runat="server" Text="Send" OnClick="SendEmail" />
</form>
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Configuration;
using System.IO;
using System.Net.Mail;
 
VB.Net
Imports System.Configuration
Imports System.IO
Imports System.Net.Mail
 
 
Populating the HTML Formatted Body
Inside the following function, the contents of the HTML Email Template file are read into a String variable using the StreamReader class and the placeholders are replaced with their values.
This method will be called on the Click event of Send Button.
C#
private string PopulateBody(string userName, string title, string url, string description)
{
    string body = string.Empty;
    using (StreamReader reader = new StreamReader(Server.MapPath("~/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(ByVal userName As String, ByVal title As String, ByVal url As String, ByVal description As String) As String
    Dim body As String = String.Empty
    Dim reader As StreamReader = New StreamReader(Server.MapPath("~/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
End Function
 
 
Sending Email
Inside the following function, the email is being sent. The SMTP email settings are read from the appSettings section of the Web.Config file.
The values of the recipient’s email address, subject and body are accepted as parameters.
C#
private void SendHtmlFormattedEmail(string recepientEmail, string subject, string body)
{
    using (MailMessage mailMessage = new MailMessage())
    {
        mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["UserName"]);
        mailMessage.Subject = subject;
        mailMessage.Body = body;
        mailMessage.IsBodyHtml = true;
        mailMessage.To.Add(new MailAddress(recepientEmail));
        SmtpClient smtp = new SmtpClient();
        smtp.Host = ConfigurationManager.AppSettings["Host"];
        smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
        System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
        NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
        NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
        smtp.Send(mailMessage);
    }
}
 
VB.Net
Private Sub SendHtmlFormattedEmail(ByVal recepientEmail As String, ByVal subject As String, ByVal body As String)
    Dim mailMessage As MailMessage = New MailMessage
    mailMessage.From = New MailAddress(ConfigurationManager.AppSettings("UserName"))
    mailMessage.Subject = subject
    mailMessage.Body = body
    mailMessage.IsBodyHtml = True
    mailMessage.To.Add(New MailAddress(recepientEmail))
    Dim smtp As SmtpClient = New SmtpClient
    smtp.Host = ConfigurationManager.AppSettings("Host")
    smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings("EnableSsl"))
    Dim NetworkCred As System.Net.NetworkCredential = New System.Net.NetworkCredential
    NetworkCred.UserName = ConfigurationManager.AppSettings("UserName")
    NetworkCred.Password = ConfigurationManager.AppSettings("Password")
    smtp.UseDefaultCredentials = True
    smtp.Credentials = NetworkCred
    smtp.Port = Integer.Parse(ConfigurationManager.AppSettings("Port"))
    smtp.Send(mailMessage)
End Sub
 
 
Web.Config Configuration
You will need to add the following configuration in the Web.Config file in the appSettings section.
<appSettings>
  <add key="Host" value="smtp.gmail.com"/>
  <add key="EnableSsl" value="true"/>
  <add key="UserName" value="sender@gmail.com"/>
  <add key="Password" value="xxxxx"/>
  <add key="Port" value="587"/>
</appSettings>
 
 
Sending the Formatted HTML email
When the Send Button is clicked, first the Body of the email is generated using the PopulateBody method and then 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",
        "//www.aspsnippets.com/Articles/Fetch-multiple-values-as-Key-Value-pair-" +
        "in-ASP.Net-AJAX-AutoCompleteExtender.aspx",
        "Here Mudassar Ahmed Khan has explained 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("recipient@gmail.com", "New article published!", body);
}
 
VB.Net
Protected Sub SendEmail(ByVal sender As Object, ByVal e As EventArgs)
    Dim body As String = Me.PopulateBody("John", _
       "Fetch multiple values as Key Value pair in ASP.Net AJAX AutoCompleteExtender", _
       "//www.aspsnippets.com/Articles/Fetch-multiple-values-as-Key-Value" & _
       "-pair-in-ASP.Net-AJAX-AutoCompleteExtender.aspx", _
       ("Here Mudassar Ahmed Khan has explained 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("recipient@gmail.com", "New article published!", body)
End Sub
 
 
Screenshot
Create and send HTML Formatted Emails in ASP.Net using C# and VB.Net
 
 
Downloads