Added Smtp retry on failure

This commit is contained in:
Mia Rose Winter 2024-03-28 14:17:54 +01:00
parent 37f84da148
commit 7d97cd4b36
Signed by: miawinter
GPG key ID: 4B6F6A83178F595E
2 changed files with 30 additions and 25 deletions

View file

@ -187,8 +187,8 @@
}
foreach (var smtp in emailConfig.Smtp) {
builder.Services.AddKeyedScoped<IEmailService, LiveEmailService>(smtp.Key.ToLower(), (provider, key) =>
ActivatorUtilities.CreateInstance<LiveEmailService>(provider,
builder.Services.AddKeyedScoped<IEmailService, SmtpEmailService>(smtp.Key.ToLower(), (provider, key) =>
ActivatorUtilities.CreateInstance<SmtpEmailService>(provider,
provider.GetRequiredService<IOptions<EmailConfiguration>>().Value.Smtp[(string)key]));
}

View file

@ -6,8 +6,8 @@
namespace Wave.Services;
public class LiveEmailService(ILogger<LiveEmailService> logger, IOptions<EmailConfiguration> emailConfiguration, SmtpConfiguration configuration) : IEmailService {
private ILogger<LiveEmailService> Logger { get; } = logger;
public class SmtpEmailService(ILogger<SmtpEmailService> logger, IOptions<EmailConfiguration> emailConfiguration, SmtpConfiguration configuration) : IEmailService {
private ILogger<SmtpEmailService> Logger { get; } = logger;
private EmailConfiguration EmailConfiguration { get; } = emailConfiguration.Value;
private SmtpConfiguration Configuration { get; } = configuration;
@ -44,7 +44,6 @@ public class LiveEmailService(ILogger<LiveEmailService> logger, IOptions<EmailCo
}
public async ValueTask SendEmailAsync(IEmail email) {
try {
if (Client is null) throw new ApplicationException("Not connected.");
var message = new MimeMessage {
@ -64,15 +63,21 @@ public class LiveEmailService(ILogger<LiveEmailService> logger, IOptions<EmailCo
message.Headers.Add(id, value);
}
int retryCount = 0;
while (retryCount < 3) {
try {
await Client.SendAsync(message);
Logger.LogInformation("Successfully send mail to {email} (subject: {subject}).",
email.ReceiverEmail, email.Subject);
return;
} catch (Exception ex) {
throw new EmailNotSendException("Failed Email send.", ex);
}
} catch (Exception ex) {
Logger.LogError(ex, "Error sending E-Mail");
retryCount++;
Logger.LogWarning(ex, "Error sending E-Mail to {email}. Try: {RetryCount}.",
email.ReceiverEmail, retryCount);
}
}
// TODO enqueue for re-sending or throw exception if applicable and handle hard bounce
// throw new EmailNotSendException();
Logger.LogError("Giving up");
}
}