Most web applications need to send out email for a variety of purposes, right? I like to use email as a sort of extended user interface - allowing entry points to let the user conveniently do work by getting an email and clicking on a link. I've struggled for a while with a good way of managing email templates to use in my applications. I recently found a good project that simplifies the process of templating - See Alexander Kleshchevnikov's excellent solution for managing and sending emails inside a web application.
I like his template approach, but I don't like to keep my template files in a directory with my web project, mainly because it tightly couples these files and a certain directory structure to the classes that actually do the email work. This makes my classes harder to test, re-use and deploy. I recently figured out how to embed these templates into my class' assembly files, making the class much more useful.
To embed a resource, just drop it in your project, and select "Embedded Resource"
Using Alexander's solution for templating, and an embedded resource html file for a template, the code to use this resource looks like this:
public static void SendRegisterNotification(User user)
Hashtable templateVars = new Hashtable();
Parser parser = new Parser(templateVars);
Assembly asm = Assembly.GetExecutingAssembly();
Stream stream = asm.GetManifestResourceStream(asm.GetName().Name +
using (StreamReader reader = new StreamReader(stream))
parser.TemplateBlock = reader.ReadToEnd();
// Send email
System.Net.Mail.MailMessage message =
message.From = new MailAddress("firstname.lastname@example.org");
message.Subject = "Your StreetTurns.Com Account Information";
message.Body = parser.Parse();
message.IsBodyHtml = true;
SmtpClient sc = new SmtpClient("StreetTurns.Com");
Yes, but what about Modifying your Templates?
As Jeremy Miller has pointed out, you shouldn't be afraid to compile and release your code. If you are, you need some serious work on your build process. To me, the benefit of having one class that I can drop anywhere without worrying about permissions, file paths, and all that far outweighs the need to re-build the DLL when I make a text change.
I'm pretty happy about the way this all works. For more on embedded resources, ther's some information here and here about how you can access your resources via a URL in a web app.
10-24-2007 8:23 AM