smtp-relay/src/smtprelay/Smtp/SmtpServer.cs

71 lines
2 KiB
C#
Raw Normal View History

2025-10-27 15:36:41 +01:00
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Net.Sockets;
namespace SmtpRelay;
public class SmtpServer(IServiceScopeFactory scopeFactory, ILogger<SmtpServer> logger)
{
private readonly ILogger<SmtpServer> _logger = logger;
private readonly IServiceScopeFactory _scopeFactory = scopeFactory;
public bool IsRunning { get; private set; } = false;
public async Task RunAsync(SmtpConfig config, CancellationToken cancellationToken)
{
if (IsRunning)
return;
var ep = new IPEndPoint(IPAddress.Parse(config.Host), config.Port);
// start listener
using var listener = new TcpListener(ep);
listener.Start();
cancellationToken.Register(listener.Stop);
// set listener state
IsRunning = true;
// log
_logger.LogInformation("SMTP listening on {HOST}:{PORT}", config.Host, config.Port);
// handler loop
while (!cancellationToken.IsCancellationRequested)
{
try
{
// await new client
var client = await listener.AcceptTcpClientAsync(cancellationToken);
// handle client async
_ = HandleClientAsync(client, config, cancellationToken);
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
_logger.LogError(ex.ToString());
}
}
// set listener state
IsRunning = false;
}
private async Task HandleClientAsync(TcpClient client, SmtpConfig config, CancellationToken cancellationToken)
{
// create session
using var scope = _scopeFactory.CreateScope();
var session = scope.ServiceProvider.GetRequiredService<SmtpSession>();
try
{
await session.InitAsync(client.Client, config, cancellationToken);
}
finally
{
client?.Dispose();
}
}
}