private async Task SendEmailAndSaveHistoryAsync(int?opportunityId, int?opportunityItemId, string recipient, EmailTemplate emailTemplate,
                                                        IDictionary <string, string> personalisationTokens, string createdBy)
        {
            try
            {
                var tokens = personalisationTokens.Select(x => new { key = x.Key, val = (dynamic)x.Value })
                             .ToDictionary(item => item.key, item => item.val);

                var emailresponse = await _notificationClient.SendEmailAsync(recipient, emailTemplate.TemplateId, tokens);

                Guid.TryParse(emailresponse.id, out var notificationId);

                await SaveEmailHistoryAsync(notificationId, emailTemplate.Id, personalisationTokens, opportunityId, opportunityItemId,
                                            recipient, createdBy);
            }
            catch (Exception ex)
            {
                var message = $"Error sending email template {emailTemplate?.TemplateId} to {recipient}. {ex.Message}";
                _logger.LogError(ex, message);

                message += $"\r\nInner exception: {ex.InnerException?.Message}\r\n" +
                           $"Stack trace: {ex.StackTrace}";
                await _functionLogRepository.CreateAsync(new FunctionLog
                {
                    ErrorMessage = message,
                    FunctionName = nameof(EmailService),
                    RowNumber    = -1
                });
            }
        }
        public async Task CreateEmailNotificationAsync(CreateEmailNotificationCommand notificationCommand, Dictionary <string, string> parameters)
        {
            var template = await _queryHandler.Handle <GetTemplateByNotificationTypeQuery, Template>(new GetTemplateByNotificationTypeQuery(notificationCommand.NotificationType));

            await _commandHandler.Handle(notificationCommand);

            var requestParameters         = parameters.ToDictionary(x => x.Key, x => (dynamic)x.Value);
            var emailNotificationResponse = await _asyncNotificationClient.SendEmailAsync(notificationCommand.ContactEmail, template.NotifyTemplateId.ToString(), requestParameters, notificationCommand.NotificationId.ToString());

            await _commandHandler.Handle(new UpdateNotificationSentCommand(notificationCommand.NotificationId, emailNotificationResponse.id, emailNotificationResponse.content.body));
        }
Beispiel #3
0
 public async Task SendEmailAsync(string emailAddress, string templateId,
                                  Dictionary <string, dynamic> personalisation)
 {
     try
     {
         await _notifyClient.SendEmailAsync(emailAddress, templateId, personalisation);
     }
     catch (Exception ex)
     {
         _logger.LogError($"NotifyTemplatedEmailProvider::SendEmailAsync, email failed to send using template id {templateId}: {ex.Message}");
     }
 }
        public async Task Then_Send_Email_And_Save_Email_History(
            MatchingConfiguration configuration,
            [Frozen] MatchingDbContext dbContext,
            IAsyncNotificationClient notificationClient,
            ILogger <GenericRepository <EmailTemplate> > emailTemplateLogger,
            ILogger <GenericRepository <EmailHistory> > emailHistoryLogger,
            ILogger <GenericRepository <FunctionLog> > functionLogLogger,
            ILogger <EmailService> emailServiceLogger,
            [Frozen] Domain.Models.Opportunity opportunity,
            [Frozen] OpportunityItem opportunityItem,
            [Frozen] Domain.Models.Provider provider,
            [Frozen] Domain.Models.ProviderVenue venue,
            [Frozen] BackgroundProcessHistory backgroundProcessHistory,
            [Frozen] EmailHistory emailHistory,
            [Frozen] EmailTemplate emailTemplate,
            [Frozen] EmailNotificationResponse emailNotificationResponse
            )
        {
            //Arrange
            var(templateRepository, emailHistoryRepository, functionLogRepository, mapper)
                = SetUp(dbContext, emailTemplateLogger, emailHistoryLogger, functionLogLogger);

            var sut = new EmailService(configuration, notificationClient, templateRepository, emailHistoryRepository,
                                       functionLogRepository, mapper, emailServiceLogger);

            var tokens = new Dictionary <string, string>
            {
                { "contactname", "name" }
            };

            notificationClient.SendEmailAsync(Arg.Any <string>(), Arg.Any <string>(),
                                              Arg.Any <Dictionary <string, dynamic> >()).Returns(Task.FromResult(emailNotificationResponse));

            await DataBuilder.SetTestData(dbContext, provider, venue, opportunity, backgroundProcessHistory);

            await DataBuilder.SetEmailTemplate(dbContext, emailTemplate);

            //Act
            await sut.SendEmailAsync(emailTemplate.TemplateName, "*****@*****.**", opportunity.Id, opportunityItem.Id, tokens, "System");

            //Assert
            Guid.TryParse(emailNotificationResponse.id, out var notificationId);
            var data = dbContext.EmailHistory.AsNoTracking().FirstOrDefault(x => x.NotificationId == notificationId);

            data.Should().NotBeNull();
            data?.EmailTemplateId.Should().Be(emailHistory.EmailTemplateId);
            data?.Status.Should().BeNullOrEmpty();
            data?.NotificationId.Should().Be(emailNotificationResponse.id);
            data?.CreatedBy.Should().Be("System");
            data?.SentTo.Should().Be("*****@*****.**");
        }
        public async Task SendNotification(string templateName, string toAddress, dynamic tokens)
        {
            var templateId            = templateName == Constants.TlevelsQueryTemplateName ? Constants.TlevelsQueryTemplateId : "";
            var personalisationTokens = new Dictionary <string, dynamic>();

            foreach (var property in tokens.GetType().GetProperties())
            {
                personalisationTokens[property.Name] = property.GetValue(tokens);
            }

            var emailNotificationResponse = await _notificationClient.SendEmailAsync(
                emailAddress : toAddress,
                templateId : templateId,
                personalisation : personalisationTokens);

            var result = emailNotificationResponse;
        }
        public async Task <EmailNotificationResponse> SendEmailAsyncRetry(string contactEmail, string notifyTemplateId, Dictionary <string, dynamic> requestParameters, string notificationId)
        {
            var maxRetryAttempts     = 2;
            var pauseBetweenFailures = TimeSpan.FromSeconds(5);

            var result = await _pollyRetryService.WaitAndRetryAsync <Exception, EmailNotificationResponse>
                         (
                maxRetryAttempts,
                _ => pauseBetweenFailures,
                retryAttempt =>
                _logger.LogWarning(
                    "Failed to send email to send email to the NotifyAPi for notifcationId {Hearing}. Retrying attempt {RetryAttempt}", notificationId, retryAttempt
                    ),
                callResult => callResult == null,
                () => _asyncNotificationClient.SendEmailAsync(contactEmail, notifyTemplateId, requestParameters, notificationId)
                         );

            return(result);
        }
        public async Task SendMailAsync <TRequest>(TRequest request)
            where TRequest : EmailRequest
        {
            try
            {
                var requestName = typeof(TRequest).Name;
                if (_options.GetTemplateIds().TryGetValue(requestName, out var templateId))
                {
                    await _notificationClientAsync.SendEmailAsync(request.Address, templateId, request);

                    _logger.LogInformation(Resources.SuccessfullySentEmail, requestName);
                }
                else
                {
                    _logger.LogError(Resources.ResolveTemplateError, requestName);
                }
            }
            catch (NotifyClientException ex)
            {
                _logger.LogError(ex, Resources.EmailFailed, ex.Message);
            }
        }
Beispiel #8
0
        private async Task <bool> SendEmail(string recipient, string emailTemplateId,
                                            Dictionary <string, dynamic> personalisationTokens)
        {
            var emailSent = false;

            try
            {
                var emailResponse = await _notificationClient.SendEmailAsync(recipient, emailTemplateId, personalisationTokens);

                _logger.LogInformation($"Email sent - notification id '{emailResponse.id}', " +
                                       $"reference '{emailResponse.reference}, " +
                                       $"content '{emailResponse.content}'");
                emailSent = true;
            }
            catch (Exception ex)
            {
                var message = $"Error sending email template {emailTemplateId} to {recipient}. {ex.Message}";
                _logger.LogError(ex, message);
            }

            return(emailSent);
        }
Beispiel #9
0
        private async Task NotifyByEmailInternalAsync(
            string templateId,
            string emailAddress,
            Dictionary <string, dynamic> personalisation = null,
            string clientReference = null,
            string emailReplyToId  = null
            )
        {
            var emailNotificationResponse =
                await _client.SendEmailAsync(
                    emailAddress, templateId, personalisation, clientReference, emailReplyToId
                    ).ConfigureAwait(false);

            if (emailNotificationResponse == null)
            {
                throw new NotifyClientException("Failed to receive valid response from GOV.UK Notify client. No response was received from service.");
            }

            if (!String.IsNullOrWhiteSpace(clientReference) && !clientReference.Equals(emailNotificationResponse.reference))
            {
                throw new NotifyClientException("Failed to receive valid response from GOV.UK Notify client. Client reference received does not match client reference supplied.");
            }
        }
        public async Task <bool> SendEmailNotificationAsync(string templateName, string toAddress, IDictionary <string, dynamic> tokens)
        {
            var hasEmailSent         = false;
            var notificationTemplate = await _notificationTemplateRepository.GetFirstOrDefaultAsync(t => t.TemplateName == templateName);

            if (notificationTemplate == null)
            {
                _logger.LogWarning(LogEvent.EmailTemplateNotFound, $"Notification email template {templateName} not found");
                return(hasEmailSent);
            }

            try
            {
                var personalisationTokens = tokens.ToDictionary(t => t.Key, t => t.Value);
                await _notificationClient.SendEmailAsync(emailAddress : toAddress, templateId : notificationTemplate.TemplateId.ToString(), personalisation : personalisationTokens);

                hasEmailSent = true;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEvent.EmailSendFailed, ex, $"Error sending notification email, templateName: {notificationTemplate.TemplateName}, templateId: {notificationTemplate.TemplateId} to {toAddress}");
            }
            return(hasEmailSent);
        }
Beispiel #11
0
        //Need to uncomment later
        // public NotifyEmailFramework(IOptions<EmailFrameworkOptions> options)
        // {
        //     _notificationClient = new NotificationClient(options.Value.ApiKey);
        // }

        public async Task SendEmail(string emailAddress, string templateId, Dictionary <string, dynamic> personalisation)
        {
            await _notificationClient.SendEmailAsync(emailAddress, templateId, personalisation);
        }