/// <summary> /// Asynchronously sends an e-mail on behalf of the given controller using the specified parameters. /// </summary> /// <param name="controller">The controller that initiated the action.</param> /// <param name="model">An object used to create the message to send.</param> /// <param name="emailClient">An object used to send the e-mail.</param> /// <returns></returns> public static async Task <IActionResult> SendEmailAsync(this Controller controller, EmailModel model, IEmailClientService emailClient) { var config = emailClient.Configuration; try { var message = EmailClientService.CreateMessage( model.Subject, model.Body, model.From, model.To ); await emailClient.SendAsync(message); return(controller.Ok()); } catch (ServiceNotAuthenticatedException ex) { if (false == config?.RequiresAuth) { return(controller.BadRequest(new ServiceNotAuthenticatedException(SmtpServerRequiresAuth))); } return(controller.BadRequest(ex)); } catch (SslHandshakeException ex) { if (true == config?.UseSsl) { return(controller.BadRequest(new SslHandshakeException(SmtpServerDoesNotSupportSsl))); } return(controller.BadRequest(ex)); } catch (SocketException) { return(controller.BadRequest(new Exception(string.Format(SmtpHostUnreachable, config?.Host)))); } catch (Exception ex) { return(controller.BadRequest(ex)); } }
/// <summary> /// Executes a long running task until cancellation is requested. /// </summary> /// <param name="cancellationToken">The token used to cancel an ongoing async operation.</param> /// <returns></returns> protected override async Task ExecuteAsync(CancellationToken cancellationToken) { if (Dispatching || Disabled) { return; } Dispatching = true; CancellationTokenSource cts = null; try { await RetrieveFailedEmails(); var unlogged = true; var hubClients = _hubContext.Clients.All; var messages = new HashSet <MimeMessage>(); cts = CreateLinkedTokenSource(cancellationToken); foreach (var item in DequeueAll()) { if (item is MimeMessageContainer container) { _workingSet.Add(container); messages.Add(container.Message); } else { try { // broadcast notification message await hubClients.BroadcastMessage(item); } catch (Exception ex) { if (unlogged) { Logger.LogWarning(ex, "Error broadcasting message to SignalR clients."); unlogged = false; } } } if (cts.IsCancellationRequested) { break; } } if (!cts.IsCancellationRequested && messages.Count > 0) { if (_emailClient.Configuration == null) { await SyncEmailSettings(); } Logger.LogInformation("Dispatching e-mails..."); await _emailClient.SendAsync(messages, cts.Token); Logger.LogInformation("Done dispatching e-mails."); } messages.Clear(); } catch (Exception ex) { Logger.LogError(ex, "Something strange happened in the e-mail dispatcher."); } finally { _workingSet.Clear(); cts?.Dispose(); Dispatching = false; } }