I'm using the following code to build and send an email using RazorEngine.
//build email using template.
string template = File.OpenText(EmailTemplatePath).ReadToEnd();
OrganizationInviteEmailTemplate model = new OrganizationInviteEmailTemplate()
{
FirstName = Invitation.FirstName,
LastName = Invitation.LastName,
Message = Message,
OrganizationName = Invitation.Organization.OrganizationName,
ConfirmUrl = string.Format(ConfirmUrlTemplate, Invitation.InviteCode)
};
string body = Razor.Parse(template, model);
//email the invitation.
MailMessage message = new MailMessage();
message.To.Add(Invitation.Email);
message.Subject = "Invitation From " + Invitation.Organization.OrganizationName;
message.Body = body;
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.Send(message);
The template is below:
<html>
<head>
</head>
<body>
<h3>@Model.OrganizationName has invited you to be part of their organization</h3>
<p>
Hi @Model.FirstName,
</p>
.....etc......
</body>
</html>
I get the "Unable to compile template" error 9 times out of 10 and then it will work once after I adjust the template by removing Model. and/or adjusting the code to use Parse instead, but then it will go right back to not working. It's like something is caching a piece of code briefly or something.
I'm using the RazorEngine.dll included with RazorJS, version 2.1.4113.149. Maybe that's the issue. Going to try this library or Postal next since this is taking way too much time already. Or just hard code the damn thing.
Unless you want to code it all by yourself, it will be more easy to install a nuget package like MvcMailer.
Aren't you missing the @model declaration at the top of your template?