public async Task SendEmailAsync(string[] recipients, string templateId, Dictionary <string, object> personalisation, string groupReference)
        {
            if (groupReference == null)
            {
                groupReference = Guid.NewGuid().ToString();
            }

            var now = DateTime.UtcNow;

            foreach (var recipient in recipients)
            {
                _logger.LogTrace($"Email: E:{EmailHelpers.AnonymiseEmailAddress(recipient)}, T:{templateId}, G:{groupReference}");

                var response = _notifyService.SendEmail(recipient, templateId, personalisation, groupReference);

                _logger.LogInformation($"Email response id: {response.id}");
                var notification = new SchoolExperienceData.Entities.Notification
                {
                    EmailAddress       = recipient,
                    NotificationId     = response.id,
                    SendGroupReference = groupReference,
                    Sent       = now,
                    TemplateId = templateId,
                };

                _dbContext.Notifications.Add(notification);
            }

            await _dbContext.SaveChangesAsync().ConfigureAwait(false);
        }
コード例 #2
0
        public SendEmailResponse SendEmail(SendEmailRequest sendEmailRequest)
        {
            try
            {
                var response = _client.SendEmail(
                    sendEmailRequest.EmailAddress,
                    sendEmailRequest.TemplateId,
                    sendEmailRequest.Personalisation);

                return(response == null ? null : new SendEmailResponse {
                    EmailId = response.id
                });
            }
            catch (NotifyClientException e)
            {
                CustomLogger.Error(
                    "EMAIL FAILURE: Error whilst sending email using Gov.UK Notify",
                    new
                {
                    NotifyEmail            = sendEmailRequest,
                    Personalisation        = JsonConvert.SerializeObject(sendEmailRequest.Personalisation),
                    ErrorMessageFromNotify = e.Message
                });
                throw;
            }
        }
コード例 #3
0
 public void SendEmail(NotificationClient client,
                       string email,
                       string templateId,
                       Dictionary <string, dynamic> values)
 {
     client.SendEmail(email, templateId, values);
 }
コード例 #4
0
        public EmailNotificationResponse SendEmail(NotifyEmail notifyEmail)
        {
            if (EmailIsAnonymised(notifyEmail.EmailAddress))
            {
                return(null);
            }

            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;
            }
        }
コード例 #5
0
ファイル: GovNotifyAPI.cs プロジェクト: simbo1905/ACDPP
        public Notification SendEmail(string emailAddress, string templateId, Dictionary <string, dynamic> personalisation, bool test = false)
        {
            var client       = new NotificationClient(test && !string.IsNullOrWhiteSpace(_apiTestKey) ? _apiTestKey : _apiKey);
            var result       = client.SendEmail(emailAddress, templateId, personalisation, _clientReference);
            var notification = client.GetNotificationById(result.id);

            return(notification);
        }
 public EmailNotificationResponse SendEmail(string toEmail, string templateId, System.Collections.Generic.Dictionary <string, dynamic> personalisation)
 {
     using (var httpClientWrapper = new HttpClientWrapper(httpClient))
     {
         var notificationClient = new NotificationClient(httpClientWrapper, notifyOptions.ApiKey);
         return(notificationClient.SendEmail(toEmail, templateId, personalisation));
     }
 }
        public Task <string> SendEmail(string toEmail, string templateId, Dictionary <string, dynamic> parameters)
        {
            if (string.IsNullOrEmpty(_config.ApiKey))
            {
                throw new ArgumentException("Api key is empty");
            }

            var client   = new NotificationClient(_config.ApiKey);
            var response = client.SendEmail(toEmail, templateId, parameters);

            return(Task.FromResult(response.reference));
        }
コード例 #8
0
 private void SendNotification(string templateId, string emailAddress, Dictionary <string, dynamic> personalisations)
 {
     if (!string.IsNullOrEmpty(GovUkNotifyApiKey))
     {
         var client   = new NotificationClient(GovUkNotifyApiKey);
         var response = client.SendEmail(emailAddress, templateId, personalisations);
     }
     else
     {
         throw new Exception("GOV.UK Notify API Key in web.config missing or invalid.");
     }
 }
        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);
        }
コード例 #10
0
        /// <summary>
        /// Send email
        /// </summary>
        /// <param name="notifyAPIKey"></param>
        /// <param name="model"></param>
        /// <returns>bool</returns>
        public static bool Send(string notifyAPIKey, EmailModel model)
        {
            var client = new NotificationClient(notifyAPIKey); //("emailintegration-f0833c0b-c57b-48c2-b455-62cf80226d42-89b7c7f6-8e59-4df6-ab62-27e7661e5a10");
            EmailNotificationResponse response = client.SendEmail(model.To, model.EmailTemplate, model.Personalisation);

            if (response != null && !String.IsNullOrEmpty(response.id))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        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);
        }
コード例 #12
0
        public bool Send(NotifyMailMessage msg, string messageTemplate)
        {
            try
            {
                client.SendEmail(
                    msg.To,
                    messageTemplate,
                    msg.Personalisation,
                    null,
                    null);

                logger.TimedLog(LogLevel.Information, $"Email sent to GOV.Notify : Address : {msg.To} : Success");
                return(true);
            }
            catch (NotifyClientException ex)
            {
                logger.TimedLog(LogLevel.Error, $"Email sending to GOV.Notify FAILED : Message: {ex.Message}", ex);
                return(false);
            }
        }
        public bool SendEmail(string email, string subject, string message = "", Dictionary <string, dynamic> tokens = null)
        {
            AuthMessageSenderOptions = _config.Value;

            var client = new NotificationClient(AuthMessageSenderOptions.NotifyKey);

            ConfigureEmailTemplate(email, subject, message, tokens);

            try
            {
                client.SendEmail(email, EmailTemplate, TemplateContent, null, null);
            }
            catch (Notify.Exceptions.NotifyClientException e)
            {
                _logger.LogError(email + e.Message);
                return(false);
            }

            return(true);
        }
コード例 #14
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);
            }
        }
コード例 #15
0
        public void SendAccessRequestEmailToSupport(AccessRequest accessRequest, User requester, User requestedOrNull)
        {
            var templateValues = new Dictionary <string, dynamic>()
            {
                { "request_id", accessRequest.Id },

                { "requester_firstname", requester.FirstName ?? "unknown" },
                { "requester_lastname", requester.LastName ?? "unknown" },
                { "requester_email", requester.Email },
                { "requester_existingorgs", String.Join(", ", requester.OrganisationUsers.Select(x => x.Organisation.Name)) },

                { "requested_firstname", accessRequest.FirstName ?? "unknown" },
                { "requested_lastname", accessRequest.LastName ?? "unknown" },
                { "requested_email", accessRequest.EmailAddress },
                { "requested_organisation", accessRequest.Organisation ?? "unknown" },
                { "requested_reason", accessRequest.Reason ?? "unknown" },

                { "requested_existingorgs", requestedOrNull == null ? "-" : String.Join(", ", requestedOrNull.OrganisationUsers.Select(x => x.Organisation.Name)) }
            };

            _notificationClient.SendEmail(_user, _templateId, templateValues);
        }
コード例 #16
0
        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);
        }
        /// <summary>
        /// This is only a proxy to GovNotify client as there are no interface we could hang our unit tests over
        /// </summary>
        /// <param name="apiKey">The key needed for gov uk notify api</param>
        /// <param name="emailAddress">email address to send email</param>
        /// <param name="templateId">template id</param>
        /// <param name="notifyUkDynamicObject">dictionary of personalisation</param>
        /// <returns><see cref="EmailNotificationResponse"/></returns>
        public EmailNotificationResponse SendEmail(string apiKey, string emailAddress, string templateId, Dictionary <string, dynamic> notifyUkDynamicObject)
        {
            var client = new NotificationClient(apiKey);

            return(client.SendEmail(emailAddress, templateId, notifyUkDynamicObject));
        }
コード例 #18
0
ファイル: AlertService.cs プロジェクト: zjxbetter/StockSharp
        /// <summary>
        /// Initializes a new instance of the <see cref="AlertService"/>.
        /// </summary>
        /// <param name="dumpDir">Temp files directory.</param>
        public AlertService(string dumpDir)
        {
            if (dumpDir.IsEmpty())
            {
                throw new ArgumentNullException(nameof(dumpDir));
            }

            ThreadingHelper
            .Thread(() =>
            {
                try
                {
                    var player = new MediaPlayer();

                    var fileName = Path.Combine(dumpDir, "alert.mp3");

                    if (!File.Exists(fileName))
                    {
                        Properties.Resources.Alert.Save(fileName);
                    }

                    player.Open(new Uri(fileName, UriKind.RelativeOrAbsolute));

                    var logManager = ConfigManager.GetService <LogManager>();

                    using (var speech = new SpeechSynthesizer())
                        using (var client = new NotificationClient())
                            using (player.MakeDisposable(p => p.Close()))
                            {
                                while (!IsDisposed)
                                {
                                    Tuple <AlertTypes, string, string, DateTimeOffset> alert;

                                    if (!_alerts.TryDequeue(out alert))
                                    {
                                        break;
                                    }

                                    try
                                    {
                                        switch (alert.Item1)
                                        {
                                        case AlertTypes.Sound:
                                            player.Play();
                                            break;

                                        case AlertTypes.Speech:
                                            speech.Speak(alert.Item2);
                                            break;

                                        case AlertTypes.Popup:
                                            GuiDispatcher.GlobalDispatcher.AddAction(() => new AlertPopupWindow
                                            {
                                                Title   = alert.Item2,
                                                Message = alert.Item3,
                                                Time    = alert.Item4.UtcDateTime
                                            }.Show());
                                            break;

                                        case AlertTypes.Sms:
                                            client.SendSms(alert.Item2);
                                            break;

                                        case AlertTypes.Email:
                                            client.SendEmail(alert.Item2, alert.Item3);
                                            break;

                                        case AlertTypes.Log:
                                            logManager.Application.AddWarningLog(() => LocalizedStrings.Str3033Params
                                                                                 .Put(alert.Item4, alert.Item2, Environment.NewLine + alert.Item3));
                                            break;

                                        default:
                                            throw new ArgumentOutOfRangeException();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        ex.LogError();
                                    }
                                }
                            }
                }
                catch (Exception ex)
                {
                    ex.LogError();
                }
            })
            .Name("Alert thread")
            .Launch();
        }
コード例 #19
0
ファイル: AlertService.cs プロジェクト: hbwjz/StockSharp
		/// <summary>
		/// Initializes a new instance of the <see cref="AlertService"/>.
		/// </summary>
		/// <param name="dumpDir">Temp files directory.</param>
		public AlertService(string dumpDir)
		{
			if (dumpDir.IsEmpty())
				throw new ArgumentNullException("dumpDir");

			ThreadingHelper
				.Thread(() =>
				{
					try
					{
						var player = new MediaPlayer();

						var fileName = Path.Combine(dumpDir, "alert.mp3");

						if (!File.Exists(fileName))
							Properties.Resources.Alert.Save(fileName);

						player.Open(new Uri(fileName, UriKind.RelativeOrAbsolute));

						var logManager = ConfigManager.GetService<LogManager>();

						using (var speech = new SpeechSynthesizer())
						using (var client = new NotificationClient())
						using (player.MakeDisposable(p => p.Close()))
						{
							while (!IsDisposed)
							{
								Tuple<AlertTypes, string, string, DateTime> alert;

								if (!_alerts.TryDequeue(out alert))
									break;

								try
								{
									switch (alert.Item1)
									{
										case AlertTypes.Sound:
											player.Play();
											break;
										case AlertTypes.Speech:
											speech.Speak(alert.Item2);
											break;
										case AlertTypes.Popup:
											GuiDispatcher.GlobalDispatcher.AddAction(() => new AlertPopupWindow
											{
												Title = alert.Item2,
												Message = alert.Item3,
												Time = alert.Item4
											}.Show());
											break;
										case AlertTypes.Sms:
											client.SendSms(alert.Item2);
											break;
										case AlertTypes.Email:
											client.SendEmail(alert.Item2, alert.Item3);
											break;
										case AlertTypes.Log:
											logManager.Application.AddWarningLog(() => LocalizedStrings.Str3033Params
												.Put(alert.Item4, alert.Item2, Environment.NewLine + alert.Item3));
											break;
										default:
											throw new ArgumentOutOfRangeException();
									}
								}
								catch (Exception ex)
								{
									ex.LogError();
								}
							}
						}
					}
					catch (Exception ex)
					{
						ex.LogError();
					}
				})
				.Name("Alert thread")
				.Launch();
		}
コード例 #20
0
        public AlertService()
        {
            ThreadingHelper
            .Thread(() =>
            {
                try
                {
                    var player = new MediaPlayer();

                    var fileName = Path.Combine(UserConfig.Instance.MainFolder, "alert.mp3");

                    if (!File.Exists(fileName))
                    {
                        File.WriteAllBytes(fileName, Properties.Resources.Alert);
                    }

                    player.Open(new Uri(fileName, UriKind.RelativeOrAbsolute));

                    var logManager = ConfigManager.GetService <LogManager>();

                    using (var speech = new SpeechSynthesizer())
                        using (var client = new NotificationClient())
                            using (player.MakeDisposable(p => p.Close()))
                            {
                                while (!IsDisposed)
                                {
                                    Tuple <AlertTypes, string, string, DateTime> alert;

                                    if (!_alerts.TryDequeue(out alert))
                                    {
                                        break;
                                    }

                                    try
                                    {
                                        switch (alert.Item1)
                                        {
                                        case AlertTypes.Sound:
                                            player.Play();
                                            break;

                                        case AlertTypes.Speech:
                                            speech.Speak(alert.Item2);
                                            break;

                                        case AlertTypes.Popup:
                                            GuiDispatcher.GlobalDispatcher.AddAction(() => new AlertPopupWindow
                                            {
                                                Title   = alert.Item2,
                                                Message = alert.Item3,
                                                Time    = alert.Item4
                                            }.Show());
                                            break;

                                        case AlertTypes.Sms:
                                            client.SendSms(alert.Item2);
                                            break;

                                        case AlertTypes.Email:
                                            client.SendEmail(alert.Item2, alert.Item3);
                                            break;

                                        case AlertTypes.Log:
                                            logManager.Application.AddWarningLog(() => "Оповещение! В {0} случилось '{1}'.{2}"
                                                                                 .Put(alert.Item4, alert.Item2, Environment.NewLine + alert.Item3));
                                            break;

                                        default:
                                            throw new ArgumentOutOfRangeException();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        ex.LogError();
                                    }
                                }
                            }
                }
                catch (Exception ex)
                {
                    ex.LogError();
                }
            })
            .Name("Alert thread")
            .Launch();
        }