public virtual Email Execute(string templateName, object model = null) { Invariant.IsNotBlank(templateName, "templateName"); templateName = templateName.CleanCodeName(); var templates = CreateTemplateInstances(templateName); foreach (var pair in templates) { pair.Value.SetModel(model); pair.Value.Execute(); } var mail = new Email(); templates.SelectMany(x => x.Value.To) .Distinct(StringComparer.OrdinalIgnoreCase) .Each(AddMails(mail)); templates.SelectMany(x => x.Value.ReplyTo) .Distinct(StringComparer.OrdinalIgnoreCase) .Each(AddReplyToMails(mail)); templates.SelectMany(x => x.Value.Bcc) .Distinct(StringComparer.OrdinalIgnoreCase) .Each(AddBccMails(mail)); templates.SelectMany(x => x.Value.CC) .Distinct(StringComparer.OrdinalIgnoreCase) .Each(AddCCMails(mail)); Action<string, Action<string>> set = (contentType, action) => { var item = templates.SingleOrDefault(x => x.Key.Equals(contentType)); IEmailTemplate template = item.Value; if (item.Value != null) { if (!string.IsNullOrWhiteSpace(template.From)) { mail.From = template.From; } if (!string.IsNullOrWhiteSpace(template.Sender)) { mail.Sender = template.Sender; } if (!string.IsNullOrWhiteSpace(template.Subject)) { mail.Subject = template.Subject; } template.Headers.Each(pair => mail.Headers[pair.Key] = pair.Value); if (action != null) { action(template.Body); } } }; set(ContentTypes.Text, AssignTextBody(mail)); set(ContentTypes.Html, AssignHtmlBody(mail)); set(string.Empty, null); return mail; }
public void Send(Email email) { Invariant.IsNotNull(email, "email"); using (var message = CreateDefaultMailMessageFactory()(email)) { using (var client = CreateClientFactory()) { client.Send(message); } } }
static Email CreateEmail() { var email = new Email { From = "*****@*****.**", Sender = "*****@*****.**", Subject = "A sample mail" }; email.To.Add("*****@*****.**"); email.To.Add("*****@*****.**"); email.ReplyTo.Add("*****@*****.**"); email.ReplyTo.Add("*****@*****.**"); email.CC.Add("*****@*****.**"); email.CC.Add("*****@*****.**"); email.Bcc.Add("*****@*****.**"); email.Bcc.Add("*****@*****.**"); email.Headers.Add("k1", "v1"); email.Headers.Add("k2", "v2"); return email; }
Action<string> AddMails(Email mail) { return email => mail.To.Add(email); }
Action<string> AddReplyToMails(Email mail) { return email => mail.ReplyTo.Add(email); }
Action<string> AddBccMails(Email mail) { return email => mail.Bcc.Add(email); }
Action<string> AddCCMails(Email mail) { return email => mail.CC.Add(email); }
Action<string> AssignTextBody(Email mail) { return body => mail.TextBody = body; }
Action<string> AssignHtmlBody(Email mail) { return body => mail.HtmlBody = body; }