string ReplaceFieldsInHtml(EmailTemplate emailTemplate, Email email)
 {
     var html = emailTemplate.Html;
     foreach (var key in email.Fields.Keys)
         html = html.Replace("{{" + key + "}}", email.Fields[key]);
     return html;
 }
        void SendEmail(string processedHtml, Email email, EmailTemplate emailTemplate)
        {
            var client = new SmtpClient("smtp.sendgrid.net", 587)
                             {
                                 UseDefaultCredentials = false,
                                 Credentials = new NetworkCredential("*****@*****.**", "orange5")
                             };
            var from = new MailAddress(emailTemplate.SentFromEmail, emailTemplate.SentFromName);

            foreach (var recipient in email.Recipients)
            {
                var message = new MailMessage(from, new MailAddress(recipient.Email, recipient.Name))
                                  {
                                      Body = processedHtml,
                                      Subject = emailTemplate.Subject,
                                  };

                try
                {
                    client.Send(message);
                    email.SentOn = DateTime.UtcNow;
                    email.HtmlResult = processedHtml;
                    EmailService.Save(email);
                    
                    Trace.WriteLine(string.Format("{0}: Email sent to {1}", email.SentOn, recipient.Email));
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Format("{0}: Failure.  Email was not sent to {1}", email.SentOn, recipient.Email));
                    Trace.WriteLine(ex.Message);
                }
            }
        }
        public EmailTemplate Save(Guid realmToken, EmailTemplate emailTemplate)
        {
            using (var transaction = new TransactionScope())
            {
                var realm = RealmRepository.ByKey(realmToken);
                if (string.IsNullOrEmpty(emailTemplate.Id))
                {
                    emailTemplate = EmailTemplateRepository.Add(emailTemplate);
                    realm.EmailTemplates.Add(emailTemplate);
                    RealmRepository.Update(realm);
                }
                else
                    emailTemplate = EmailTemplateRepository.Update(emailTemplate);

                transaction.Complete();
                return emailTemplate;
            }
        }