public EmailNotificationResponse SendEmail(string emailAddress, string templateId, Dictionary <string, dynamic> personalisation = null, string clientReference = null, string emailReplyToId = null)
        {
            EmailNotificationResponse result = null;

            if (hasClient)
            {
                _logger.LogDebug("Sending email using templateId {0}", templateId);
                result = _client.SendEmail(emailAddress, templateId, personalisation, clientReference, emailReplyToId);
            }
            else
            {
                _logger.LogCritical("Email not send. Missing config: {0}", EmailApiKey);
            }

            return(result);
        }
        public void SendEmailTestWithPersonalisation()
        {
            Dictionary <String, dynamic> personalisation = new Dictionary <String, dynamic>
            {
                { "name", "someone" }
            };

            EmailNotificationResponse response =
                this.client.SendEmail(FUNCTIONAL_TEST_EMAIL, EMAIL_TEMPLATE_ID, personalisation);

            this.emailNotificationId = response.id;

            Assert.IsNotNull(response);
            Assert.AreEqual(response.content.body, TEST_EMAIL_BODY);
            Assert.AreEqual(response.content.subject, TEST_EMAIL_SUBJECT);
        }
        public EmailNotificationResponse SendEmail(String emailAddress, String templateId, Dictionary <String, dynamic> personalisation = null, String clientReference = null, String emailReplyToId = null)
        {
            JObject o = CreateRequestParams(templateId, personalisation, clientReference);

            o.AddFirst(new JProperty("email_address", emailAddress));

            if (emailReplyToId != null)
            {
                o.Add(new JProperty("email_reply_to_id", emailReplyToId));
            }

            String response = this.POST(SEND_EMAIL_NOTIFICATION_URL, o.ToString(Formatting.None));

            EmailNotificationResponse receipt = JsonConvert.DeserializeObject <EmailNotificationResponse>(response);

            return(receipt);
        }
        public async Task Then_Do_Not_Send_Email_If_Template_Name_Is_Null(
            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,
            EmailTemplate emailTemplate,
            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("", "*****@*****.**", opportunity.Id, opportunityItem.Id, tokens, "System");

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

            emailHistory.Should().BeNull();
        }
        public void Setup()
        {
            _mocker = AutoMock.GetLoose();
            _createNotificationService = _mocker.Create <CreateNotificationService>();
            _emailResponseContent      = new EmailResponseContent()
            {
                body = "Email reponse Body"
            };

            _template = new Template(Guid.NewGuid(), NotificationType.JudgeDemoOrTest, MessageType.Email, "param1, param2");
            _createEmailNotificationCommand = new CreateEmailNotificationCommand(NotificationType.JudgeDemoOrTest, "*****@*****.**", Guid.NewGuid(), Guid.NewGuid());
            _parameters = new Dictionary <string, dynamic>
            {
                { "Test param1Key", "Test param1Value" }
            };
            _emailResponseContent = new EmailResponseContent()
            {
                body = "Email reponse Body"
            };
            _expectedEmailNotificationResponse = new EmailNotificationResponse()
            {
                id        = Guid.NewGuid().ToString(),
                reference = "reference",
                uri       = "uri",
                content   = _emailResponseContent,
                template  = null
            };

            _mocker.Mock <IPollyRetryService>().Setup(x => x.WaitAndRetryAsync <Exception, EmailNotificationResponse>
                                                      (
                                                          It.IsAny <int>(), It.IsAny <Func <int, TimeSpan> >(), It.IsAny <Action <int> >(), It.IsAny <Func <EmailNotificationResponse, bool> >(), It.IsAny <Func <Task <EmailNotificationResponse> > >()
                                                      ))
            .Callback(async(int retries, Func <int, TimeSpan> sleepDuration, Action <int> retryAction, Func <EmailNotificationResponse, bool> handleResultCondition, Func <Task <EmailNotificationResponse> > executeFunction) =>
            {
                sleepDuration(1);
                retryAction(7);
                handleResultCondition(_expectedEmailNotificationResponse);
                await executeFunction();
            })
            .ReturnsAsync(_expectedEmailNotificationResponse);
        }
Esempio n. 6
0
        /// <summary>
        /// Send Email with specified template using template data
        /// </summary>
        /// <param name="EmailTo">To email id</param>
        /// <param name="TemplateId">Gov Notifier Template Id</param>
        /// <param name="TemplateData">key value pair of the data in template</param>
        /// <returns></returns>

        public static void SendEmail(GovNotifierEmailPdfInParams inparam)
        {
            logger.Debug($@"Inside SendEmail for Id = {inparam.Id}");
            StringBuilder DebugInfo = new StringBuilder("Initiated for Pdf generation.\r\n");

            try
            {
                Data.StatusUpdate(inparam.Id, "2", "In progress", DebugInfo.Append("Inside SendEmail to start Generating pdf.\r\n").ToString());
                logger.Debug($@"In progress with for GeneratePdfDocument");
                Document document = new BuildDoc().GeneratePdfDocument(inparam.ContactId, inparam.TenancyAgreementRef, inparam.StartDate);

                if (document != null)
                {
                    Data.StatusUpdate(inparam.Id, "3", "Document Created", DebugInfo.Append("Document created.\r\n").ToString());
                    logger.Debug($@"Document Created");
                    byte[] docbytes = document.Draw();
                    logger.Debug($@"Document Size = {docbytes.Length}");
                    NotificationClient client = new NotificationClient(_apiKey);
                    var TemplateDataDict      = JsonConvert.DeserializeObject <Dictionary <string, string> >(inparam.TemplateData);
                    logger.Debug($@"Creating Personalization");
                    Dictionary <string, dynamic> personalisation = new Dictionary <string, dynamic>();
                    foreach (KeyValuePair <string, string> pair in TemplateDataDict)
                    {
                        personalisation.Add(pair.Key.ToString(), pair.Value.ToString());
                        logger.Debug($@"Adding Personalization for key = {pair.Key.ToString()} value = {pair.Value.ToString()}");
                    }
                    personalisation.Add("link_to_document", NotificationClient.PrepareUpload(docbytes));
                    logger.Debug($@"Linked document to template");
                    Data.StatusUpdate(inparam.Id, "4", "Sending email", DebugInfo.Append("Emailing with pdf attachment.\r\n").ToString());

                    EmailNotificationResponse response = client.SendEmail(inparam.EmailTo, inparam.TemplateId, personalisation);
                    logger.Debug($@"Email Sent successfully to Gov Notifier with attachments {response.id}");
                    Data.StatusUpdate(inparam.Id, "0", "Email Sent Successfully", DebugInfo.Append("Completed.\r\n").ToString());
                }
            }
            catch (Exception ex)
            {
                Data.StatusUpdate(inparam.Id, "-1", "Error Occurred", DebugInfo.Append("Error occured : \r\n").ToString() + ex.Message);
                logger.Error(ex, "Error occured in Send Email $$$$$ " + ex.Message);
            }
        }
        public void SendEmailNotificationGeneratesExpectedRequest()
        {
            Dictionary <string, dynamic> personalisation = new Dictionary <string, dynamic>
            {
                { "name", "someone" }
            };
            JObject expected = new JObject
            {
                { "email_address", Constants.fakeEmail },
                { "template_id", Constants.fakeTemplateId },
                { "personalisation", JObject.FromObject(personalisation) },
                { "reference", Constants.fakeNotificationReference }
            };

            MockRequest(Constants.fakeTemplatePreviewResponseJson,
                        client.SEND_EMAIL_NOTIFICATION_URL,
                        AssertValidRequest,
                        HttpMethod.Post,
                        AssertGetExpectedContent, expected.ToString(Formatting.None));

            EmailNotificationResponse response = client.SendEmail(Constants.fakeEmail, Constants.fakeTemplateId, personalisation, Constants.fakeNotificationReference);
        }
        public EmailNotificationResponse SendEmail(NotifyEmail notifyEmail)
        {
            try
            {
                EmailNotificationResponse response = _client.SendEmail(
                    notifyEmail.EmailAddress,
                    notifyEmail.TemplateId,
                    notifyEmail.Personalisation);

                return(response);
            }
            catch (NotifyClientException e)
            {
                CustomLogger.Error(
                    "EMAIL FAILURE: Error whilst sending email using Gov.UK Notify",
                    new {
                    NotifyEmail            = notifyEmail,
                    Personalisation        = JsonConvert.SerializeObject(notifyEmail.Personalisation),
                    ErrorMessageFromNotify = e.Message
                });
                throw;
            }
        }
        public EmailNotificationResponse SendEmail(TemplateOptions options)
        {
            EmailNotificationResponse response = null;

            try
            {
                var serviceApp   = GovNotifySettings.ServiceApps.Find(s => s.Service.ToUpper() == options.ServiceType.ToUpper());
                var notifyScheme = serviceApp.NotifySchemes.Find(n => n.Name == options.NotifyScheme);
                var templateId   = notifyScheme.TemplateId;
                if (string.IsNullOrEmpty(templateId))
                {
                    return(null);
                }
                options.Personalisation.Add("System", serviceApp.Description);
                response = Client.SendEmail(options.EmailAddress, templateId, options.Personalisation, null, null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            return(response);
        }
        public async Task Then_Send_Email_And_Save_Email_History_And_Update_Email_History_If_Status_Is_Null(
            string status,
            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,
            EmailDeliveryStatusPayLoad payLoad
            )
        {
            //Arrange
            Guid.TryParse(emailNotificationResponse.id, out var notificationId);
            payLoad.Status = status;
            payLoad.Id     = notificationId;

            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
            var data = dbContext.EmailHistory.AsNoTracking().FirstOrDefault(x => x.NotificationId == notificationId);

            data.Should().NotBeNull();
            data?.EmailTemplateId.Should().Be(emailHistory.EmailTemplateId);
            data?.NotificationId.Should().Be(emailNotificationResponse.id);
            data?.CreatedBy.Should().Be("System");
            data?.Status.Should().BeNullOrEmpty();
            data?.ModifiedBy.Should().BeNullOrEmpty();
            data?.ModifiedOn.Should().BeNull();

            dbContext.DetachAllEntities();

            //Act - Update Email With Status
            await sut.UpdateEmailStatus(payLoad);

            data = dbContext.EmailHistory.AsNoTracking().FirstOrDefault(x => x.NotificationId == notificationId);

            data.Should().NotBeNull();
            data?.EmailTemplateId.Should().Be(emailHistory.EmailTemplateId);
            data?.Status.Should().NotBeNullOrEmpty();
            data?.Status.Should().Be(payLoad.Status);
            data?.NotificationId.Should().Be(emailNotificationResponse.id);
            data?.CreatedBy.Should().Be("System");
            data?.ModifiedBy.Should().Be("System");
        }