private async Task <IOutcome> SendOverMultipleSmtpServersAsync(EmailMessage message) { var errors = new List <string>(); var smtpServerConfigurations = _mailSettingsConfig.Smtp.Servers; var wasSentSuccessfully = false; foreach (var smtpServerConfiguration in smtpServerConfigurations) { try { if (wasSentSuccessfully) { continue; } var createRequest = new MailMessageCreateRequest() { EmailMessage = message, SmtpServerConfig = smtpServerConfiguration, IsReadSenderFromConfig = true, RequiredRecipients = _mailSettingsConfig.Smtp.RequiredRecipients, }; var mailMessage = await _mailMessageFactory.CreateAsync(createRequest); using (var smtpClient = _smtpClientFactory.Create(smtpServerConfiguration)) { await smtpClient.SendAsync(mailMessage); wasSentSuccessfully = true; } } catch (Exception ex) { wasSentSuccessfully = false; var error = ex.Message; if (ex.InnerException != null) { var innerEx = ex.InnerException; while (innerEx.InnerException != null) { innerEx = innerEx.InnerException; } error = innerEx.Message; } errors.Add($"SMTP {smtpServerConfiguration.Host} throw an error: {error}"); } } if (wasSentSuccessfully) { return(Outcomes.Success()); } return(Outcomes.Failure().WithMessagesFrom(errors.Distinct())); }
public MailMessageFactoryTests() { _factory = new MailMessageFactory(); _smtpServerConfig = SmtpServerConfigFake.Generate(); var from = _faker.Internet.Email(); var to = new List <string>() { _faker.Internet.Email() }; _emailMessage = new EmailMessage(from, to, "subject", "body"); _request = new MailMessageCreateRequest() { EmailMessage = _emailMessage, SmtpServerConfig = _smtpServerConfig, IsReadSenderFromConfig = false, }; }