feat: add ImapClientFactory for IMAP connection management
This commit is contained in:
34
src/SpamGuard/Services/ImapClientFactory.cs
Normal file
34
src/SpamGuard/Services/ImapClientFactory.cs
Normal file
@@ -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<ImapClientFactory> _logger;
|
||||||
|
|
||||||
|
public ImapClientFactory(IOptions<SpamGuardOptions> options, ILogger<ImapClientFactory> logger)
|
||||||
|
{
|
||||||
|
_options = options.Value;
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<ImapClient> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user