Comprobar this a cabo. Lo estoy usando con plantillas como recursos incrustados como este (pero puede ser modificado para localizar las plantillas en cualquier lugar):
public static class MailSender
{
static MailSender()
{
CompilerServiceFactory = new DefaultCompilerServiceFactory();
TemplateService = new TemplateService(CompilerServiceFactory.CreateCompilerService(), typeof(MailTemplate<>));
}
private static ICompilerServiceFactory CompilerServiceFactory { get; set; }
private static TemplateService TemplateService { get; set; }
private static ITemplate<T> GetTemplate<T>(T model)
{
string path = typeof(T).FullName;
var assembly = Assembly.GetExecutingAssembly();
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(path))
{
if (stream == null)
throw new FileNotFoundException("Mail template not found");
using (var reader = new StreamReader(stream))
{
string source = reader.ReadToEnd();
return TemplateService.GetTemplate<T>(source, model);
}
}
}
public static void Send<T>(string to, T model)
{
Send(new string[] { to }, new string[] { }, new string[] { }, model);
}
public static void Send<T>(string to, string cc, string bcc, T model)
{
Send(new string[] { to }, new string[] { cc }, new string[] { bcc }, model);
}
public static void Send<T>(string[] to, string[] cc, string[] bcc, T model)
{
var template = (MailTemplate<T>)GetTemplate<T>(model);
template.Execute();
Trace.WriteLine(string.Format("To: {0} Subject: {1}{3}Body: {2}", string.Join(",", to), template.Subject, template.Result, Environment.NewLine), "Mail");
#if !LOCAL
using (var message = new MailMessage())
using (var client = new SmtpClient())
{
if (!string.IsNullOrWhiteSpace(template.From))
message.From = new MailAddress(template.From);
message.To.Add(string.Join(",", to));
if (cc != null && cc.Length > 0)
message.CC.Add(string.Join(",", cc));
if (bcc != null && bcc.Length > 0)
message.Bcc.Add(string.Join(",", bcc));
message.Subject = template.Subject;
message.Body = template.Result;
message.IsBodyHtml = true;
client.Send(message);
}
#endif
}
}
public abstract class MailTemplate<TModel> : TemplateBase<TModel>
{
public string From { get; set; }
public string Subject { get; set; }
}
modelo:
public class Contact
{
public string Name { get; set; }
public string Email { get; set; }
public string Text { get; set; }
}
plantilla:
@inherits Feedback.Lib.Mail.MailTemplate<Feedback.Lib.Mail.Templates.Contact>
@{
From = string.Format("{0} <{1}>", Model.Name, Model.Email);
Subject = "Contact request - " + From;
}
@Model.Text
tengo para cada plantilla es su propio modelo, por lo que es fácil ubicarlos por nombre de clase. Además, no pude hacer un trabajo intellisense.
Hey! ¡No puedo crear mi propio proyecto aquí! :) – Buildstarted