U1 mail-foundation (backend): verzender, opties, sjabloon, SiteSettings met toegestane afzenderlijst

IEmailSender met MailKit-implementatie (StartTls, timeout, fouten als waarde), opties met
startvalidatie, nl/en sjabloon, taalkeuze, tabel SiteSettings (additieve migratie),
SiteSettings-API (Beheerder leest, Eigenaar wijzigt) en emailEnabled/defaultLanguage in de
capabilities. Zonder SMTP-host verandert er niets.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 18:22:26 +01:00
co-authored by Claude Sonnet 5.5
parent 1a2fb56e1e
commit 745f0b2203
27 changed files with 2069 additions and 2 deletions
@@ -0,0 +1,160 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Email;
namespace SlpModularCms.Core.Tests.Email;
/// <summary>A minimal in-process SMTP server: accepts one message and records it. No TLS, no auth.</summary>
internal sealed class StubSmtpServer : IDisposable
{
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
private readonly bool _silent;
private readonly Task _loop;
public string? ReceivedData { get; private set; }
public string? MailFrom { get; private set; }
public List<string> Recipients { get; } = [];
public int Port => ((IPEndPoint)_listener.LocalEndpoint).Port;
/// <param name="silent">Accept connections but never answer (to provoke the timeout).</param>
public StubSmtpServer(bool silent = false)
{
_silent = silent;
_listener.Start();
_loop = Task.Run(Serve);
}
private async Task Serve()
{
try
{
using var client = await _listener.AcceptTcpClientAsync();
if (_silent) { await Task.Delay(TimeSpan.FromSeconds(30)); return; }
await using var stream = client.GetStream();
using var reader = new StreamReader(stream, Encoding.ASCII);
await using var writer = new StreamWriter(stream, new UTF8Encoding(false)) { AutoFlush = true, NewLine = "\r\n" };
await writer.WriteLineAsync("220 stub ESMTP");
while (await reader.ReadLineAsync() is { } line)
{
if (line.StartsWith("EHLO", StringComparison.OrdinalIgnoreCase)) await writer.WriteLineAsync("250 stub");
else if (line.StartsWith("MAIL FROM", StringComparison.OrdinalIgnoreCase)) { MailFrom = line; await writer.WriteLineAsync("250 ok"); }
else if (line.StartsWith("RCPT TO", StringComparison.OrdinalIgnoreCase)) { Recipients.Add(line); await writer.WriteLineAsync("250 ok"); }
else if (line.StartsWith("DATA", StringComparison.OrdinalIgnoreCase))
{
await writer.WriteLineAsync("354 go");
var data = new StringBuilder();
while (await reader.ReadLineAsync() is { } d && d != ".") data.AppendLine(d);
ReceivedData = data.ToString();
await writer.WriteLineAsync("250 queued");
}
else if (line.StartsWith("QUIT", StringComparison.OrdinalIgnoreCase)) { await writer.WriteLineAsync("221 bye"); break; }
else await writer.WriteLineAsync("250 ok");
}
}
catch (Exception) { /* the test ended or the client disconnected */ }
}
public void Dispose() => _listener.Stop();
}
public class SmtpEmailSenderTests
{
private static SmtpEmailSender Sender(int port, int timeoutSeconds = 5) => new(
Options.Create(new EmailOptions
{
FromAddress = "no-reply@example.nl",
FromName = "Example Site",
Smtp = { Host = "127.0.0.1", Port = port, EnableSsl = false, TimeoutSeconds = timeoutSeconds }
}),
NullLogger<SmtpEmailSender>.Instance);
[Fact]
public async Task Sends_TheMail_WithTheConfiguredSender()
{
using var server = new StubSmtpServer();
var result = await Sender(server.Port).SendAsync(new OutgoingMail("to@example.org", "Hello", "<p>Body</p>", "Body"));
result.Should().Be(MailSendResult.Ok);
server.MailFrom.Should().Contain("no-reply@example.nl");
server.Recipients.Should().ContainSingle().Which.Should().Contain("to@example.org");
server.ReceivedData.Should().Contain("Subject: Hello").And.Contain("Example Site").And.Contain("Body");
}
[Fact]
public async Task ASenderOverride_IsUsedForTheFromHeader()
{
using var server = new StubSmtpServer();
var result = await Sender(server.Port).SendAsync(
new OutgoingMail("to@example.org", "Hi", "<p>x</p>", FromAddress: "info@example.nl", FromName: "Andrea"));
result.Sent.Should().BeTrue();
server.ReceivedData.Should().Contain("From: Andrea <info@example.nl>");
}
[Fact]
public async Task ASimpleDeckAppShapedCall_Works()
{
using var server = new StubSmtpServer();
var result = await Sender(server.Port).SendAsync("to@example.org", "Subject", "<p>x</p>");
result.Sent.Should().BeTrue();
}
[Theory]
[InlineData("to@example.org\r\nBcc: victim@example.org", "Subject")]
[InlineData("not-an-address", "Subject")]
[InlineData("to@example.org", "Subject\r\nBcc: victim@example.org")]
public async Task HeaderInjectionAndBadAddresses_AreRefused_WithoutConnecting(string to, string subject)
{
using var server = new StubSmtpServer();
var result = await Sender(server.Port).SendAsync(new OutgoingMail(to, subject, "<p>x</p>"));
result.Should().Be(MailSendResult.Fail(MailSendResult.Rejected));
server.ReceivedData.Should().BeNull();
server.Recipients.Should().BeEmpty();
}
[Fact]
public async Task ASlowServer_ProducesATimeout_NotAnException()
{
using var server = new StubSmtpServer(silent: true);
var started = DateTime.UtcNow;
var result = await Sender(server.Port, timeoutSeconds: 1).SendAsync(new OutgoingMail("to@example.org", "S", "<p>x</p>"));
result.Should().Be(MailSendResult.Fail(MailSendResult.Timeout));
(DateTime.UtcNow - started).Should().BeLessThan(TimeSpan.FromSeconds(10));
}
[Fact]
public async Task ANeverListeningServer_IsAFailureValue_NotAnException()
{
int freePort;
using (var probe = new TcpListener(IPAddress.Loopback, 0)) { probe.Start(); freePort = ((IPEndPoint)probe.LocalEndpoint).Port; }
var result = await Sender(freePort, timeoutSeconds: 2).SendAsync(new OutgoingMail("to@example.org", "S", "<p>x</p>"));
result.Sent.Should().BeFalse();
result.ErrorCode.Should().NotBeNullOrEmpty();
}
[Fact]
public async Task WithoutAHost_ItReportsNotConfigured()
{
var sender = new SmtpEmailSender(Options.Create(new EmailOptions()), NullLogger<SmtpEmailSender>.Instance);
(await sender.SendAsync(new OutgoingMail("to@example.org", "S", "x"))).Should().Be(MailSendResult.Fail(MailSendResult.NotConfigured));
}
[Fact]
public async Task TheNullSender_ReportsDisabled() =>
(await new NullEmailSender().SendAsync(new OutgoingMail("to@example.org", "S", "x"))).Should().Be(MailSendResult.Fail(MailSendResult.Disabled));
}