Example #1
0
        public async Task Send(IEmailTemplate emailTemplate)
        {
            var fromEmailAddress = this.systemParameterListRepository.GetSystemParameterList().FromEmailAddress;

            var message = new MailMessage(fromEmailAddress, emailTemplate.To, emailTemplate.Subject, emailTemplate.PlainTextBody);

            message.AlternateViews.Add(
                AlternateView.CreateAlternateViewFromString(
                    emailTemplate.HtmlBody,
                    new ContentType("text/html")));

            message.Headers.Add("X-SES-CONFIGURATION-SET", ConfigSet);

            var password = await this.secretsManager.Fetch("/parkingrota/SmtpPassword");

            const int Port = 587;

            using (var client = new SmtpClient(Host, Port))
            {
                client.Credentials = new NetworkCredential(Username, password);
                client.EnableSsl   = true;

                // Ensure we stay within AWS sending rate limit
                Thread.Sleep(TimeSpan.FromMilliseconds(100));

                await client.SendMailAsync(message);
            }
        }
Example #2
0
        /// <summary>
        /// Resends activation link for a user account
        /// </summary>
        /// <param name="dbCtx"></param>
        /// <param name="emailSender"></param>
        /// <param name="emailAccount"></param>
        /// <param name="emailTemplate"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task ResendActivationLinkAsync(DbContext dbCtx,
                                                    IEmailSender emailSender,
                                                    IEmailAccount emailAccount   = null,
                                                    IEmailTemplate emailTemplate = null, string password = null)
        {
            if (Uuid == default(Guid))
            {
                throw new InvalidOperationException("You cannot resend an activation link - this user has not yet been created...");
            }

            var newActivationDetails = await Auth.GetNewAccountActivationDetailsAsync(Uuid);

            //generate new email confirmation token
            var emailConfirmationToken =
                Auth.MergeIdWithToken(
                    Uuid,
                    newActivationDetails.newAccountActivationToken
                    );


            //send out the email
            if (emailTemplate != null && emailAccount != null)
            {
                emailSender.Send(
                    emailAccount,
                    emailTemplate.Prepare(new Dictionary <string, object>
                {
                    { "VerificationKey", emailConfirmationToken },
                    { "InitialPassword", newActivationDetails.newPass }
                }),
                    Email
                    );
            }
        }
        public bool SendEmail(EmailEventType eventType, object dataTableOrDTO, string to = "", string toName = "")
        {
            IEmailTemplate template = this.emailTemplateRepository.GetTemplate((int)eventType);

            if (to == "")
            {
                to = template.DefaultMailToId;
            }

            if (toName == "")
            {
                toName = template.DefaultMailToName;
            }

            object dataRow = dataTableOrDTO;

            if (dataTableOrDTO is DataTable)
            {
                dataRow = ((DataTable)dataTableOrDTO).Rows.FirstOrDefault();
            }

            string htmlBody = this.ParseEmailTemplate(template.DefaultMailBody, dataRow);

            bool result = SendMail(to, toName, template.DefaultMailFromId, template.DefaultMailFromName, template.DefaultMailCC, "", template.DefaultMailSubject, htmlBody);

            return(result);
        }
Example #4
0
 public SendEmailService(IUserInfoRepository userInfoRepository, ISendEmail sendEmail, ICompiler compiler, IEmailTemplate template)
 {
     _userInfoRepository = userInfoRepository;
     _sendEmail          = sendEmail;
     _compiler           = compiler;
     _template           = template;
 }
Example #5
0
 public CashierWF(IOrganizationService service, new_incidentservice target,
                  new_incidentserviceparameter paramters,
                  new_flightoccurrence orginalFlightOccurrence,
                  IEmailTemplate iEmailTemplate)
     : base(service, target, paramters, orginalFlightOccurrence, iEmailTemplate)
 {
 }
Example #6
0
        private static void SetProperties(IEmailTemplate template, Email mail, Action <string> updateBody)
        {
            if (template != 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 (updateBody != null)
                {
                    updateBody(template.Body);
                }
            }
        }
Example #7
0
        public async Task SendEmail(IEmailTemplate model, EmailCredentialsSettings settings, string emailTo, string templateName, string subject)
        {
            MailAddress from = new MailAddress(settings.EmailAccount);
            MailAddress to   = new MailAddress(emailTo);

            MailMessage message = new MailMessage(from, to);

            message.IsBodyHtml = true;
            message.Subject    = subject;

            string body = FileHelper.Load(settings.EmailsTemplatesFolder, templateName);

            message.Body = ReplaceText(model, body);

            using (var client = new SmtpClient())
            {
                client.UseDefaultCredentials = settings.UseDefaultCredentials;
                client.Host        = settings.Host;
                client.Port        = settings.Port;
                client.EnableSsl   = settings.EnableSsl;
                client.Credentials =
                    new NetworkCredential(settings.EmailAccount, settings.EmailPassword);

                await client.SendMailAsync(message).ConfigureAwait(false);
            }
        }
Example #8
0
 public ScheduleWF(IOrganizationService service, new_incidentservice target,
     new_incidentserviceparameter paramters,
     new_flightoccurrence orginalFlightOccurrence,
     IEmailTemplate iEmailTemplate)
     : base(service, target, paramters, orginalFlightOccurrence, iEmailTemplate)
 {
 }
Example #9
0
        /// <summary>
        /// Sends an email to a specified address using a specified template.
        /// </summary>
        /// <param name="toAddress">The address to send the email to.</param>
        /// <param name="template">The template to use for the email.</param>
        public void SendEmail(string toAddress, IEmailTemplate template)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(this.Settings.FromEmail));
            message.To.Add(new MailboxAddress(toAddress));

            message.Subject = $"{this.Settings.SubjectPrefix} {template.Subject}";

            message.Body = new TextPart("plain")
            {
                Text = template.GetPlainText()
            };

            using (var client = new SmtpClient())
            {
                // accept all SSL certificates (in case the server supports STARTTLS)
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect(this.Settings.SmtpHost, this.Settings.SmtpPort, this.Settings.SmtpSslRequired);

                if (this.Settings.NeedsAuthentication)
                {
                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate(this.Settings.SmtpUsername, this.Settings.SmtpPassword);
                }

                client.Send(message);
                client.Disconnect(true);
            }
        }
 public BookUserEmailService(IUserService userService, IBookService bookService, IEmailService emailService, IEmailTemplate emailTemplate)
 {
     _userService   = userService;
     _bookService   = bookService;
     _emailService  = emailService;
     _emailTemplate = emailTemplate;
 }
Example #11
0
        /// <summary>
        /// Sends an email
        /// </summary>
        /// <param name="emailAccount"></param>
        /// <param name="emailTemplate"></param>
        /// <param name="recipient"></param>
        /// <returns></returns>
        public async Task SendAsync(IEmailAccount emailAccount, IEmailTemplate emailTemplate, string recipient)
        {
            await Task.Run(() =>
            {
                var mail = new MailMessage();

                mail.To.Add(recipient);

                mail.From = new MailAddress(emailAccount.Sender);

                mail.Subject         = emailTemplate.Title;
                mail.SubjectEncoding = Encoding.UTF8;

                mail.Body         = emailTemplate.Body;
                mail.IsBodyHtml   = emailTemplate.IsBodyHtml;
                mail.BodyEncoding = Encoding.UTF8;

                var smtp = new SmtpClient
                {
                    Host        = emailAccount.SmtpHost,
                    Port        = emailAccount.SmtpPort ?? 587,
                    Credentials = new System.Net.NetworkCredential(emailAccount.User, emailAccount.Pass),
                    EnableSsl   = emailAccount.Ssl ?? false
                };

                var actionId = DateTime.Now.Ticks;

                try
                {
                    //Log($"{actionId} :: Attempting to send email to {recipient}; time start: {DateTime.Now.ToShortDateString()}-{DateTime.Now.ToShortTimeString()}");
                    smtp.Send(mail);
                    //Log($"{actionId} :: Email sent to {recipient}", $"Time taken in seconds: {new TimeSpan(DateTime.Now.Ticks - actionId).TotalSeconds}");
                }
                catch (Exception ex)
                {
                    var msgs = new List <string>
                    {
                        $"{actionId} :: Failed to send emails to {recipient}", $"Time taken in seconds: {new TimeSpan(DateTime.Now.Ticks - actionId).TotalSeconds}",
                        $"Sender details - host: {emailAccount.SmtpHost}, port: {emailAccount.SmtpPort}, sender: {emailAccount.Sender}, user: {emailAccount.User}, pass: {emailAccount.Pass}, ssl: {emailAccount.Ssl}",
                    };

                    var e   = ex;
                    var tab = string.Empty;

                    while (e != null)
                    {
                        msgs.Add($"{tab}{e.Message}");
                        e    = ex.InnerException;
                        tab += '\t';
                    }

                    //debug
                    //TODO - use proper logging utils!
                    //Log(
                    //    msgs.ToArray()
                    //);
                }
            });
        }
 public BookUserEmailService(IUserService userService, IBookService bookService, IEmailService emailService, IEmailTemplate emailTemplate, INotificationService notificationService)
 {
     _userService         = userService;
     _bookService         = bookService;
     _emailService        = emailService;
     _emailTemplate       = emailTemplate;
     _notificationService = notificationService;
 }
 public AppSendEmails(OrganizationServiceProxy service)
 {
     _service = service;
     _wfemailTemp = new ConsoleEmailTemplate(_service);
     WhoAmIRequest requst = new WhoAmIRequest();
     WhoAmIResponse res = (WhoAmIResponse)_service.Execute(requst);
     _userid = res.UserId;
 }
Example #14
0
 public RepositoryWrapper(BookLibraryContext bookLibraryContext, IMapper mapper, IEmailService emailService, IEmailTemplate emailTemplate, IHttpContextAccessor httpContextAccessor)
 {
     _libraryContext      = bookLibraryContext;
     _emailService        = emailService;
     _emailTemplate       = emailTemplate;
     _httpContextAccessor = httpContextAccessor;
     _mapper = mapper;
 }
Example #15
0
 public ForgotPasswordModel(UserManager <ApplicationUser> userManager,
                            IEmailSender emailSender,
                            IEmailTemplate emailTemplate)
 {
     _userManager   = userManager;
     _emailSender   = emailSender;
     _emailTemplate = emailTemplate;
 }
 public EmailTemplateEntity(IEmailTemplate emailTemplate)
 {
     CampaignId = emailTemplate.CampaignId;
     TemplateId = emailTemplate.TemplateId;
     Body       = emailTemplate.Body;
     Subject    = emailTemplate.Subject;
     IsLayout   = emailTemplate.IsLayout;
 }
 public BorrowerRepository(BookLibraryContext repositoryContext, IEmailService emailService, IEmailTemplate emailTemplate, IMapper mapper)
     : base(repositoryContext, emailService)
 {
     _mapper        = mapper;
     _context       = repositoryContext;
     _emailService  = emailService;
     _emailTemplate = emailTemplate;
 }
Example #18
0
 public EmailTemplateHistoryItemEntity(IEmailTemplate emailTemplate, string username)
 {
     CampaignId = emailTemplate.CampaignId;
     TemplateId = emailTemplate.TemplateId;
     Body       = emailTemplate.Body;
     Subject    = emailTemplate.Subject;
     IsLayout   = emailTemplate.IsLayout;
     Username   = username;
 }
 //////////////////////////////////
 public UserBaseController(IUserBaseService userBaseService, IUserService userService, ISendgridService sendgridService, IErrorLogService errorLogService, IGmailService gmailService, IEmailTemplate emailTemplate)
 {
     _userBaseService = userBaseService;
     _userService     = userService;
     _sendgridService = sendgridService;
     _gmailService    = gmailService;
     _errorLogService = errorLogService;
     _emailTemplate   = emailTemplate;
 }
Example #20
0
        public void Send(IEmailTemplate emailTemplate)
        {
            if (emailTemplate == null)
            {
                throw new ArgumentNullException("emailTemplate");
            }

            Send(emailTemplate.BuildMessage());
        }
        public async Task AddOrUpdateTemplateAsync(IEmailTemplate emailTemplate, string username)
        {
            await _templateRepository.UpsertAsync(emailTemplate, username);

            _cache.Remove(CacheKey(emailTemplate.CampaignId));

            await _log.WriteInfoAsync(nameof(AddOrUpdateTemplateAsync), $"Campaign: {emailTemplate.CampaignId}, TemplateId: {emailTemplate.TemplateId}",
                                      "Email template added or updated");
        }
Example #22
0
        public void TemplateConfiguration(string templateName, string customerId, string templateCode)
        {
            logger.Info("TemplateConfiguration Encountered");
            Type type              = this.GetType().Assembly.GetType(templateName);
            var  customerIdParam   = new Ninject.Parameters.ConstructorArgument("customerId", customerId);
            var  templateCodeParam = new Ninject.Parameters.ConstructorArgument("templateCode", templateCode);

            emailTemplate = Utility.General.Resolve <IEmailTemplate>(type, customerIdParam, templateCodeParam);
        }
        public AppSendEmails(OrganizationServiceProxy service)
        {
            _service     = service;
            _wfemailTemp = new ConsoleEmailTemplate(_service);
            WhoAmIRequest  requst = new WhoAmIRequest();
            WhoAmIResponse res    = (WhoAmIResponse)_service.Execute(requst);

            _userid = res.UserId;
        }
Example #24
0
 public Observer(IOrganizationService service, new_incidentservice target,
                 new_incidentserviceparameter paramters, new_flightoccurrence orginalFlightOccurrence, IEmailTemplate configEmailTemplate)
 {
     _service   = service;
     _target    = target;
     _paramters = paramters;
     _orginalFlightOccurrence = orginalFlightOccurrence;
     _emailTemplate           = configEmailTemplate;
 }
Example #25
0
 public Observer(IOrganizationService service, new_incidentservice target,
     new_incidentserviceparameter paramters, new_flightoccurrence orginalFlightOccurrence, IEmailTemplate configEmailTemplate)
 {
     _service = service;
     _target = target;
     _paramters = paramters;
     _orginalFlightOccurrence = orginalFlightOccurrence;
     _emailTemplate = configEmailTemplate;
 }
Example #26
0
        /// <summary>
        /// Ensures the mandatory placeholders are all specified in this template.
        /// </summary>
        public static void EnsurePlaceholders(this IEmailTemplate template)
        {
            // Make sure that all place holders appear in the email body or subject.
            var missingElements = template.GetPlaceholderTokens().Except(t => (template.Subject + template.Body).Contains(t));

            if (missingElements.Any())
            {
                throw new ValidationException("Email template subject or body must have all place-holders for {0}. The missing ones are: {1}", template.Key, missingElements.ToString(", "));
            }
        }
Example #27
0
        public async Task Send(IEmailTemplate emailTemplate)
        {
            var rawData = JsonSerializer.Serialize(emailTemplate);

            this.logger.LogInformation("Sending email: {@EmailTemplate}", emailTemplate);

            await this.storageProvider.SaveEmail(rawData);

            await this.emailProvider.Send(emailTemplate);
        }
        public void GetTokenAsync_ArgumentException(string key, IEmailTemplate template, Type exceptionType)
        {
            // Arrange
            var helper  = new TestHelper();
            var service = helper.Create <NotificationService>();
            var model   = new { };

            // Act
            // Assert
            Assert.Throws(exceptionType, () => service.Build(key, template, model));
        }
 public ForgotPasswordRequestedEventHandler(
     UserManager <ApplicationUser> userManager,
     IOptions <IdentityServerUserInteractionConfig> managementOptions,
     IEmailTemplate emailTemplate,
     IEmailer emailer)
 {
     _userManager        = userManager;
     _interactionOptions = managementOptions.Value;
     _emailTemplate      = emailTemplate;
     _emailer            = emailer;
 }
Example #30
0
        private string ReplaceText(IEmailTemplate model, string body)
        {
            foreach (PropertyInfo propertyInfo in model.GetType().GetProperties())
            {
                string propertyName  = "@[" + propertyInfo.Name + "]";
                string propertyValue = propertyInfo.GetValue(model, null)?.ToString();

                body = body.Replace(propertyName, propertyValue);
            }

            return(body);
        }
        /// <summary>
        /// Renders out the field of an email template into an HTML string using {Parameter.Property} notation
        /// </summary>
        /// <param name="Parameters">The source parameters as a dictionary of property name, value pairs</param>
        /// <param name="Template">The template to use as the binding definition</param>
        /// <param name="Field">The field of the email template that will be bound to (incase its not the body)</param>
        /// <returns>The HTML contents of the post bound template field</returns>
        public string RenderEmail(IEnumerable <TemplateParameter> Parameters, IEmailTemplate Template, PropertyInfo Field)
        {
            if (Parameters is null)
            {
                throw new ArgumentNullException(nameof(Parameters));
            }

            if (Field is null)
            {
                throw new ArgumentNullException(nameof(Field));
            }

            string TemplateValue = Field.GetValue(Template)?.ToString();

            foreach (TemplateParameter parameter in Parameters)
            {
                if (IsStraightCopy(parameter.Type))
                {
                    string thisMacro = "{" + $"{parameter.Name}" + "}";

                    string replacement = parameter.Value.ToString();

                    Field.SetValue(Template, Field.GetValue(Template)?.ToString().Replace(thisMacro, replacement));
                }
                else
                {
                    foreach (PropertyInfo objectProperty in parameter.Type.GetProperties().Where(p => p.GetCustomAttribute <DontTemplateBindAttribute>() is null))
                    {
                        if (objectProperty.GetGetMethod() is null)
                        {
                            continue;
                        }

                        try
                        {
                            string thisMacro = "{" + $"{parameter.Name}.{objectProperty.Name}" + "}";

                            if (TemplateValue != null && TemplateValue.Contains(thisMacro))
                            {
                                string replacement = objectProperty.GetValue(parameter.Value)?.ToString();

                                TemplateValue = TemplateValue.Replace(thisMacro, replacement);
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }

            return(TemplateValue);
        }
Example #32
0
        public Email RenderTemplate(string templateName, object model = null)
        {
            if (String.IsNullOrWhiteSpace(templateName))
            {
                throw new System.ArgumentException(String.Format(System.Globalization.CultureInfo.CurrentUICulture, "\"{0}\" cannot be blank.", "templateName"));
            }

            var templates = CreateTemplateInstances(templateName);

            foreach (var pair in templates)
            {
                pair.Value.SetModel(CreateModel(model));
                pair.Value.Execute();
            }

            var mail = new Email();

            templates.SelectMany(x => x.Value.To)
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .Each(email => mail.To.Add(email));

            templates.SelectMany(x => x.Value.ReplyTo)
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .Each(email => mail.ReplyTo.Add(email));

            templates.SelectMany(x => x.Value.Bcc)
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .Each(email => mail.Bcc.Add(email));

            templates.SelectMany(x => x.Value.CC)
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .Each(email => mail.CC.Add(email));

            IEmailTemplate template = null;

            // text template (.text.cshtml file)
            if (templates.TryGetValue(ContentTypes.Text, out template))
            {
                SetProperties(template, mail, body => { mail.TextBody = body; });
            }
            // html template (.html.cshtml file)
            if (templates.TryGetValue(ContentTypes.Html, out template))
            {
                SetProperties(template, mail, body => { mail.HtmlBody = body; });
            }
            // shared template (.cshtml file)
            if (templates.TryGetValue(String.Empty, out template))
            {
                SetProperties(template, mail, null);
            }

            return(mail);
        }
Example #33
0
        public async Task <Response> Execute(Enum emailType)
        {
            FromEmail = await _appSettings.AdminEmail;
            FromName  = await _appSettings.AdminName;

            var apiKey = await _appSettings.SendGridAPIKey;
            var client = new SendGridClient(apiKey);
            var from   = new EmailAddress(FromEmail, FromName);
            var to     = new EmailAddress(_toEmail, _toName);

            _token = HttpUtility.UrlEncode(_token);


            switch (emailType)
            {
            case EmailType.AccountVerification:
                var accountVerification = new AccountVerificationEmail(_appSettings);
                accountVerification._email = _email;
                accountVerification._token = _token;
                _template = accountVerification;

                break;

            case EmailType.ScoreDetail:
                var scoreDetails = new ScoreDetailsEmail();
                scoreDetails._score = _score;
                _template           = scoreDetails;
                break;

            case EmailType.Purchase:
                var purchaseDetails = new PurchaseDetailsEmail();
                purchaseDetails._coin = _coin;
                _template             = purchaseDetails;
                break;

            case EmailType.ChangePassword:
                var changePasswordEmail = new ChangePasswordEmail(_appSettings);
                changePasswordEmail._email = _email;
                changePasswordEmail._token = _token;
                _template = changePasswordEmail;
                break;

            default:
                break;
            }
            var item = await _template.Template();

            var msg      = MailHelper.CreateSingleEmail(from, to, item.Subject, item.PlainTextContent, item.HtmlContent);
            var response = await client.SendEmailAsync(msg);

            return(response);
        }
        public Email GetTemplate(IEmailTemplate email)
        {
            Guard.NotNull(email, nameof(email));

            var variables = email.GetVariablesToReplace();

            var template = this.ReadEmailTemplate(email.GetType());
            template.Subject = this.ReplaceVariables(template.Subject, variables);
            template.Body = this.ReplaceVariables(template.Body, variables);
            template.Sender = email.Sender;

            return template;
        }
Example #35
0
 public UserController(
     ApplicationDbContext context,
     UserManager<ApplicationUser> userManager,
     IEmailSender emailSender,
     IEmailTemplate emailTemplate,
     IStringLocalizer<AccountController> localizer)
 {
     DbContext = context;
     _userManager = userManager;
     _emailSender = emailSender;
     _emailTemplate = emailTemplate;
     T = localizer;
 }
Example #36
0
        public AccountController(
            UserManager<ApplicationUser> userManager,
            SignInManager<ApplicationUser> signInManager,
            IEmailSender emailSender,
            ISmsSender smsSender,
            ILoggerFactory loggerFactory,
            ApplicationDbContext applicationDbContext,
            IEmailTemplate emailTemplate,
            IStringLocalizer<AccountController> localizer)

        {
            _userManager = userManager;
            _signInManager = signInManager;
            _emailSender = emailSender;
            _smsSender = smsSender;
            _logger = loggerFactory.CreateLogger<AccountController>();
            _applicationDbContext = applicationDbContext;
            _emailTemplate = emailTemplate;
            T = localizer;

        }
Example #37
0
		/// <summary>
		/// Initially parses the email for each of the tags, then
		/// creates an email scope object for storing this information.
		/// </summary>
		/// <param name="template">Email template to parse.</param>
		/// <returns></returns>
		public EmailScope InitializeEmail(IEmailTemplate template)
		{
			//Iterate through the emailbody and identify each of the tags
			var result = new EmailScope
			{
				HtmlEmailBody = template.HtmlTemplate,
				PlainEmailBody = template.TextTemplate,
				Subject = template.Subject,
				BooleanLogics = new List<BooleanLogic>(),
				StringVariables = new List<StringVariable>()
			};

			var searchIndex = 0;
			//Run this once for the HTML body, again for the plain body and once more for the subject.
			if (!string.IsNullOrEmpty(template.HtmlTemplate))
			{
				while (searchIndex < template.HtmlTemplate.Length)
				{
					//Retrieve the index of the next occurence of {{ in the email
					var startIndexValue = GetIndexOfNextOpenTag(template.HtmlTemplate, searchIndex);
					if (startIndexValue == null)
					{
						//No more start tags
						searchIndex = template.HtmlTemplate.Length;
						break;
						//return result;
					}

					//Set the search index to this value now
					searchIndex = (int) startIndexValue;

					//Get the end index value of this tag
					var endIndexValue = GetIndexOfCloseTag(template.HtmlTemplate, searchIndex);

					//Verify that this tag has an ending
					if (endIndexValue == null)
					{
						//This tag doesn't actually end, let's bow out of this loop
						break;
					}

					//Now, set the search index to this value
					searchIndex = (int) endIndexValue;

					//Extract the contents of the tag
					var tagBody = template.HtmlTemplate.Substring((int) startIndexValue + 2,
						(int) endIndexValue - (int) startIndexValue - 2);

					//Set the values of the name and comment
					var tagName = tagBody;
					var tagDescription = "";

					//Identify if there's a comment in the tag
					if (tagBody.Contains("|"))
					{
						var splitValues = tagBody.Split('|');
						tagName = splitValues[0];
						tagDescription = splitValues[1];
					}

					//Look at the first character in the tag name (and see if it's a special character)
					if (tagName[0] == '#')
					{
						//This is a boolean logic tag
						var booleanTag = new BooleanLogic
						{
							Name = tagName.Substring(1), //Remove the # from the name
							Description = tagDescription
						};

						//Check to see that this tag doesn't already exist (name search)
						if (result.BooleanLogics.All(t => t.Name != booleanTag.Name))
						{
							//Append this tag to the email scope object
							result.BooleanLogics.Add(booleanTag);
						}
					}
					else if (tagName[0] == '/')
					{
						//This is a close tag for a boolean statement - ignore
					}
					else
					{
						//This is a variable tag
						var variableTag = new StringVariable()
						{
							Name = tagName,
							Description = tagDescription
						};

						//Check to see that this tag doesn't already exist (name match)
						if (result.StringVariables.All(t => t.Name != variableTag.Name))
						{
							//Append this tag to the email scope object
							result.StringVariables.Add(variableTag);
						}
					}
				}
			}

			//Now for the plain text body
			searchIndex = 0;
			if (!string.IsNullOrEmpty(template.TextTemplate))
			{
				while (searchIndex < template.TextTemplate.Length)
				{
					//Retrieve the index of the next occurence of {{ in the email
					var startIndexValue = GetIndexOfNextOpenTag(template.TextTemplate, searchIndex);
					if (startIndexValue == null)
					{
						//No more start tags
						searchIndex = template.TextTemplate.Length;
						break;
						//return result;
					}

					//Set the search index to this value now
					searchIndex = (int) startIndexValue;

					//Get the end index value of this tag
					var endIndexValue = GetIndexOfCloseTag(template.TextTemplate, searchIndex);

					//Verify that this tag has an ending
					if (endIndexValue == null)
					{
						//This tag doesn't actually end - let's bow out of this loop
						break;
					}

					//Now, set the search index to this value
					searchIndex = (int) endIndexValue;

					//Extract the contents of the tag
					var tagBody = template.TextTemplate.Substring((int) startIndexValue + 2,
						(int) endIndexValue - (int) startIndexValue - 2);

					//Set the values of the name and comment
					var tagName = tagBody;
					var tagDescription = "";

					//Identify if there's a comment in the tag
					if (tagBody.Contains("|"))
					{
						var splitValues = tagBody.Split('|');
						tagName = splitValues[0];
						tagDescription = splitValues[1];
					}

					//Look at the first character in the tag name (and see if it's a special character)
					if (tagName[0] == '#')
					{
						//This is a boolean logic tag
						var booleanTag = new BooleanLogic
						{
							Name = tagName.Substring(1), //Remove the # from the name
							Description = tagDescription
						};

						//Check to see that this tag doesn't already exist (name search)
						if (result.BooleanLogics.All(t => t.Name != booleanTag.Name))
						{
							//Append this tag to the email scope object
							result.BooleanLogics.Add(booleanTag);
						}
					}
					else if (tagName[0] == '/')
					{
						//This is a close tag for a boolean statement - ignore
					}
					else
					{
						//This is a variable tag
						var variableTag = new StringVariable()
						{
							Name = tagName,
							Description = tagDescription
						};

						//Check to see that this tag doesn't already exist (name match)
						if (result.StringVariables.All(t => t.Name != variableTag.Name))
						{
							//Append this tag to the email scope object
							result.StringVariables.Add(variableTag);
						}
					}
				}
			}

			//Finally for the subject
			searchIndex = 0;
			if (!string.IsNullOrEmpty(template.Subject))
			{
				while (searchIndex < template.Subject.Length)
				{
					//Retrieve the index of the next occurence of {{ in the email
					var startIndexValue = GetIndexOfNextOpenTag(template.Subject, searchIndex);
					if (startIndexValue == null)
					{
						//No more start tags
						searchIndex = template.Subject.Length;
						break;
						//return result;
					}

					//Set the search index to this value now
					searchIndex = (int) startIndexValue;

					//Get the end index value of this tag
					var endIndexValue = GetIndexOfCloseTag(template.Subject, searchIndex);

					//Verify that this tag has an ending
					if (endIndexValue == null)
					{
						//This tag doesn't actually end - let's bow out of this loop
						break;
					}

					//Now, set the search index to this value
					searchIndex = (int) endIndexValue;

					//Extract the contents of the tag
					var tagBody = template.Subject.Substring((int) startIndexValue + 2,
						(int) endIndexValue - (int) startIndexValue - 2);

					//Set the values of the name and comment
					var tagName = tagBody;
					var tagDescription = "";

					//Identify if there's a comment in the tag
					if (tagBody.Contains("|"))
					{
						var splitValues = tagBody.Split('|');
						tagName = splitValues[0];
						tagDescription = splitValues[1];
					}

					//Look at the first character in the tag name (and see if it's a special character)
					if (tagName[0] == '#')
					{
						//This is a boolean logic tag
						var booleanTag = new BooleanLogic
						{
							Name = tagName.Substring(1), //Remove the # from the name
							Description = tagDescription
						};

						//Check to see that this tag doesn't already exist (name search)
						if (result.BooleanLogics.All(t => t.Name != booleanTag.Name))
						{
							//Append this tag to the email scope object
							result.BooleanLogics.Add(booleanTag);
						}
					}
					else if (tagName[0] == '/')
					{
						//This is a close tag for a boolean statement - ignore
					}
					else
					{
						//This is a variable tag
						var variableTag = new StringVariable()
						{
							Name = tagName,
							Description = tagDescription
						};

						//Check to see that this tag doesn't already exist (name match)
						if (result.StringVariables.All(t => t.Name != variableTag.Name))
						{
							//Append this tag to the email scope object
							result.StringVariables.Add(variableTag);
						}
					}
				}
			}

			return result;
		}
        private static void SetProperties(IEmailTemplate template, Email mail, Action<string> updateBody)
        {
            if (template != 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 (updateBody != null)
                {
                    updateBody(template.Body);
                }
            }
        }