feat(email): implement email queue management

This commit is contained in:
2026-03-06 20:13:24 -05:00
parent 95da3f9543
commit 5420d94595
2 changed files with 49 additions and 9 deletions
+47 -8
View File
@@ -3,29 +3,68 @@ using MailKit.Security;
using Microsoft.Extensions.Options;
using MimeKit;
using SharpbinV3.Server.Settings;
using System.Threading.Channels;
namespace SharpbinV3.Server.Services
{
public class EmailService(IOptions<EmailSettings> emailSettings)
public class EmailService(IOptions<EmailSettings> emailSettings, ILogger<EmailService> logger) : BackgroundService
{
private readonly EmailSettings settings = emailSettings.Value;
private readonly Channel<QueuedEmail> queue = Channel.CreateUnbounded<QueuedEmail>(
new UnboundedChannelOptions
{
SingleReader = true,
SingleWriter = false,
}
);
public async Task SendAsync(string to, string subject, string body)
{
var email = new QueuedEmail(to, subject, body);
if (queue.Writer.TryWrite(email))
return;
await queue.Writer.WriteAsync(email);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var email in queue.Reader.ReadAllAsync(stoppingToken))
{
try
{
await SendNowAsync(email, stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to send email to {EmailTo}", email.To);
}
}
}
private async Task SendNowAsync(QueuedEmail email, CancellationToken cancellationToken)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Sharpbin", settings.From));
message.To.Add(MailboxAddress.Parse(to));
message.Subject = subject;
message.To.Add(MailboxAddress.Parse(email.To));
message.Subject = email.Subject;
message.Body = new TextPart("html") { Text = body };
message.Body = new TextPart("html") { Text = email.Body };
using var smtp = new SmtpClient();
await smtp.ConnectAsync(settings.Host, settings.Port, SecureSocketOptions.StartTls);
await smtp.ConnectAsync(settings.Host, settings.Port, SecureSocketOptions.StartTls, cancellationToken);
await smtp.AuthenticateAsync(settings.User, settings.Password);
await smtp.AuthenticateAsync(settings.User, settings.Password, cancellationToken);
await smtp.SendAsync(message);
await smtp.DisconnectAsync(true);
await smtp.SendAsync(message, cancellationToken);
await smtp.DisconnectAsync(true, cancellationToken);
}
private readonly record struct QueuedEmail(string To, string Subject, string Body);
}
}