Zian's Blog

Send Dynamic Responsive HTML Page (File) as Email Body in ASP.Net using C#

In this article I will explain with an example, how to send Dynamic Responsive HTML Page (File) as Email Body in ASP.Net using C#.

Let’s start with the Email Template HTML page.

HTML Page:

The very first step is to Right Click on Project in the Solution Explorer and click ‘Add’ and then ‘New Item’ and then select ‘HTML’ Page and name it as EmailTemplate.htm or EmailTemplate.html

Done, let’s proceed to HTML Design.

Building HTML Template for Email Body:

I won’t concentrate much on designing, so I’ll use a snippet that available online, you can use any other template you like.

Let’s modify the HTML a bit so that we can replace the content 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.

<div style="line-height: 24px;">
    <font face="Arial, Helvetica, sans-serif" size="4" color="#57697e" style="font-size: 15px;">
       <span style="font-family: Arial, Helvetica, sans-serif; font-size: 15px; color: #57697e;">                                                                    Hello {UserName},
        </span>
  <p style="font-family: Arial, Helvetica, sans-serif; font-size: 15px;              color: #57697e;text-align:left;">                                                                    {body}
</p>
     </font>
</div>

We’re all set! Here, {UserName} and {body} we’ll pass as parameter later while sending the Email.

Next step:

Go to the controller/service you want to send Email. And add these namespaces:

using System.Net.Mail;
using System.Configuration;
using System.IO;
using MyApp.Communication.EmailProxy; //Your your email proxy library here

Populating the HTML Formatted Body:

private string PopulateBody(string userName, string body)
{
string body = string.Empty;
using (StreamReader reader = new StreamReader(Server.MapPath(“~/Uploads/EmailTemplate.html”)))
{
body = reader.ReadToEnd();
}
body = body.Replace(“{UserName}”, userName);
body = body.Replace(“{body}”, title);
return body;
}

Sending the Email:

private bool SendHtmlFormattedEmail(string recepientEmail, string subject, string body)
{
String error = string.Empty;
bool result = false;
using (MailMessage mailMessage = new MailMessage())
{
try
{
mailMessage.From = new MailAddress(ConfigurationManager.AppSettings[“Email_Username”]);
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MailAddress(recepientEmail));
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings[“Email_SMTP_Server”];
smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings[“Email_EnableSSL”]);
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings[“Email_Username”];
NetworkCred.Password = ConfigurationManager.AppSettings[“Email_Password”];
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = int.Parse(ConfigurationManager.AppSettings[“SMTP_Port”]);
smtp.Send(mailMessage);
result = true;
return result;
}
catch (Exception ex)
{
error = ex.ToString();
return result;
}
}
}

FYI, all my Email settings like SMTP_Port, Email_Password is in my Web.config.

Above I’ve already given the functions and namespace required to send HTMl formatted email. Let’s have a look at the complete code again.

string subject = “Send Dynamic Responsive Email in ASP.Net using C#”;

//generate the body want to send in the mail starts here
string body = “Thank you for reading my Blog!”;
body += “<br>”;
body += “To read more blogs visit me by clicking the below URL.”;
body += “URL: blog.nazrulkabir.com“;
body += “<br>”;
body += “<br>”;
body += “Regards”;
body += “<br>”;
body += “Nazrul Kabir”;
body += “<br>”;
body += “Web: blog.nazrulkabir.com“;
body += “<br>”;
body += “DO NOT reply to this email. This email is system generated.”;
body += “<br>”;
//generate the body want to send in the mail starts here

//Populate HTML body
string PopulatedBody = this.PopulateBody(“me@nazrulkabir.com”, body);
//Send Email
if (!this.SendHtmlFormattedEmail(model.EmailAddress, subject, PopulatedBody))
{
ViewBag.Message += “Something went wrong “;
return View(model);
}

That’s all! We’re done!
If you’ve any confusion please let me know 🙂

On the next part of this post I’ll share how to make the Logo, Footer dynamic (Using model and DB). Thanks!