Exemplo n.º 1
0
        public override async Task <string> SendTemplate(EmailConstants.EmailTypes emailType, Dictionary <string, string> emailAttributes)
        {
            var emailTemplateId = EmailTypeToSendgridId(emailType);
            var from            = new EmailAddress(emailAttributes["FromEmail"], emailAttributes["FromUserName"]);
            var to  = new EmailAddress(emailAttributes["ToEmail"], emailAttributes["ToUserName"]);
            var msg = MailHelper.CreateSingleTemplateEmail(from, to, emailTemplateId, emailAttributes);

            return(await SendViaSendGrid(msg));
        }
        public override async Task <string> SendTemplate(EmailConstants.EmailTypes emailType, Dictionary <string, string> emailAttributes)
        {
            var to = new List <SendSmtpEmailTo>();

            to.Add(new SendSmtpEmailTo(emailAttributes["ToEmail"], emailAttributes["ToUserName"]));
            var sendSmtpEmail = new SendSmtpEmail(to: to);

            sendSmtpEmail.TemplateId = EmailTypeToSendInBlueId(emailType);
            sendSmtpEmail.Params     = emailAttributes;
            return(await SendViaSendInBlue(sendSmtpEmail));
        }
        private long EmailTypeToSendInBlueId(EmailConstants.EmailTypes emailType)
        {
            string emailTemplateId = "";

            switch (emailType)
            {
            case EmailConstants.EmailTypes.PasswordReset:
                emailTemplateId = emailSettings.SendInBlueSettings.PasswordResetId;
                break;

            case EmailConstants.EmailTypes.WelcomeEmailValidation:
                emailTemplateId = emailSettings.SendInBlueSettings.WelcomeEmailValidationId;
                break;

            case EmailConstants.EmailTypes.PasswordResetUnknownEmail:
                emailTemplateId = emailSettings.SendInBlueSettings.PasswordResetUnknownEmailId;
                break;

            case EmailConstants.EmailTypes.PasswordResetEmailNotValidated:
                emailTemplateId = emailSettings.SendInBlueSettings.PasswordResetEmailNotValidatedId;
                break;

            case EmailConstants.EmailTypes.ChangePasswordEmail:
                emailTemplateId = emailSettings.SendInBlueSettings.ChangePasswordEmailId;
                break;

            case EmailConstants.EmailTypes.CommunityInvitation:
                emailTemplateId = emailSettings.SendInBlueSettings.CommunityInvitationId;
                break;

            case EmailConstants.EmailTypes.CommunityInvitationManager:
                emailTemplateId = emailSettings.SendInBlueSettings.CommunityInvitationManagerId;
                break;

            case EmailConstants.EmailTypes.None:
                throw new SendInBlueException("EmailType None");
            }

            if (emailTemplateId == "")
            {
                throw new SendInBlueException("EmailType Unknown: " + emailType.ToString());
            }

            try
            {
                return(Convert.ToInt64(emailTemplateId));
            }
            catch (Exception e)
            {
                throw new SendInBlueException(string.Format("EmailType {}: Could not convert {} to long. {}",
                                                            emailType, emailTemplateId, e.ToString()));
            }
        }
Exemplo n.º 5
0
        private string EmailTypeToSendgridId(EmailConstants.EmailTypes emailType)
        {
            string emailTemplateId = "";

            switch (emailType)
            {
            case EmailConstants.EmailTypes.PasswordReset:
                emailTemplateId = emailSettings.SendGridSettings.PasswordResetId;
                break;

            case EmailConstants.EmailTypes.WelcomeEmailValidation:
                emailTemplateId = emailSettings.SendGridSettings.WelcomeEmailValidationId;
                break;

            case EmailConstants.EmailTypes.PasswordResetUnknownEmail:
                emailTemplateId = emailSettings.SendGridSettings.PasswordResetUnknownEmailId;
                break;

            case EmailConstants.EmailTypes.PasswordResetEmailNotValidated:
                emailTemplateId = emailSettings.SendGridSettings.PasswordResetEmailNotValidatedId;
                break;

            case EmailConstants.EmailTypes.ChangePasswordEmail:
                emailTemplateId = emailSettings.SendGridSettings.ChangePasswordEmailId;
                break;

            case EmailConstants.EmailTypes.CommunityInvitation:
                emailTemplateId = emailSettings.SendGridSettings.CommunityInvitationId;
                break;

            case EmailConstants.EmailTypes.CommunityInvitationManager:
                emailTemplateId = emailSettings.SendGridSettings.CommunityInvitationManagerId;
                break;

            case EmailConstants.EmailTypes.SignupConfirmation:
                emailTemplateId = emailSettings.SendGridSettings.SignupConfirmationId;
                break;

            case EmailConstants.EmailTypes.None:
                throw new SendgridException("EmailType None");
            }

            if (emailTemplateId == "")
            {
                throw new SendgridException("EmailType Unknown: " + emailType.ToString());
            }

            return(emailTemplateId);
        }
        public async Task SendOneEmail(EmailConstants.EmailTypes emailType, Dictionary <string, string> emailAttributes)
        {
            if (EmailSettings.Type == EmailSettings.EmailTypeDisabled)
            {
                throw new SendEmailException("Email sending disabled");
            }

            // A base url for general links in the email - the front-end will decide the redirect location.
            emailAttributes["EmailLink"] = this.MakeEmailLink("/email.html", "").ToString();

            logger.LogDebug("SendOneEmail sending email {EmailType} {ClientIp}",
                            emailAttributes["EmailType"], emailAttributes["ClientIp"]);
            var  stopWatch = Stopwatch.StartNew();
            bool success   = false;

            try
            {
                var worker = SendEmailWorkerFactory.Get(EmailSettings, logger);
                if (worker == null)
                {
                    throw new SendEmailException("Unknown email type " + EmailSettings.Type);
                }
                success = true;
                var id = await worker.SendTemplate(emailType, emailAttributes);

                logger.LogInformation("SendOneEmail: Send success. {EmailType} {ClientIp} {MessageId}",
                                      emailAttributes["EmailType"], emailAttributes["ClientIp"], id);
            }
            finally
            {
                stopWatch.Stop();
                EmailSendingHistogram.Labels(emailAttributes["EmailType"], EmailSettings.Type, success.ToString())
                .Observe(stopWatch.Elapsed.TotalSeconds);
            }


            if (!success)
            {
                throw new UnableToSendEmailException();
            }
        }
 public abstract Task <string> SendTemplate(EmailConstants.EmailTypes emailType,
                                            Dictionary <string, string> emailAttributes);
Exemplo n.º 8
0
        public override async Task <string> SendTemplate(EmailConstants.EmailTypes emailType, Dictionary <string, string> emailAttributes)
        {
            Task <string> result = base.SendTemplate(emailType, emailAttributes);

            string templateFile = $"{Path.Combine(this.emailSettings.FileTemplatePath, emailType.ToString())}.html";
            string outputPath   = this.emailSettings.FileOutputPath ?? Path.Combine(Path.GetTempPath(), "morphic-emails");

            Directory.CreateDirectory(outputPath);

            string saveAs = Path.Combine(outputPath, this.emailSettings.FileOverwrite
                ? $"{emailType}-output.html"
                : $"{DateTime.Now:yyyyMMddTHHmmss}.{emailType}-output.html");

            // Some generate some debug information.
            StringBuilder debug = new StringBuilder();

            debug.AppendLine($"\n\n<!-- {emailType} {DateTime.Now:R}")
            .AppendLine($"Template: {Path.GetFileName(templateFile)}")
            .AppendLine($"Output: {Path.GetFileName(saveAs)}")
            .AppendLine()
            .AppendLine($"{string.Join("\n", emailAttributes)}")
            .AppendLine();

            HashSet <string> usedKeys = new HashSet <string>();

            string template;

            try
            {
                template = await File.ReadAllTextAsync(templateFile);
            }
            catch (Exception e)
            {
                // Create a basic template, using the email attributes dictionary.
                StringBuilder templateBuilder = new StringBuilder($"<html><body><pre>Email sent {DateTime.Now:R}\n\n");

                templateBuilder.AppendLine(e.Message).AppendLine();

                emailAttributes.Select(attr => $"{attr.Key}: {{{{ {attr.Key} }}}}\n")
                .ToList()
                .ForEach(s => templateBuilder.AppendLine(s));
                templateBuilder.AppendLine("</pre></body></html>");

                template = templateBuilder.ToString();
            }

            // Matches simple "handlebars" expressions, containing a key-name.
            Regex fillEmail = new Regex(@"\{\{\s*([^}\s]+)\s*}}");

            // Resolve the key-name with the value in the dictionary
            string content = fillEmail.Replace(template, match =>
            {
                string key = match.Groups[1].Value;
                if (emailAttributes.TryGetValue(key, out string?value))
                {
                    usedKeys.Add(key);
                }
                else
                {
                    debug.AppendLine($"Unknown: {key}");
                }

                return(value ?? match.Value);
            });

            debug.AppendLine($"Used: {string.Join(", ", usedKeys)}")
            .AppendLine($"Unused: {string.Join(", ", emailAttributes.Keys.Except(usedKeys))}")
            .AppendLine("-->");

            logger.LogWarning("Debug Email Output {File}", new Uri(saveAs));

            await File.WriteAllTextAsync(saveAs, content + debug, Encoding.UTF8);

            return(await result);
        }