コード例 #1
0
        public Task SendClientActivationEmailAsync(DomainPendingClient client)
        {
            if (string.IsNullOrEmpty(client.Email))
            {
                return(Task.FromResult(0));
            }

            var email = new SendEmailDomain
            {
                Address     = _settings.EmailAddressAlerts,
                DisplayName = Emails.SenderDisplayName,
                Emails      = new List <string> {
                    client.Email
                },
                Subject = Emails.SubjectRegistration,
                Body    = string.Format(
                    PortalResources.ClientActivation,
                    client.ContactPerson,
                    client.Email,
                    _settings.PortalUri,
                    client.Id)
            };

            // Send email on user registration
            return(_emailSenderService.SendEmailAsync(email));
        }
コード例 #2
0
        public async Task <IActionResult> SendRequestAsync([FromForm] RequestModel requestModel)
        {
            var requiredFields = new List <string> {
                "files", "email"
            };
            var dictionary = new Dictionary <string, string>();

            foreach (var field in Request.Form)
            {
                if (requiredFields.Contains(field.Key))
                {
                    continue;
                }
                dictionary.Add(field.Key, field.Value);
            }
            requestModel.CustomFields = dictionary;

            if (requestModel.Files.IsListNotNull())
            {
                var directoryPath      = Path.Combine(Environment.CurrentDirectory, "TempFiles");
                int maxFileSizeInBytes = Convert.ToInt32(configuration["maxFileSize"]);

                int count = 1;

                var pathes = new List <string>();

                foreach (var file in requestModel.Files)
                {
                    var photoType = file.FileName.Contains("png") ? ".png" : ".jpg";

                    if (file.Length > maxFileSizeInBytes)
                    {
                        continue;
                    }

                    var fullPath = Path.Combine(directoryPath, string.Format("temp{0}{1}", count, photoType));
                    if (System.IO.File.Exists(fullPath))
                    {
                        System.IO.File.Delete(fullPath);
                    }
                    await using (var fileStream = new FileStream(fullPath, FileMode.Create))
                    {
                        await file.CopyToAsync(fileStream);
                    }

                    pathes.Add(fullPath);
                    count++;
                }
                await emailSenderService.SendEmailAsync(requestModel, requestModel.Email, MailTempleteNames.RequestMailTemplateName, pathes);
            }
            else
            {
                await emailSenderService.SendEmailAsync(requestModel, requestModel.Email, MailTempleteNames.RequestMailTemplateName);
            }
            return(Ok());
        }
コード例 #3
0
        public async Task <Result> ChangeRoleAsync(string idFromIdentity, CancellationToken cancellationToken = default)
        {
            var userIdentity = await _userManager.FindByIdAsync(idFromIdentity);

            if (userIdentity == null)
            {
                return(await Task.FromResult(Result.Fail(ExceptionConstants.USER_WAS_NOT_FOUND)));
            }
            try
            {
                if (await _userManager.IsInRoleAsync(userIdentity, AppIdentityConstants.USER))
                {
                    userIdentity.Role = AppIdentityConstants.ADMIN;
                    await _userManager.UpdateAsync(userIdentity);

                    await _userManager.AddToRoleAsync(userIdentity, AppIdentityConstants.ADMIN);

                    await _userManager.RemoveFromRoleAsync(userIdentity, AppIdentityConstants.USER);

                    var result = await _emailSender.SendEmailAsync(userIdentity.Email, EmailConstants.ROLE_SUBJECT, EmailConstants.ROLE_MESSAGE_FOR_ADMIN, cancellationToken);

                    if (result.IsError)
                    {
                        return(Result.Quite(NotificationConstans.SOMETHING_WRONG_WITH_EMAIL + result.Message));
                    }
                    return(await Task.FromResult(Result.Ok()));
                }
                else if (await _userManager.IsInRoleAsync(userIdentity, AppIdentityConstants.ADMIN))
                {
                    userIdentity.Role = AppIdentityConstants.USER;
                    await _userManager.UpdateAsync(userIdentity);

                    await _userManager.AddToRoleAsync(userIdentity, AppIdentityConstants.USER);

                    await _userManager.RemoveFromRoleAsync(userIdentity, AppIdentityConstants.ADMIN);

                    var result = await _emailSender.SendEmailAsync(userIdentity.Email, EmailConstants.ROLE_SUBJECT, EmailConstants.ROLE_MESSAGE_FOR_USER, cancellationToken);

                    if (result.IsError)
                    {
                        return(Result.Quite(NotificationConstans.SOMETHING_WRONG_WITH_EMAIL + result.Message));
                    }
                    return(await Task.FromResult(Result.Ok()));
                }
                return(await Task.FromResult(Result.Quite(NotificationConstans.SOMETHING_WRONG_WITH_ROLES)));
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(await Task.FromResult(Result.Fail(ExceptionConstants.CANNOT_CHANGE_ROLE + ex.Message)));
            }
            catch (DbUpdateException ex)
            {
                return(await Task.FromResult(Result.Fail(ExceptionConstants.CANNOT_CHANGE_ROLE + ex.Message)));
            }
        }
コード例 #4
0
        private async Task SendMessageEmail(ApplicationUser userFrom, ApplicationUser userTo)
        {
            var code = "";

            if (!string.IsNullOrEmpty(userFrom.PinDigit))
            {
                code = userFrom.PinDigit;
            }
            else
            {
                code = userFrom.Id;
            }

            var callbackUrl = $"{Request.Scheme}://{Request.Host}/viewProfile/{code}";

            var frontWebSite   = UriHelper.BuildAbsolute(Request.Scheme, Request.Host);
            var logoUrl        = UriHelper.BuildAbsolute(Request.Scheme, Request.Host, "/assets/img/logo_full.png");
            var unSubscribeUrl = UriHelper.BuildAbsolute(Request.Scheme, Request.Host, "/Account/UnSubscribe");
            var login          = $"{userFrom.DisplayName}";

            var parameters = new Dictionary <string, string>()
            {
                { "login", login },
                { "frontWebSite", frontWebSite },
                { "logoUrl", logoUrl },
                { "unSubscribeUrl", unSubscribeUrl },
                { "callbackUrl", callbackUrl },
                { "userFrom", userFrom.DisplayName }
            };

            var html = GenerateHtmlTemplate(_serviceProvider, _env.WebRootPath, EmailTemplateEnum.MessageReceived, parameters);
            await _emailSender.SendEmailAsync(userTo.Email, $"{userFrom.DisplayName} vous a envoyé un message sur meetag.co", html);
        }
コード例 #5
0
        public async Task <IActionResult> GenerateNewPasswordLink([FromBody] ResetPasswordViewModel model)
        {
            var user = await UserManager.FindByEmailAsync(model.Email);

            if (user != null)
            {
                string code = await UserManager.GeneratePasswordResetTokenAsync(user);

                code = HttpUtility.UrlEncode(code).Replace("%", "-");

                var culture     = Thread.CurrentThread.CurrentUICulture;
                var mailContent = FileService.LoadFile(@"Mail\ResetPasswordMail.html", culture);

                if (mailContent != null)
                {
                    var url = _configuration["AppPath"] + "/password/" + code;
#if DEBUG
                    url = _configuration["DebugAppPath"] + "/password/" + code;
#endif
                    var filledContent = mailContent.Replace("{0}", url).Replace("{1}", user.UserName);
                    EmailSenderService.SendEmailAsync(model.Email, _localizer["FORGOTTEN_PASSWORD"], filledContent).Wait();
                }
            }
            return(Ok());
        }
        public async Task <IActionResult> SendCode(SendCodeViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();

            if (user == null)
            {
                return(View("Error"));
            }

            // Generate the token and send it
            var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);

            if (string.IsNullOrWhiteSpace(code))
            {
                return(View("Error"));
            }

            var message = "Your security code is: " + code;

            if (model.SelectedProvider == "Email")
            {
                await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message);
            }
            else if (model.SelectedProvider == "Phone")
            {
                await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message);
            }

            return(RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }));
        }
コード例 #7
0
        private async Task SendMailToClient(string emailTo, string name, string attach, string mailTemplateId)
        {
            var attachs = new List <string>();

            if (!string.IsNullOrEmpty(attach))
            {
                attachs.Add(attach);
            }
            ;
            name = name ?? emailTo;

            var mailTemplate = await _mailTemplateService.GetByIdAsync(mailTemplateId);

            var subject = "Mensaje de notificación";
            var message = $"<div><p>Hola {name}</p><p>¡Gracias por tu interés en Grupo PerTI!</p><p></p>Nos pondremos en contacto contigo lo más pronto posible.<div>";

            if (mailTemplate != null)
            {
                subject = mailTemplate.Subject;
                message = SetTemplate(mailTemplate, name, true);
            }

            try
            {
                await _emailSenderService.SendEmailAsync(emailTo, subject, message, attachs);
            }
            catch (Exception ex)
            {
                LoggerService.LogToFile(ex);
            }
        }
コード例 #8
0
        public async Task <Result> SendConfirmMessage(AppUser user, string callBackUrl, CancellationToken cancellationToken = default)
        {
            var t = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            var token = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(t));

            var emailForSending = user.Email;

            var subject = EmailConstants.CONFIRM_SUBJECT;

            var finalUrl = callBackUrl + $"?userId={user.Id}&token={token}";

            var message = $"{EmailConstants.CONFIRM_MESSAGE_PART_BEFORE_URL}, <a href='{finalUrl}'>{EmailConstants.CONFIRM_MESSAGE_URL_TEXT}</a> {EmailConstants.CONFIRM_MESSAGE_PART_AFTER_URL}";

            return(await _emailSender.SendEmailAsync(emailForSending, subject, message, cancellationToken));
        }
コード例 #9
0
        private async Task SendEmailTemplate(Shared.Functional.AdModel ad, EmailTemplateEnum emailType, string callbackUrl)
        {
            _logger.LogInformation($"send email {emailType} to user {ad.OwnerId}");

            var frontWebSite   = _configuration["Service:FrontOffice:Url"];
            var logoUrl        = $"{frontWebSite.TrimEnd('/')}/assets/img/logo_full.png";
            var unSubscribeUrl = $"{frontWebSite.TrimEnd('/')}/Account/UnSubscribe";

            var parameters = new Dictionary <string, string>()
            {
                { "title", ad.Title },
                { "frontWebSite", frontWebSite },
                { "logoUrl", logoUrl },
                { "unSubscribeUrl", unSubscribeUrl },
                { "callbackUrl", callbackUrl }
            };

            if (emailType == EmailTemplateEnum.AdEndPublished)
            {
                parameters.Add("EndPublishingDate", ad.EndDisplayTime.Value.ToLongDateString());
                parameters.Add("ViewCount", ad.ViewCount.ToString());
            }

            var message = GenerateHtmlTemplate(_serviceProvider, _env.WebRootPath, emailType, parameters);
            var user    = await _userManager.FindByIdAsync(ad.OwnerId);

            await _emailSender.SendEmailAsync(user.Email, ad.Title, message);
        }
コード例 #10
0
        public async Task <IActionResult> Registration(RegistrationView registrationView)
        {
            if (ModelState.IsValid)
            {
                var item   = mapper.Map <RegistrationView, IUserInfo>(registrationView);
                var result = await userService.AddUserAsync(item);

                if (result.Succeeded)
                {
                    var token = await userService.GetUserTokenAsync(item);


                    var callbackUrl = Url.Action(
                        "ConfirmEmail",
                        "user",
                        new { item.Email, token },
                        protocol: HttpContext.Request.Scheme);

                    var message = string.Format("Для завершения регистрации перейдите по ссылке:" +
                                                "<a href=\"{0}\" title=\"Подтвердить регистрацию\">{0}</a>", callbackUrl);

                    await emailSenderService.SendEmailAsync(item.Email, "Registration TwitNew", message);

                    return(RedirectToAction("Confirm", "User", new { message = "send confirmed message" }));
                }
                else
                {
                    AddErrors(result);
                }
            }
            return(View(registrationView));
        }
コード例 #11
0
        public async Task <ActionResult> PostFeedback(FeedbackModel model)
        {
            var email = new SendEmailDomain
            {
                Address = model.Email,
                UserId  = UserId,
                Body    = model.Message,
                Emails  = new List <string> {
                    _settings.EmailAddressSupport
                },
                Subject = Emails.SubjectFeedback
            };

            if (!ModelState.IsValid)
            {
                return(View("Feedback"));
            }

            try
            {
                await _emailSenderService.SendEmailAsync(email);
            }
            catch (Exception)
            {
                return(View(new FeedbackResultModel {
                    Status = FeedbackStatus.Error
                }));
            }

            return(View(new FeedbackResultModel {
                Status = FeedbackStatus.Success
            }));
        }
コード例 #12
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(model.Email);

                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(RedirectToAction(nameof(ForgotPasswordConfirmation)));
                }

                // For more information on how to enable account confirmation and password reset please
                // visit https://go.microsoft.com/fwlink/?LinkID=532713
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                var callbackUrl = Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme);
                await _emailSender.SendEmailAsync(model.Email, "Reset Password",
                                                  $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");

                return(RedirectToAction(nameof(ForgotPasswordConfirmation)));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #13
0
        public async Task <BaseModel> SendCommunityGroupPublishEmailAsync(long Id, string EmailTemplateBody, string callbackUrl)
        {
            try
            {
                var _data = await _unitOfWork.UserCommunityGroupsRepository.GetByID(Id);

                if (_data != null)
                {
                    string token = Guid.NewGuid().ToString().Replace("-", "");
                    UserCommunityGroupPublishLinksDataModel model = new UserCommunityGroupPublishLinksDataModel()
                    {
                        CommunityGroupId = Id,
                        VerificationCode = token,
                        CreatedDate      = DateTime.UtcNow,
                        IsPublished      = false
                    };
                    await _unitOfWork.CommunityGroupPublishLinksRepository.Insert(model);

                    string messageBody = string.Format(EmailTemplateBody,
                                                       _data.Title,
                                                       UMessagesInfo.AWSPublicURL + _data.DescriptionVideoUrl,
                                                       _data.Description,
                                                       callbackUrl + token
                                                       );
                    await _emailSender.SendEmailAsync(
                        UMessagesInfo.NewCommunityGroupEmailSubject,
                        messageBody,
                        _sphixConfiguration.SuperAdminEmail,
                        _sphixConfiguration.SupportEmail,
                        UMessagesInfo.SphixSupport
                        );

                    return(new BaseModel {
                        Status = true, Messsage = UMessagesInfo.EmailSent
                    });
                }
                return(new BaseModel {
                    Status = false, Messsage = UMessagesInfo.Error
                });
            }
            catch (Exception)
            {
                return(new BaseModel {
                    Status = false, Messsage = UMessagesInfo.Error
                });
            }
        }
コード例 #14
0
        public async Task <bool> SendEmail(string email, string url, string code)
        {
            url = url + "?email=" + email + "&code=" + code;
            await _emailSender.SendEmailAsync(email, "Invitation",
                                              $"You have been invited. Please register by clicking this link: <a href='{url}'>link</a>");

            return(true);
        }
コード例 #15
0
 public static Task SendEmailConfirmationAsync(this IEmailSenderService emailSender, string email, string link)
 {
     return(emailSender
            .SendEmailAsync(
                email,
                "Your registration is almost complete!",
                "<h2>Thanks for signing up for Mp3MusicZone!</h2>" +
                $"<h4>Please verify your account by clicking the link below: <a href='{HtmlEncoder.Default.Encode(link)}'>{HtmlEncoder.Default.Encode(link)}</a></h4>"));
 }
コード例 #16
0
ファイル: ProfileManager.cs プロジェクト: ForNeVeR/SunEngine
        public virtual Task SendPrivateMessageAsync(User from, User to, string text)
        {
            var header =
                $"<div>Вам написал: <a href='{globalOptions.SiteUrl.AppendPathSegment("user/" + from.Link)}'>{from.UserName}</a></div><br/>";

            text = sanitizer.Sanitize(header + text);
            string subject = $"Сообщение от {to.UserName} с сайта {globalOptions.SiteName}";

            return(EmailSenderService.SendEmailAsync(to.Email, subject, text));
        }
コード例 #17
0
        public async Task <BaseModel> SendMailOnCreateNewTableAsync(long userId, string token, string callBackLink, string emailTemplateBody, string meetingDateAndTime)
        {
            try
            {
                var _data = await _unitOfWork.UserProfileRepository.FindAllBy(c => c.User.Id == userId);

                if (_data != null)
                {
                    if (string.IsNullOrEmpty(_data[0].Email))
                    {
                        return(new BaseModel {
                            Status = false, Messsage = UMessagesInfo.Error
                        });
                    }
                    string messageBody = string.Format(emailTemplateBody,
                                                       _data[0].FirstName,
                                                       meetingDateAndTime,
                                                       callBackLink,
                                                       UMessagesInfo.MailFooter
                                                       );
                    await _emailSender.SendEmailAsync(
                        "Open Office Hours Meeting",
                        messageBody,
                        _data[0].Email,
                        _sphixConfiguration.SupportEmail,
                        UMessagesInfo.SphixSupport
                        );

                    return(new BaseModel {
                        Status = true, Messsage = UMessagesInfo.EmailSent
                    });
                }
                return(new BaseModel {
                    Status = false, Messsage = UMessagesInfo.Error
                });
            }
            catch (Exception)
            {
                return(new BaseModel {
                    Status = false, Messsage = UMessagesInfo.Error
                });
            }
        }
コード例 #18
0
        /// <summary>
        /// 发送邮件随机验证码
        /// </summary>
        /// <param name="emailSender"></param>
        /// <param name="email"></param>
        /// <param name="min"></param>
        /// <param name="max"></param>
        /// <returns></returns>
        public static async Task <(IEmailSendedResual, int)> SendEmailRandomCodeAsync(this IEmailSenderService emailSender, string email, int min = 100000, int max = 999999)
        {
#if !DEBUG
            var code = new Random().Next(min, max);
            return(await emailSender.SendEmailAsync(email, "你的邮件验证码", $"你的账号邮件验证码为:{code},请注意保密哦!"), code);
#else
            var res = new EmailSendedResual(HttpStatusCode.OK, null, null);
            return(await Task.FromResult((res, 197238)));
#endif
        }
コード例 #19
0
        public virtual async Task <ServiceResult> RegisterAsync(NewUserArgs model)
        {
            var user = new User
            {
                UserName = model.UserName,
                Email    = model.Email,
                Avatar   = User.DefaultAvatar,
                Photo    = User.DefaultAvatar
            };

            using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                IdentityResult result = await userManager.CreateAsync(user, model.Password);

                await db.Users.Where(x => x.Id == user.Id).Set(x => x.Link, x => x.Id.ToString()).UpdateAsync();

                if (!result.Succeeded)
                {
                    return(ServiceResult.BadResult(new ErrorView(result.Errors)));
                }

                logger.LogInformation($"New user registered (id: {user.Id})");

                if (!user.EmailConfirmed)
                {
                    // Send email confirmation email
                    var confirmToken = await userManager.GenerateEmailConfirmationTokenAsync(user);

                    var emailConfirmUrl = globalOptions.SiteApi.AppendPathSegments("Auth", "ConfirmRegister")
                                          .SetQueryParams(new { uid = user.Id, token = confirmToken });

                    try
                    {
                        await EmailSenderService.SendEmailAsync(model.Email, "Please confirm your account",
                                                                $"Please confirm your account by clicking this <a href=\"{emailConfirmUrl}\">link</a>."
                                                                );
                    }
                    catch (Exception exception)
                    {
                        return(ServiceResult.BadResult(
                                   new ErrorView("EmailSendError", "Can not send email", exception)));
                    }


                    logger.LogInformation($"Sent email confirmation email (id: {user.Id})");
                }

                logger.LogInformation($"User logged in (id: {user.Id})");

                transaction.Complete();

                return(ServiceResult.OkResult());
            }
        }
コード例 #20
0
        private async Task SendForgotPasswordToken(UserEf user)
        {
            string code = await this.userService.GeneratePasswordResetTokenAsync(user);

            string callbackUrl =
                Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme);

            callbackUrl += $"&email={user.Email}";

            await emailSender.SendEmailAsync(user.Email, "Reset Password",
                                             $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");
        }
コード例 #21
0
ファイル: AccountManager.cs プロジェクト: ForNeVeR/SunEngine
        public virtual async Task <ServiceResult> ResetPasswordSendEmailAsync(User user)
        {
            var resetToken = await userManager.GeneratePasswordResetTokenAsync(user);

            var resetPasswordUrl = globalOptions.SiteApi
                                   .AppendPathSegments("Account", "ResetPasswordShowClientDialog")
                                   .SetQueryParams(new { uid = user.Id, token = resetToken });

            try
            {
                await EmailSenderService.SendEmailAsync(user.Email, "You can reset your password",
                                                        $"Reset password by clicking this <a href=\"{resetPasswordUrl}\">link</a>."
                                                        );
            }
            catch (Exception)
            {
                ServiceResult.BadResult(new ErrorView("EmailSendError", "Server error. Can not send email."));
            }

            return(ServiceResult.OkResult());
        }
コード例 #22
0
        private async Task SendEmailTemplate(AdModel adModel)
        {
            var callbackUrl = $"{Request.Scheme}://{Request.Host}/ads/details/{adModel.Id}";

            var frontWebSite   = UriHelper.BuildAbsolute(Request.Scheme, Request.Host);
            var logoUrl        = UriHelper.BuildAbsolute(Request.Scheme, Request.Host, "/assets/img/logo_full.png");
            var unSubscribeUrl = UriHelper.BuildAbsolute(Request.Scheme, Request.Host, "/Account/UnSubscribe");

            var parameters = new Dictionary <string, string>()
            {
                { "title", adModel.Title },
                { "frontWebSite", frontWebSite },
                { "logoUrl", logoUrl },
                { "unSubscribeUrl", unSubscribeUrl },
                { "callbackUrl", callbackUrl }
            };

            var message = GenerateHtmlTemplate(_serviceProvider, _env.WebRootPath, EmailTemplateEnum.AdValidated, parameters);
            var user    = await _userManager.FindByIdAsync(adModel.OwnerId);

            await _emailSender.SendEmailAsync(user.Email, adModel.Title, message);
        }
コード例 #23
0
        public async Task <IActionResult> Restore(UserRestoreRequest user)
        {
            var result = dbContext.Users.FirstOrDefault(u => u.Email.Equals(user.Email));

            if (result != null)
            {
                var hash = hashService.GetRandom();
                dbContext.PasswordRestores.Add(new PasswordRestore
                {
                    UserId  = result.Id,
                    Restore = hash,
                    Valid   = true,
                });
                await dbContext.SaveChangesAsync();

                await sender.SendEmailAsync(result.Username, result.Email,
                                            $"Someone tries to reset your password on CTOX.\nIf it were you, please follow the link https://localhost:5001/Reset/{hash}");
            }

            ViewData["info-message"] = RestoreInfoMessage;
            return(View("Login"));
        }
コード例 #24
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel data)
        {
            ViewData["Email"] = data.Email;

            if (!ModelState.IsValid)
            {
                return(PartialView(data));
            }

            if (!_emailValidatorService.IsValidEmail(data.Email))
            {
                ModelState.AddModelError("InvalidEmail", _localizer[AuthenticationErrorMessages.InvalidEmail]);
                return(PartialView(data));
            }

            var userSpecification = new UserSpecification()
            {
                Email = data.Email
            };

            AuthenticationUser = await _userRepository.ReadAsync(userSpecification);

            if (AuthenticationUser is null)
            {
                ModelState.AddModelError("UserDoesNotExist", _localizer[AuthenticationErrorMessages.UserDoesNotExist]);
                return(PartialView(data));
            }

            string token     = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
            var    userDTO   = new UserDTO(AuthenticationUser);
            var    saveToken = await _userPasswordRepository.SavePasswordTokenAsync(userDTO, token);

            if (!saveToken)
            {
                ModelState.AddModelError("ReminderFailed", _localizer[AuthenticationErrorMessages.PasswordReminderFailed]);
                return(PartialView(data));
            }

            var domain = Request.Host.Value;

            domain += (Request.PathBase.Value.HasValue()) ? Request.PathBase.Value : string.Empty;
            var emailSubject = _forgotPasswordEmail.Subject();
            var emailBody    = _forgotPasswordEmail.Body(AuthenticationUser, domain, emailSubject, token);

            await _emailSenderService.SendEmailAsync(data.Email, emailSubject, emailBody);

            data.SendReminderSuccess = true;

            return(PartialView(data));
        }
コード例 #25
0
        public async Task SendRegistrationNotification(SendEmailRequest sendEmailRequest)
        {
            //валидация
            User user = await m_context.Users.SingleOrDefaultAsync(x => x.Name == sendEmailRequest.ReceiverName);

            if (user != null)
            {
                throw new UserNotFound($"Пользователь {sendEmailRequest.ReceiverName} не найден");
            }

            await m_emailSenderService.SendEmailAsync(sendEmailRequest, m_senderConfig);

            if (await m_context.TemporaryUsers.SingleOrDefaultAsync(x => x.Name == sendEmailRequest.ReceiverName) == null)
            {
                await m_context.TemporaryUsers.AddAsync(new TemporaryUser
                {
                    Name  = sendEmailRequest.ReceiverName,
                    Email = sendEmailRequest.ReceiverEmail
                });
            }

            await m_context.SaveChangesAsync();
        }
コード例 #26
0
        private async Task <bool> SendEmailAsync(EmailRequest emailRequest)
        {
            try
            {
                await _emailSenderService.SendEmailAsync(emailRequest);

                return(true);
            }
            catch (Exception e)
            {
                //TODO log error
                return(false);
            }
        }
コード例 #27
0
        private async Task SendInvitationEmailTemplate(ApplicationUser user)
        {
            string data1 = CryptHelper.Rijndael.Encrypt($"{user.Id}", _configuration["QrCode:Key"]);
            string data2 = CryptHelper.Rijndael.Encrypt($"{User.NameIdentifier()}", _configuration["QrCode:Key"]);

            var callbackUrl = $"{Request.Scheme}://{Request.Host}/Identity/Account/ConfirmContact?data1={data1}&data2={data2}";

            var frontWebSite   = UriHelper.BuildAbsolute(Request.Scheme, Request.Host);
            var logoUrl        = UriHelper.BuildAbsolute(Request.Scheme, Request.Host, "/assets/img/logo_full.png");
            var unSubscribeUrl = UriHelper.BuildAbsolute(Request.Scheme, Request.Host, "/Account/UnSubscribe");
            var login          = $"{user.DisplayName}";

            var parameters = new Dictionary <string, string>()
            {
                { "login", login },
                { "frontWebSite", frontWebSite },
                { "logoUrl", logoUrl },
                { "unSubscribeUrl", unSubscribeUrl },
                { "callbackUrl", callbackUrl }
            };

            var message = GenerateHtmlTemplate(_serviceProvider, _env.WebRootPath, EmailTemplateEnum.ContactInvitationAdded, parameters);
            await _emailSender.SendEmailAsync(user.Email, "Add Contact", message);
        }
コード例 #28
0
        private async Task <IActionResult> SendConfirmationEmail(AppUser user, bool isResend)
        {
            // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
            // Send an email with this link
            var originalCode = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            var code = WebUtility.UrlEncode(originalCode);

            var urlBuilder =
                new System.UriBuilder(_configuration["SiteUrl"])
            {
                Path  = Url.Content("~/account/confirm-email"),
                Query = "userId=" + user.Id + "&code=" + code
            };
            var callbackUrl = urlBuilder.ToString();

            callbackUrl = HtmlEncoder.Default.Encode(callbackUrl);

            string confirmText = @"Hi,<br /><br />" +
                                 "Thank you for registering an account on our site.<br /><br />" +
                                 "Please confirm your email address by clicking here:<br /><br />" +
                                 "<a href='" + callbackUrl + "'>Confirm Email</a><br /><br />" +
                                 "If you didn't register for this account, please ignore and delete this message.<br /><br />" +
                                 "Thank you.<br /><br />" +
                                 "Site Admin<br /><br />";

            if (isResend)
            {
                confirmText += "(This is confirmation email has been resent upon request.)";
            }

            var response = await _emailSender.SendEmailAsync(user.Email, "Confirm your account",
                                                             confirmText);

            return(new OkObjectResult(null));
        }
コード例 #29
0
        public async Task Handle(UserInvitation notification, CancellationToken cancellationToken)
        {
            var token  = Convert.ToBase64String(Guid.NewGuid().ToByteArray());
            var domain = _urlProvider.GetBaseUrl();
            var createPasswordToken = await _userPasswordRepository.CreatePasswordTokenAsync(notification.User, token);

            if (!createPasswordToken)
            {
                return;
            }

            var emailSubject = _userInvitationEmail.Subject();
            var emailBody    = _userInvitationEmail.Body(notification.User, domain, emailSubject, token);
            await _emailSenderService.SendEmailAsync(notification.User.Email, emailSubject, emailBody);
        }
コード例 #30
0
        // POST /api/email
        public async Task <HttpResponseMessage> Post(SendEmailModel sendEmailModel)
        {
            var email = new SendEmailDomain
            {
                Address     = _settings.EmailAddressInfo,
                DisplayName = Emails.SenderDisplayName,
                UserId      = UserId,
                Body        = sendEmailModel.Body,
                Emails      = sendEmailModel.Emails,
                Subject     = sendEmailModel.Subject
            };

            await _emailSender.SendEmailAsync(email);

            return(Request.CreateResponse(HttpStatusCode.OK));
        }