diff --git a/src/SpamGuard/Services/ImapClientFactory.cs b/src/SpamGuard/Services/ImapClientFactory.cs new file mode 100644 index 0000000..1b02584 --- /dev/null +++ b/src/SpamGuard/Services/ImapClientFactory.cs @@ -0,0 +1,34 @@ +namespace SpamGuard.Services; + +using MailKit.Net.Imap; +using MailKit.Security; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using SpamGuard.Configuration; + +public sealed class ImapClientFactory +{ + private readonly SpamGuardOptions _options; + private readonly ILogger _logger; + + public ImapClientFactory(IOptions options, ILogger logger) + { + _options = options.Value; + _logger = logger; + } + + public async Task CreateConnectedClientAsync(CancellationToken ct = default) + { + var client = new ImapClient(); + var imap = _options.Imap; + + _logger.LogDebug("Connecting to {Host}:{Port} (SSL={UseSsl})", imap.Host, imap.Port, imap.UseSsl); + + var secureSocketOptions = imap.UseSsl ? SecureSocketOptions.SslOnConnect : SecureSocketOptions.StartTlsWhenAvailable; + await client.ConnectAsync(imap.Host, imap.Port, secureSocketOptions, ct); + await client.AuthenticateAsync(imap.Username, imap.Password, ct); + + _logger.LogDebug("Connected and authenticated as {Username}", imap.Username); + return client; + } +}