コード例 #1
0
ファイル: EmailService.cs プロジェクト: dmptrluke/FurCoNZ
        public async Task SendOrderCancelledNotificationAsync(Order order, CancellationToken cancellationToken = default)
        {
            var viewModel = new OrderExpiredNotificationViewModel
            {
                Id        = order.Id,
                CreatedAt = order.CreatedAt,
                Name      = order.OrderedBy.Name,
                Email     = order.OrderedBy.Email,
            };

            // Gather metadata
            var toAddresses = new MailAddressCollection
            {
                new MailAddress(viewModel.Email, viewModel.Name),
            };

            // Prepare template
            var message = await _viewRenderService.RenderToStringAsync("EmailTemplate/ExpiredOrder", viewModel, cancellationToken : cancellationToken);

            var subject = message.ViewData.ContainsKey("Subject")
                ? message.ViewData["Subject"] as string
                : $"Order #{viewModel.Id} has expired";

            // Send message
            await _emailProvider.SendEmailAsync(toAddresses, subject, message.Output, cancellationToken : cancellationToken);
        }
コード例 #2
0
ファイル: UserService.cs プロジェクト: Esusbek/EducationApp
        public async Task RegisterAsync(UserModel user)
        {
            _validator.ValidateUser(user);
            var newUser = _mapper.Map <UserEntity>(user);
            var dbUser  = await _userManager.FindByNameAsync(user.UserName);

            if (dbUser is not null)
            {
                throw new CustomApiException(HttpStatusCode.Conflict, Constants.USERNAMETAKENERROR);
            }
            dbUser = await _userManager.FindByEmailAsync(user.Email);

            if (dbUser is not null)
            {
                throw new CustomApiException(HttpStatusCode.Conflict, Constants.EMAILTAKENERROR);
            }
            var result = await _userManager.CreateAsync(newUser, user.Password);

            if (!result.Succeeded)
            {
                throw new CustomApiException(HttpStatusCode.Conflict, Constants.FAILEDTOCREATEUSERERROR);
            }
            result = await _userManager.AddToRoleAsync(newUser, Enums.UserRolesType.Client.ToString());

            if (!result.Succeeded)
            {
                await _userManager.DeleteAsync(newUser);

                throw new CustomApiException(HttpStatusCode.Conflict, Constants.FAILEDTOCREATEUSERERROR);
            }
            string code = await _userManager.GenerateEmailConfirmationTokenAsync(newUser);

            var uriBuilder = new UriBuilder
            {
                Scheme = _urlConfig.Scheme,
                Port   = _urlConfig.Port,
                Host   = _urlConfig.Host,
                Path   = Constants.CONFIRMEMAILPATH
            };
            var query = HttpUtility.ParseQueryString(uriBuilder.Query);

            query[Constants.USERIDKEY] = newUser.Id;
            query[Constants.CODEKEY]   = code;
            uriBuilder.Query           = query.ToString();
            string callbackUrl = uriBuilder.ToString();
            await _email.SendEmailAsync(new MailAddress(newUser.Email),
                                        Constants.DEFAULTEMAILCONFIRMATION,
                                        string.Format(Constants.DEFAULTEMAILCONFIRMATIONBODY, callbackUrl));
        }
コード例 #3
0
        public static async Task ProcessMailAsync([QueueTrigger(QueueStore.NEW_MAIL)] CloudQueueMessage message, [Queue(QueueStore.NEW_MAIL)] CloudQueue nextQueue)
        {
            Console.WriteLine($"Started {QueueStore.NEW_MAIL}: {DateTime.UtcNow.ToLocalString()}");
            var msg = message.GetBaseQueueMessage();

            try
            {
                await _emailProvider.SendEmailAsync(msg.DeserializeData <MailQueueMessage>());
            }
            catch (Exception e)
            {
                Console.WriteLine($"Exception {QueueStore.NEW_MAIL}: {DateTime.UtcNow.ToLocalString()}, Retry {msg.RetryNext}: {e.Message}");
                if (!msg.RetryNext)
                {
                    // if a message is catched here then we inform the admin.
                    await _exceptionHandler.ProcessExceptionAsync(QueueStore.NEW_MAIL, e);

                    throw;
                }

                await nextQueue.AddMessageAsync(
                    CloudQueueMessage.CreateCloudQueueMessageFromByteArray(
                        msg.NextMessage.AsBytes()
                        ),
                    null,
                    TimeSpan.FromSeconds(msg.NextMessage.TriggerDelay),
                    new QueueRequestOptions(),
                    new OperationContext()
                    );
            }
            finally
            {
                Console.WriteLine($"Finished {QueueStore.NEW_MAIL}: {DateTime.UtcNow.ToLocalString()}");
            }
        }
コード例 #4
0
ファイル: UserService.cs プロジェクト: ByrkoAnton/Store
        public async Task <string> ForgotPasswordAsync(ForgotPasswordModel forgotPasswordModel)
        {
            var user = await _userManager.FindByEmailAsync(forgotPasswordModel.Email);

            if (user is null)
            {
                throw new CustomExeption(Constants.Error.PASSWORD_RESET_FAILD_NO_USER_WITH_THIS_EMAIL,
                                         StatusCodes.Status400BadRequest);
            }

            if (!await _userManager.IsEmailConfirmedAsync(user))
            {
                throw new CustomExeption(Constants.Error.PASSWORD_RESET_FAILD_NO_USER_WITH_THIS_EMAIL,
                                         StatusCodes.Status400BadRequest);
            }

            var code = await _userManager.GeneratePasswordResetTokenAsync(user);

            string newPassword = _randomPasswordGenerator.GenerateRandomPassword();
            var    result      = await _userManager.ResetPasswordAsync(user, code, newPassword);

            if (!result.Succeeded)
            {
                throw new Exception(Constants.Error.PASSWORD_RESET_FAILD_CONTACT_ADMIN);
            }

            await _emailService.SendEmailAsync(user.Email, "reset password",
                                               $"new password is {newPassword}");

            return("check your email");
        }
コード例 #5
0
 private async Task SendPasswordChangeAsync(ForgotPasswordModel criterias, ApplicationUser user, string token)
 {
     var activeUserUrl = $"{_resetPasswordSettings.Url}/{criterias.Email}/{token}";
     await _emailSender.SendEmailAsync(new MailMessageRequest()
     {
         Body      = string.Format(MailTemplateResources.USER_CHANGE_PASWORD_CONFIRMATION_BODY, user.DisplayName, _appSettings.ApplicationName, activeUserUrl),
         FromEmail = _resetPasswordSettings.FromEmail,
         FromName  = _resetPasswordSettings.FromName,
         ToEmail   = user.Email,
         ToName    = user.DisplayName,
         Subject   = string.Format(MailTemplateResources.USER_CHANGE_PASWORD_CONFIRMATION_SUBJECT, _appSettings.ApplicationName),
     }, EmailTextFormat.Html);
 }
コード例 #6
0
 private async Task SendActiveEmailAsync(ApplicationUser user, string confirmationToken)
 {
     var activeUserUrl = $"{_registerConfirmationSettings.Url}/{user.Email}/{confirmationToken}";
     await _emailSender.SendEmailAsync(new MailMessageRequest()
     {
         Body      = string.Format(MailTemplateResources.USER_CONFIRMATION_BODY, user.DisplayName, _appSettings.ApplicationName, activeUserUrl),
         FromEmail = _registerConfirmationSettings.FromEmail,
         FromName  = _registerConfirmationSettings.FromName,
         ToEmail   = user.Email,
         ToName    = user.DisplayName,
         Subject   = string.Format(MailTemplateResources.USER_CONFIRMATION_SUBJECT, _appSettings.ApplicationName),
     }, EmailTextFormat.Html);
 }
コード例 #7
0
        public static void NotificationReceived(string notificationJson)
        {
            //Use signalR to send the message to browser
            notificationJson = notificationJson.Replace("\"", "");
            var notification = JsonConvert.DeserializeObject <Notification>(notificationJson);

            IEmailProvider.SendEmailAsync(new Email {
                Subject    = (notification.IsSuccess ? "The booking has successfully placed" : "The booking has been rejected") + "-" + ServiceContext.NodeContext.NodeName,
                Message    = notification.Description,
                Recipients = new List <string> {
                    "*****@*****.**"
                }
            });
        }
コード例 #8
0
ファイル: AccountService.cs プロジェクト: ByrkoAnton/Store
        public async Task <string> SignUpAsync(UserModel signUpModel)
        {
            var EmailCheck = await _userManager.FindByEmailAsync(signUpModel.Email);

            if (EmailCheck != null)
            {
                throw new CustomExeption(Constants.Error.REGISRATION_FAILD_THIS_EMAIL_IS_ALREADY_IN_USE,
                                         StatusCodes.Status400BadRequest);
            }

            User user = new User
            {
                UserName  = signUpModel.Email,
                Email     = signUpModel.Email,
                FirstName = signUpModel.FirstName,
                LastName  = signUpModel.LastName
            };

            IdentityResult result = await _userManager.CreateAsync(user, signUpModel.Password);

            if (!result.Succeeded)
            {
                throw new CustomExeption(Constants.Error.REGISRATION_FAILD_USER_DID_NOT_CREATED,
                                         StatusCodes.Status400BadRequest);
            }

            var addToRoleResult = await _userManager.AddToRoleAsync(user, "user");

            if (!addToRoleResult.Succeeded)
            {
                throw new CustomExeption(Constants.Error.USER_ROLE_DID_NOT_ADDED,
                                         StatusCodes.Status400BadRequest);
            }

            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            var callbackUrl = new UriBuilder(Constants.URLs.URL_CONFIRMEMAIL);
            var parameters  = HttpUtility.ParseQueryString(string.Empty);

            parameters.Add("email", user.Email);
            parameters.Add("code", code);
            callbackUrl.Query = parameters.ToString();
            Uri finalUrl = callbackUrl.Uri;

            await _emailService.SendEmailAsync(user.Email, "confirm email",
                                               $"Confirm registration, go to : <a href='{finalUrl}'>link</a>");

            return("regisrtation success. confirm your email");
        }
コード例 #9
0
ファイル: EmailHelper.cs プロジェクト: subuch/MailProviders
        public async Task <HttpStatusCode> SendEmailHelper(object item, Email datamodel)
        {
            IEmailProvider emailProdvider = EmailFactory.getEmailInstance((EmailEnum)Enum.Parse(typeof(EmailEnum), item.ToString()));

            responseMessage = await emailProdvider.SendEmailAsync(datamodel);

            if (responseMessage.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception(responseData);
            }
            else
            {
                return(HttpStatusCode.OK);
            }
        }
コード例 #10
0
        public async Task <OperationResult> SendNotificationEmail(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return(new OperationResult(false, "Notification ID not identified"));
            }
            var notification = GetNotification(id);

            if (notification.Data != null)
            {
                if (notification.Data.Sent)
                {
                    await DeQueueNotificationMessage(notification.Data.Id); return(new OperationResult(true));
                }

                var task   = GetTask(notification.Data.TaskId);
                var status = task?.Data.State.FirstOrDefault(item => item.Id == notification.Data.TaskStatusId);
                if (task != null && status != null)
                {
                    var arguments = new Dictionary <string, string>();
                    arguments.Add("<%user%>", notification.Data.User.Name);
                    arguments.Add("<%task-title%>", task.Data.Title);
                    arguments.Add("<%task-date%>", status.RegistrationDate.ToLongDateString());
                    arguments.Add("<%task-status%>", status.Status.ToString());
                    var response = await _emailProvider.SendEmailAsync(notification.Data.User.Email, "Task Status Changed - AzureQuest", "{MyTransactionalTemplateId}", arguments);

                    if (response.Success)
                    {
                        notification.Data.Sent            = true;
                        notification.Data.DeliveryDate    = DateTime.Now;
                        notification.Data.DeliveryReponse = response.Tag;
                        await SaveNotificationAsync(notification.Data);
                        await DeQueueNotificationMessage(notification.Data.Id);

                        return(new OperationResult(true));
                    }
                }
            }
            return(new OperationResult(false, "Notification not found"));
        }
コード例 #11
0
ファイル: EmailService.cs プロジェクト: bmeijwaard/TheBlogApi
 // this function does not send the mail to the queue, but does so directly to prevent hitting the queue twice
 public async Task SendExceptionEmailNotificationAsync(string mainAddress, string message, string body, string title, IEnumerable <string> additionalAddesses = null)
 {
     await _emailProvider.SendEmailAsync(mainAddress, title, body, "*****@*****.**", additionalAddesses).ConfigureAwait(false);
 }
コード例 #12
0
 public async Task SendEmailAsync(string email, string subject, Dictionary <string, string> replacements, string template)
 {
     await _emailProvider.SendEmailAsync(email, subject, replacements, template);
 }