I had to do this several times. I originally used the ASP.Net template engine, based, in my opinion, on the Rick Strahl blog. It worked, but there was always a problem with which I hit my head.
I switched to using the NVelocity engine and found it to be a very simple way to create and maintain email templates. There are a number of other template engines, and I suspect that the next time I could take a serious look at Razor .
Code for combining values ββinto a template:
private string Merge(ManualTypeEnum manualType, Object mergeValues) { var body = ""; var templateFile = string.Format("{0}MailTemplate.vm", manualType); var velocity = new VelocityEngine(); var props = new ExtendedProperties(); props.AddProperty("file.resource.loader.path", Config.EmailTemplatePath); velocity.Init(props); var template = velocity.GetTemplate(templateFile); var context = new VelocityContext(); context.Put("Change", mergeValues); using (var writer = new StringWriter()) { template.Merge(context, writer); body = writer.ToString(); } return body; }
The values ββfor the union are passed as an anonymous object and can include various types, including lists, etc., for example.
var emailBody = Merge(newDocument.ManualType, new { ManualType = newDocument.ManualType.ToString(), Message = change.Message, NewTitle = newDocument.Title ?? "", NewVersion = newDocument.Version ?? "", Contact = From, Changes = change.ToList(), });
source share