diff --git a/Wave/Program.cs b/Wave/Program.cs index a530075..ece5707 100644 --- a/Wave/Program.cs +++ b/Wave/Program.cs @@ -187,8 +187,8 @@ } foreach (var smtp in emailConfig.Smtp) { - builder.Services.AddKeyedScoped(smtp.Key.ToLower(), (provider, key) => - ActivatorUtilities.CreateInstance(provider, + builder.Services.AddKeyedScoped(smtp.Key.ToLower(), (provider, key) => + ActivatorUtilities.CreateInstance(provider, provider.GetRequiredService>().Value.Smtp[(string)key])); } diff --git a/Wave/Services/LiveEmailService.cs b/Wave/Services/SmtpEmailService.cs similarity index 57% rename from Wave/Services/LiveEmailService.cs rename to Wave/Services/SmtpEmailService.cs index db18188..0138cf8 100644 --- a/Wave/Services/LiveEmailService.cs +++ b/Wave/Services/SmtpEmailService.cs @@ -6,8 +6,8 @@ namespace Wave.Services; -public class LiveEmailService(ILogger logger, IOptions emailConfiguration, SmtpConfiguration configuration) : IEmailService { - private ILogger Logger { get; } = logger; +public class SmtpEmailService(ILogger logger, IOptions emailConfiguration, SmtpConfiguration configuration) : IEmailService { + private ILogger Logger { get; } = logger; private EmailConfiguration EmailConfiguration { get; } = emailConfiguration.Value; private SmtpConfiguration Configuration { get; } = configuration; @@ -44,35 +44,40 @@ public class LiveEmailService(ILogger logger, IOptions"); - } - message.Headers.Add(id, value); + if (Client is null) throw new ApplicationException("Not connected."); + + var message = new MimeMessage { + From = { new MailboxAddress(EmailConfiguration.SenderName, EmailConfiguration.SenderEmail) }, + To = { new MailboxAddress(email.ReceiverName, email.ReceiverEmail) }, + Subject = email.Subject + }; + var builder = new BodyBuilder { + HtmlBody = email.ContentHtml, + TextBody = email.ContentPlain + }; + message.Body = builder.ToMessageBody(); + foreach ((string id, string value) in email.Headers) { + if (id == HeaderId.ListUnsubscribe.ToHeaderName()) { + message.Headers.Add(HeaderId.ListId, $""); } + 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); + retryCount++; + Logger.LogWarning(ex, "Error sending E-Mail to {email}. Try: {RetryCount}.", + email.ReceiverEmail, retryCount); } - } catch (Exception ex) { - Logger.LogError(ex, "Error sending E-Mail"); } + // TODO enqueue for re-sending or throw exception if applicable and handle hard bounce + // throw new EmailNotSendException(); + Logger.LogError("Giving up"); } } \ No newline at end of file