My company sends a lot of emails to clients. Order confirmation's, alert's, reports, yada yada yada. And God forbid one of them needs to be changed (I never misspell anything I swear!). So about 6 months ago Andrew (one of the other developers here) and I came up with this system.
We create several email templates that have reserved character strings in them and then use find and replace functions (String.Replace(find, replace)) to substitute in all of the values for the email. Boring right? The stroke of "genius" part for me was to access these over the web. The templates are stored on our webserver but any of the processes that need to send an email can do so via a web request. Check it out:
static public string RetrieveMailTemplate(string link)
{
System.Text.StringBuilder html = new System.Text.StringBuilder();
System.Net.HttpWebRequest request =
(System.Net.HttpWebRequest)System.Net.WebRequest.Create(link);
System.Net.HttpWebResponse response =
(System.Net.HttpWebResponse)request.GetResponse();
using (System.IO.StreamReader stream = new
System.IO.StreamReader(response.GetResponseStream()))
{
string line = "";
while ((line = stream.ReadLine()) != null)
{
html.AppendLine(line);
}
}
response.Close();
return html.ToString();
}
So you call this function with the location of the template and it returns to you the contents of the HTML document which you can modify. We use reserved strings like {#USER_ID#} that the calling function then replaces. This does require knowledge of the HTML contents, which I was hoping to avoid when I designed this, but so far in use it hasn't been a problem. Usage example:
string templatePath =
EmailTemplatesPath +
(mCurrentUser.Theme.Length > 0 ? mCurrentUser.Theme : "Normal") +
"/JobCreateSingleEmailTemplate.html;
body = RetrieveMailTemplate(templatePath);
body = body.Replace("{#PROTOCOL#}",
ConfigurationManager.AppSettings["Protocol"] + "://");
body = body.Replace("{#HTTP_HOST#}", Request.ServerVariables["HTTP_HOST"]);
body = body.Replace("{#APP_PATH#}", Request.ApplicationPath);
The example has been scrubbed of any references to the company I work for, I don't want to get sued if I broke any laws by posting this.You can also do some neat things if your webserver is an .NET server. When you make that Request call to a .NET page the page is compiled and run before the HTML is returned to you. So any code-behind that you want to run can be executed before you get that HTML back. This means that any HTML document is dynamic so long as the .NET code-behind modifies it. Cool!
