Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Using Embedded Resources for HTML Email Templates

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();
            templateVars.Add("FirstName", user.FirstName);
            templateVars.Add("LastName", user.LastName);
            templateVars.Add("Login", user.UserId);
            templateVars.Add("Password", user.Password);

            Parser parser = new Parser(templateVars);
            Assembly asm = Assembly.GetExecutingAssembly();
            Stream stream = asm.GetManifestResourceStream(asm.GetName().Name +
                ".Registration.htm");

            using (StreamReader reader = new StreamReader(stream))
            {
                parser.TemplateBlock  = reader.ReadToEnd();
            }

            // Send email
            System.Net.Mail.MailMessage message = 
                  new System.Net.Mail.MailMessage();
            message.To.Add(user.Email);
            message.From = new MailAddress("brendan.tompkins@gmail.com");
            message.Subject = "Your StreetTurns.Com Account Information";
            message.Body = parser.Parse();
            message.IsBodyHtml = true;
            SmtpClient sc = new SmtpClient("StreetTurns.Com");
            sc.Send(message);
        }

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.


Posted 10-24-2007 8:23 AM by Brendan Tompkins
Filed under: , ,

[Advertisement]

Comments

Dave Laribee wrote re: Using Embedded Resources for HTML Email Templates
on 10-24-2007 1:37 PM

Cool.

What did you use for the nice code-formatting?

Brendan Tompkins wrote re: Using Embedded Resources for HTML Email Templates
on 10-24-2007 1:49 PM

Dave, I have syntaxhighlighter installed on both Devlicio.us and CodeBetter, so you can use it too!

code.google.com/.../syntaxhighlighter

DotNetKicks.com wrote Using Embedded Resources for HTML EMail Templates
on 10-25-2007 12:25 PM

You've been kicked (a good thing) - Trackback from DotNetKicks.com

yves wrote re: Using Embedded Resources for HTML Email Templates
on 10-26-2007 1:12 PM

Isn't it better to have you template driven from a databse inseatd of having them inside of a DLL.

I can see a great purpose of embeding certain files with data that should be secure...

but an hmtl template that every time you need to modify you have to rebuild your entrie dll and push it to the server does not seem like good seniro in a real world application.

Brendan Tompkins wrote re: Using Embedded Resources for HTML Email Templates
on 10-26-2007 1:18 PM

Yves,

No, i don't think it is a better idea to have them in the database.  They become extremely hard to manage once they're there.  When you have a file that you can deploy within a dll, you can use all the tools you'd normally use to edit these files..

Again, if you're reluctant to build and deploy your code, you have a code smell in your build process!

yves wrote re: Using Embedded Resources for HTML Email Templates
on 10-26-2007 4:41 PM

Ok but the Same interface to update that embedded file would be set up to update the one in your database.

As far as pushing DLL you are taking the risk to bring the app down if you have a user accessing your app whihle your DLL push. where databse can be accessed and modifed withou interuption.

Brendan Tompkins wrote re: Using Embedded Resources for HTML Email Templates
on 10-26-2007 4:51 PM

I'm not sure what you mean.  I'm talking about editing the HTML file with Dreamweaver or Visual Studio.  You know an easy way to open and modify a db object?

Don't be afraid to build and deploy!  You have one dll to drop. You shouldn't have to re-start the appdomain, and if you do, and it's a web app, you just use your content switch to migrate users to your second server while you update.

Simone Busoli wrote re: Using Embedded Resources for HTML Email Templates
on 10-26-2007 6:37 PM
NVelocity automatically handles embedded resources and lets you parse them with a single line of code. Plus, it has a much richer syntax. http://www.codeproject.com/useritems/nvelocityaspnet.asp
Brendan Tompkins wrote re: Using Embedded Resources for HTML Email Templates
on 10-26-2007 8:13 PM

Simone,

That's very cool!

Lexapro. wrote Lexapro dosage.
on 07-26-2008 5:29 AM

Lexapro side effects. Lexapro.

Bob wrote re: Using Embedded Resources for HTML Email Templates
on 11-19-2008 7:33 PM

When working with ASP.NET's MailDefinition property (e.g., from the create user wizard), ASP.NET assumes your email body is in a file.  I would like to set the BodyFileName from an embedded resource instead.

I haven't found any way to do this other then to copy the resource to a temporary file.  Have you run into this?

Add a Comment

(required)  
(optional)
(required)  
Remember Me?

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)