Summary: Have you ever faced a need to send personalized email using preformated HTML templates. If yes then this article will give you a better idea on how to use HTML templates in ASP.NET to send custom emails.
Introduction: Did you ever felt the need of using a HTML template with place holders for variable fields to be replaced to send personalized emails to each user? If yes, then this article will give you a better idea on how to use the System.Web.Mail namespace in .NET.
You can download the complete source files also attached with this article.
Elaboration:
Here is what you need to do to get started.
- Create a generic HTML template file with the required variables. In this example we will take our file name as ForgotPassword.html and the variable to replace while sending personalized mails would be @add_username & @add_password.
Below is the source for the HTML template file used in this article.
Here are the web.config settings used in this sample article.
<appSettings>
<add key="TemplatePath" value="C:/ABC_Site/Templates/"/>
<add key="SmtpServer" value="mail.abc.com"/>
<add key="SmtpUser" value="abc@abc.com>
<"/add key="SmtpPass" value="*******"/>
</appSettings>
//This is the method to send email, you can call this method on the Button Click event inside an ASP.NET Web Form.
public string SendPasswordMail(string user, string pwd)
{
try
{
SmtpMail.SmtpServer = System.Configuration.ConfigurationManager.AppSettings["SmtpServer"]; //Read all the configuration values from web.config.
MailMessage oMessage = new MailMessage();
oMessage.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
oMessage.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = System.Configuration.ConfigurationManager.AppSettings["SmtpUser"];
oMessage.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = System.Configuration.ConfigurationManager.AppSettings["SmtpPass"];
oMessage.BodyFormat = MailFormat.Html;
oMessage.From = System.Configuration.ConfigurationManager.AppSettings["SmtpUser"].ToString();
oMessage.Subject = "Password Reminder Notification";
oMessage.To = user;
oMessage.Headers.Add("content-type", "text/html;");
string str = "";
string FilePath = System.Configuration.ConfigurationManager.AppSettings["TemplatePath"].ToString();
if (File.Exists(FilePath + "ForgotPassword.htm"))
{
FileStream f1 = new FileStream(FilePath + "ForgotPassword.htm", FileMode.Open);
StreamReader sr = new StreamReader(f1);
str = sr.ReadToEnd();
str = str.Replace("@add_username", user); //Replace the values from DB or any other source to personalize each mail.
str = str.Replace("@add_password", pwd);
f1.Close();
}
oMessage.Body = str;
SmtpMail.Send(oMessage);
return "Mail Sent Successfully!";
}
catch (Exception ex)
{
return "Error: Mail cannot be sent!";
}