private async Task SendRestorePasswordEmail(string requestId, ApplicationUser user)
        {
            var url = Url.Action("SetNewPassword", "RestorePassword", new { requestId }, "https");

            var subject     = "Восстановление пароля от ulearn.me";
            var textBody    = "Чтобы изменить пароль к аккаунту " + user.UserName + ", перейдите по ссылке: " + url + ".";
            var htmlBody    = "Чтобы изменить пароль к аккаунту " + user.UserName.EscapeHtml() + ", перейдите по ссылке: <a href=\"" + url + "\">" + url + "</a>.";
            var messageInfo = new MessageSentInfo
            {
                RecipientAddress = user.Email,
                Subject          = subject,
                Text             = textBody,
                Html             = htmlBody
            };

            log.Info($"Пытаюсь отправить емэйл на {user.Email} с темой «{subject}», text: {textBody.Replace("\n", @" \\ ")}");
            try
            {
                await spamClient.SentMessageAsync(spamChannelId, messageInfo);
            }
            catch (Exception e)
            {
                log.Error($"Не смог отправить емэйл через Spam.API на {user.Email} с темой «{subject}»", e);
                throw;
            }

            metricSender.SendCount("restore_password.send_email");
        }
Пример #2
0
        public async Task SendEmailAsync(string to, string subject, string textContent = null, string htmlContent = null, EmailButton button = null, string textContentAfterButton = null, string htmlContentAfterButton = null)
        {
            var recipientEmailMetricName = to.ToLower().Replace(".", "_");

            metricSender.SendCount("send_email.try");
            metricSender.SendCount($"send_email.try.to.{recipientEmailMetricName}");

            var messageInfo = new MessageSentInfo
            {
                RecipientAddress = to,
                Subject          = subject,
            };

            if (!string.IsNullOrEmpty(templateId))
            {
                messageInfo.TemplateId = templateId;
                messageInfo.Variables  = new Dictionary <string, object>
                {
                    { "title", subject },
                    { "content", htmlContent },
                    { "text_content", textContent },
                    { "button", button != null },
                    { "button_link", button?.Link },
                    { "button_text", button?.Text },
                    { "content_after_button", htmlContentAfterButton },
                    { "text_content_after_button", textContentAfterButton },
                };
            }
            else
            {
                messageInfo.Html = htmlContent;
                messageInfo.Text = textContent;
            }

            log.Info($"Try to send message to {to} with subject {subject}, text: {textContent?.Replace("\n", @" \\ ")}");
            try
            {
                await client.SentMessageAsync(channelId, messageInfo);
            }
            catch (Exception e)
            {
                log.Warn($"Can\'t send message via Spam.API to {to} with subject {subject}", e);
                metricSender.SendCount("send_email.fail");
                metricSender.SendCount($"send_email.fail.to.{recipientEmailMetricName}");
                throw;
            }

            metricSender.SendCount("send_email.success");
            metricSender.SendCount($"send_email.success.to.{recipientEmailMetricName}");
        }
Пример #3
0
        protected async Task <bool> SendConfirmationEmail(ApplicationUser user)
        {
            metricSender.SendCount("email_confirmation.send_confirmation_email.try");
            var confirmationUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, email = user.Email, signature = GetEmailConfirmationSignature(user.Email) }, "https");
            var subject         = "Подтверждение адреса";

            var messageInfo = new MessageSentInfo
            {
                RecipientAddress = user.Email,
                RecipientName    = user.VisibleName,
                Subject          = subject,
                TemplateId       = spamTemplateId,
                Variables        = new Dictionary <string, object>
                {
                    { "title", subject },
                    { "content", $"<h2>Привет, {user.VisibleName.EscapeHtml()}!</h2><p>Подтверди адрес электронной почты, нажав на кнопку:</p>" },
                    { "text_content", $"Привет, {user.VisibleName}!\nПодтверди адрес электронной почты, нажав на кнопку:" },
                    { "button", true },
                    { "button_link", confirmationUrl },
                    { "button_text", "Подтвердить адрес" },
                    {
                        "content_after_button",
                        "<p>Подтвердив адрес, ты сможешь восстановить доступ к своему аккаунту " +
                        "в любой момент, а также получать уведомления об ответах на свои комментарии и других важных событиях</p>" +
                        "<p>Мы не подпиcываем ни на какую периодическую рассылку, " +
                        "а все уведомления можно выключить в профиле.</p><p>" +
                        "Если ссылка для подтверждения почты не работает, просто скопируй адрес " +
                        $"и вставь его в адресную строку браузера: <a href=\"{confirmationUrl}\">{confirmationUrl}</a></p>"
                    }
                }
            };

            try
            {
                await spamClient.SentMessageAsync(spamChannelId, messageInfo).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                log.Error($"Не могу отправить письмо для подтверждения адреса на {user.Email}", e);
                return(false);
            }

            metricSender.SendCount("email_confirmation.send_confirmation_email.success");

            await usersRepo.UpdateLastConfirmationEmailTime(user).ConfigureAwait(false);

            return(true);
        }