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,264 @@
using FluentAssertions;
using FsCheck;
using FsCheck.Fluent;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Email;
using Xunit.Abstractions;
namespace SlpModularCms.Core.Tests.Email;
public class EmailOptionsValidatorTests
{
private static EmailOptionsValidator Validator(string baseUrl = "https://test.example.nl", string lang = "nl") =>
new(Options.Create(new AppMailOptions { PublicBaseUrl = baseUrl, DefaultLanguage = lang }));
private static EmailOptions Valid() => new()
{
FromAddress = "no-reply@example.nl",
FromName = "Example",
Smtp = { Host = "mail.example.nl", Port = 587, Username = "u", Password = "p" }
};
[Fact]
public void WithoutAHost_MailIsDisabled_AndNothingIsValidated() =>
Validator("", "xx").Validate(null, new EmailOptions()).Succeeded.Should().BeTrue();
[Fact]
public void AValidConfiguration_Passes() =>
Validator().Validate(null, Valid()).Succeeded.Should().BeTrue();
[Theory]
[InlineData("http://example.nl")] // http only allowed for localhost
[InlineData("https://example.nl/admin")] // no path
[InlineData("https://example.nl/?a=1")]
[InlineData("https://user:pw@example.nl")]
[InlineData("example.nl")]
[InlineData("")]
public void ABadPublicBaseUrl_FailsStartup(string url) =>
Validator(url).Validate(null, Valid()).Failed.Should().BeTrue();
[Theory]
[InlineData("http://localhost:5200")]
[InlineData("https://test.andreaslop.nl")]
[InlineData("https://test.andreaslop.nl/")]
public void GoodPublicBaseUrls_Pass(string url) =>
Validator(url).Validate(null, Valid()).Succeeded.Should().BeTrue();
[Fact]
public void EachProblem_IsReported_AndNeverEchoesTheCredentials()
{
var o = Valid();
o.FromAddress = "not-an-address";
o.FromName = "";
o.Smtp.Port = 0;
o.Smtp.TimeoutSeconds = 0;
o.Smtp.Password = ""; // username set, password empty
o.BrandColor = "red";
o.LogoUrl = "javascript:alert(1)";
o.AllowedFromAddresses = ["bad"];
var result = Validator("http://x.nl", "xx").Validate(null, o);
result.Failed.Should().BeTrue();
var text = string.Join(" | ", result.Failures!);
text.Should().Contain("FromAddress").And.Contain("FromName").And.Contain("Port").And.Contain("TimeoutSeconds")
.And.Contain("Password").And.Contain("BrandColor").And.Contain("LogoUrl")
.And.Contain("AllowedFromAddresses").And.Contain("PublicBaseUrl").And.Contain("DefaultLanguage");
text.Should().NotContain("mail.example.nl");
}
[Fact]
public void ToString_NeverContainsTheCredentials()
{
var o = Valid();
o.Smtp.Username = "user-secret-1";
o.Smtp.Password = "pw-secret-2";
o.ToString().Should().NotContain("user-secret-1").And.NotContain("pw-secret-2");
}
}
public class EmailAddressRulesTests
{
[Theory]
[InlineData("no-reply@slpsoftware.nl", true)]
[InlineData("a.b+c@sub.example.org", true)]
[InlineData("", false)]
[InlineData("a@b", false)]
[InlineData("a b@example.nl", false)]
[InlineData("a@example.nl\r\nBcc: x@y.nl", false)]
[InlineData("\"quoted\"@example.nl", false)]
[InlineData("a@exa mple.nl", false)]
[InlineData("<a@example.nl>", false)]
public void Address_IsAnAllowlistMatch(string value, bool expected) =>
EmailAddressRules.IsValidAddress(value).Should().Be(expected);
[Theory]
[InlineData("Andrea Slop Fotografie", true)]
[InlineData("Décor & Co", true)]
[InlineData("", false)]
[InlineData(" ", false)]
[InlineData("two\nlines", false)]
[InlineData("tab\there", false)]
public void DisplayName_RejectsControlCharacters(string value, bool expected) =>
EmailAddressRules.IsValidDisplayName(value).Should().Be(expected);
[Fact]
public void DisplayName_HasALengthLimit()
{
EmailAddressRules.IsValidDisplayName(new string('a', 80)).Should().BeTrue();
EmailAddressRules.IsValidDisplayName(new string('a', 81)).Should().BeFalse();
}
[Fact]
public void Sender_MustBeTheDefaultOrOnTheAllowlist()
{
string[] allowed = ["info@andreaslop.nl"];
EmailAddressRules.IsAllowedSender("no-reply@slpsoftware.nl", "no-reply@slpsoftware.nl", allowed).Should().BeTrue();
EmailAddressRules.IsAllowedSender("INFO@AndreaSlop.nl", "no-reply@slpsoftware.nl", allowed).Should().BeTrue();
EmailAddressRules.IsAllowedSender("evil@other.nl", "no-reply@slpsoftware.nl", allowed).Should().BeFalse();
}
}
public class MailTemplateRendererTests
{
private readonly MailTemplateRenderer _renderer = new();
private static MailModel Model(string site = "Andrea Slop Fotografie", string? action = "https://t.nl/admin/invite/complete?token=abc%2Fd", string? name = null) =>
new(site, name, action, ValidForMinutes: 1440, Detail: "Administrator", LogoUrl: "https://t.nl/admin/brand-logo-on-light.png", BrandColor: "#2b6cb0");
[Fact]
public void Invitation_IsRenderedInDutchWithLinkLogoAndColour()
{
var mail = _renderer.Render(MailKind.Invitation, "nl", Model());
mail.Subject.Should().Be("Uitnodiging voor Andrea Slop Fotografie");
mail.Html.Should().Contain("Account activeren").And.Contain("https://t.nl/admin/invite/complete?token=abc%2Fd")
.And.Contain("brand-logo-on-light.png").And.Contain("#2b6cb0").And.Contain("24 uur");
mail.Text.Should().Contain("https://t.nl/admin/invite/complete?token=abc%2Fd").And.Contain("24 uur");
}
[Fact]
public void English_IsSupported_AndAnUnknownLanguageFallsBackToDutch()
{
_renderer.Render(MailKind.Invitation, "en", Model()).Subject.Should().Be("Invitation to Andrea Slop Fotografie");
_renderer.Render(MailKind.Invitation, "fr", Model()).Subject.Should().StartWith("Uitnodiging");
_renderer.Render(MailKind.Invitation, "EN-gb", Model()).Subject.Should().StartWith("Invitation");
}
[Fact]
public void RoleNotice_UsesTheLocalisedRoleName()
{
_renderer.Render(MailKind.RoleChanged, "nl", Model(action: null)).Text.Should().Contain("Beheerder");
_renderer.Render(MailKind.RoleChanged, "en", Model(action: null)).Text.Should().Contain("Administrator");
}
[Fact]
public void ANoticeWithoutAButton_HasNoLink()
{
var mail = _renderer.Render(MailKind.AccountDeactivated, "nl", Model(action: "https://t.nl/x"));
mail.Html.Should().NotContain("https://t.nl/x");
mail.Text.Should().NotContain("https://t.nl/x");
}
[Fact]
public void ADisplayNameWithMarkup_IsEncoded_NotInterpreted()
{
var mail = _renderer.Render(MailKind.Invitation, "nl", Model(site: "<script>alert(1)</script> & \"Co\"", name: "<b>x</b>"));
mail.Html.Should().NotContain("<script>").And.NotContain("<b>x</b>");
mail.Html.Should().Contain("&lt;script&gt;");
}
[Fact]
public void PasswordReset_States_ThatIgnoringItKeepsThePassword()
{
_renderer.Render(MailKind.PasswordReset, "nl", Model()).Text.Should().Contain("ongewijzigd");
_renderer.Render(MailKind.PasswordReset, "en", Model()).Text.Should().Contain("unchanged");
}
[Fact]
public void AnInvalidBrandColour_FallsBackToTheDefault()
{
var mail = _renderer.Render(MailKind.Invitation, "nl", Model() with { BrandColor = "red;}</style>" });
mail.Html.Should().NotContain("red;}");
}
[Fact]
public void LanguageResolver_UsesUserThenSiteDefaultThenDutch()
{
var resolver = new LanguageResolver(Options.Create(new AppMailOptions { DefaultLanguage = "en" }));
resolver.Resolve("nl").Should().Be("nl");
resolver.Resolve(null).Should().Be("en");
resolver.Resolve("de").Should().Be("en");
new LanguageResolver(Options.Create(new AppMailOptions { DefaultLanguage = "??" })).Resolve(null).Should().Be("nl");
}
}
/// <summary>Property-based tests (PBT-03 invariants, PBT-07 generators with control characters and markup; PBT-08 seed printed by FsCheck).</summary>
public class MailPropertyTests(ITestOutputHelper output)
{
private static readonly string[] Pieces =
[
"a", "Z", "é", "ß", " ", "<", ">", "&", "\"", "'", "/", "\\", "\r", "\n", "\0", "\t", "{", "}", "{0}", "%", "@", ".", "-", "😀", "script", "javascript:"
];
private static Arbitrary<string> Strings() =>
Gen.Elements(Pieces).ArrayOf().Select(p => string.Concat(p)).ToArbitrary();
private void Check(Func<string, bool> property)
{
Prop.ForAll(Strings(), s => property(s)).Check(Config.QuickThrowOnFailure.WithMaxTest(1500));
output.WriteLine("Property held for 1500 generated inputs.");
}
[Fact]
public void Rendering_NeverThrows_NeverLeaksMarkup_AndKeepsTheSubjectOnOneLine() =>
Check(s =>
{
var renderer = new MailTemplateRenderer();
// Markers make the generated value findable inside the output.
var site = "QQ" + s + "ZZ";
var hasMarkup = s.IndexOfAny(['<', '>', '&', '"']) >= 0;
foreach (var kind in Enum.GetValues<MailKind>())
foreach (var lang in new[] { "nl", "en" })
{
var mail = renderer.Render(kind, lang, new MailModel(site, site, "https://t.nl/x?a=" + Uri.EscapeDataString(site), 60, site));
if (mail.Subject.Any(char.IsControl)) return false;
// A value containing markup characters must never appear raw in the HTML body.
if (hasMarkup && mail.Html.Contains(site, StringComparison.Ordinal)) return false;
}
return true;
});
[Fact]
public void ADisplayNameWithAControlCharacter_IsNeverValid() =>
Check(s => !s.Any(char.IsControl) || !EmailAddressRules.IsValidDisplayName(s));
[Fact]
public void AnAddressWithAnythingOutsideTheAllowedAlphabet_IsNeverValid() =>
Check(s => !EmailAddressRules.IsValidAddress(s)
|| s.All(c => char.IsAsciiLetterOrDigit(c) || "._%+-@".Contains(c)));
[Fact]
public void AnAddressNotOnTheAllowlist_IsNeverAllowedAsSender() =>
Check(s =>
{
string[] allowed = ["info@andreaslop.nl"];
var ok = EmailAddressRules.IsAllowedSender(s, "no-reply@slpsoftware.nl", allowed);
return !ok || s.Equals("no-reply@slpsoftware.nl", StringComparison.OrdinalIgnoreCase)
|| s.Equals("info@andreaslop.nl", StringComparison.OrdinalIgnoreCase);
});
[Fact]
public void ATokenSurvivesTheLinkRoundTrip() =>
Check(token =>
{
// The link carries the token as a query value: escape, then parse, must return the token.
var link = "https://t.nl/admin/invite/complete?token=" + Uri.EscapeDataString(token);
var query = new Uri(link).Query.TrimStart('?');
var value = Uri.UnescapeDataString(query["token=".Length..]);
return value == token;
});
}
@@ -0,0 +1,59 @@
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using MySql.Data.MySqlClient;
using SlpModularCms.Core.Data;
namespace SlpModularCms.Core.Tests.Email;
/// <summary>
/// The schema changes for this feature must apply, undo and re-apply on a real MariaDB (additive and
/// reversible, safe for SlpSoftware's database). Uses its own scratch database from
/// <c>ConnectionStrings__DefaultConnection</c> (set in CI); does nothing when that variable is absent.
/// </summary>
public class MigrationRoundTripTests
{
[Fact]
public async Task AllMigrations_ApplyOnMariaDb_AndTheNewestCanBeUndoneAndReapplied()
{
var raw = Environment.GetEnvironmentVariable("ConnectionStrings__DefaultConnection");
if (string.IsNullOrWhiteSpace(raw)) return; // no MariaDB available here
var cs = new MySqlConnectionStringBuilder(raw) { Database = "migration_roundtrip_probe" }.ConnectionString;
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseMySQL(cs)
.ReplaceService<Microsoft.EntityFrameworkCore.Migrations.IHistoryRepository, SlpModularCms.Core.Hosting.NonLockingMySQLHistoryRepository>() // as in production
.Options;
await using var db = new ApplicationDbContext(options);
try
{
await db.Database.EnsureDeletedAsync();
await db.Database.MigrateAsync();
(await TableExists(db, "SiteSettings")).Should().BeTrue();
var migrations = db.GetService<IMigrationsAssembly>().Migrations.Keys.OrderBy(k => k).ToList();
var previous = migrations[^2];
var migrator = db.GetService<IMigrator>();
await migrator.MigrateAsync(previous); // undo the newest
(await TableExists(db, "SiteSettings")).Should().BeFalse();
await migrator.MigrateAsync(); // and apply it again
(await TableExists(db, "SiteSettings")).Should().BeTrue();
}
finally
{
await db.Database.EnsureDeletedAsync();
}
}
private static async Task<bool> TableExists(ApplicationDbContext db, string table)
{
var rows = await db.Database
.SqlQuery<int>($"select count(*) as Value from information_schema.tables where table_schema = database() and table_name = {table}")
.ToListAsync();
return rows[0] > 0;
}
}
@@ -0,0 +1,154 @@
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Data;
using SlpModularCms.Core.Email;
using SlpModularCms.Core.Hosting;
using SlpModularCms.Core.SiteSettings;
namespace SlpModularCms.Core.Tests.Email;
public class SiteSettingsServiceTests : IDisposable
{
private readonly ApplicationDbContext _db;
public SiteSettingsServiceTests() =>
_db = new ApplicationDbContext(new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
public void Dispose() => _db.Dispose();
private SiteSettingsService Service(string host = "mail.example.nl", string[]? allowed = null) =>
new(_db, Options.Create(new EmailOptions
{
FromAddress = "no-reply@example.nl",
FromName = "Example",
AllowedFromAddresses = allowed ?? ["info@andreaslop.nl"],
Smtp = { Host = host }
}));
[Fact]
public async Task WithNothingStored_TheConfiguredDefaultsApply()
{
var view = await Service().GetMailAsync();
view.EmailEnabled.Should().BeTrue();
view.FromAddress.Should().Be("no-reply@example.nl");
view.FromName.Should().Be("Example");
view.IsCustomized.Should().BeFalse();
view.AllowedFromAddresses.Should().BeEquivalentTo("no-reply@example.nl", "info@andreaslop.nl");
}
[Fact]
public async Task AnAllowedAddressAndName_AreStored_AndUsed()
{
var result = await Service().SetMailAsync("info@andreaslop.nl", "Andrea Slop Fotografie", "owner@example.nl");
result.Ok.Should().BeTrue();
var sender = await Service().GetEffectiveSenderAsync();
sender.Should().Be(("info@andreaslop.nl", "Andrea Slop Fotografie"));
var row = await _db.SiteSettings.SingleAsync();
row.UpdatedBy.Should().Be("owner@example.nl");
}
[Theory]
[InlineData("evil@other.nl", "Name", SetMailResult.AddressNotAllowed)]
[InlineData("not-an-address", "Name", SetMailResult.InvalidAddress)]
[InlineData("info@andreaslop.nl", "two\nlines", SetMailResult.InvalidName)]
[InlineData("info@andreaslop.nl", "x", null)]
public async Task Validation_RejectsWhatIsNotAllowed(string address, string name, string? expectedError)
{
var result = await Service().SetMailAsync(address, name, null);
result.Error.Should().Be(expectedError);
if (expectedError is not null) (await _db.SiteSettings.CountAsync()).Should().Be(0);
}
[Fact]
public async Task BlankValues_ResetToTheDefaults()
{
await Service().SetMailAsync("info@andreaslop.nl", "Andrea", null);
(await Service().SetMailAsync(null, " ", null)).Ok.Should().BeTrue();
var view = await Service().GetMailAsync();
view.FromAddress.Should().Be("no-reply@example.nl");
view.IsCustomized.Should().BeFalse();
}
[Fact]
public async Task AStoredAddress_ThatIsNoLongerAllowed_FallsBackToTheDefault()
{
await Service().SetMailAsync("info@andreaslop.nl", "Andrea", null);
// The host's allowlist is narrowed later: the mail must not go out as the old address.
var sender = await Service(allowed: []).GetEffectiveSenderAsync();
sender.Address.Should().Be("no-reply@example.nl");
sender.Name.Should().Be("Andrea");
}
[Fact]
public async Task WhenMailIsDisabled_SettingsCannotBeChanged()
{
var result = await Service(host: "").SetMailAsync("info@andreaslop.nl", "x", null);
result.Error.Should().Be(SetMailResult.MailDisabled);
(await Service(host: "").GetMailAsync()).EmailEnabled.Should().BeFalse();
}
}
public class EmailRegistrationTests
{
private static IServiceProvider Build(Dictionary<string, string?> values)
{
var config = new ConfigurationBuilder().AddInMemoryCollection(values).Build();
var services = new ServiceCollection();
services.AddLogging();
services.AddCmsEmail(config);
return services.BuildServiceProvider();
}
[Fact]
public void WithoutAHost_TheNullSenderIsRegistered_AndNothingIsValidated()
{
var sp = Build(new() { ["App:PublicBaseUrl"] = "garbage" });
sp.GetRequiredService<IEmailSender>().Should().BeOfType<NullEmailSender>();
sp.GetRequiredService<IOptions<EmailOptions>>().Value.Smtp.Host.Should().BeEmpty();
}
[Fact]
public void WithAHost_TheSmtpSenderIsRegistered()
{
var sp = Build(new()
{
["Email:Smtp:Host"] = "mail.example.nl", ["Email:FromAddress"] = "no-reply@example.nl",
["Email:FromName"] = "Example", ["App:PublicBaseUrl"] = "https://example.nl"
});
sp.GetRequiredService<IEmailSender>().Should().BeOfType<SmtpEmailSender>();
sp.GetRequiredService<IOptions<EmailOptions>>().Value.Smtp.Port.Should().Be(587);
sp.GetRequiredService<IOptions<EmailOptions>>().Value.Smtp.EnableSsl.Should().BeTrue();
}
[Fact]
public void WithAHostButABrokenConfiguration_OptionsFail()
{
var sp = Build(new() { ["Email:Smtp:Host"] = "mail.example.nl", ["App:PublicBaseUrl"] = "http://example.nl" });
var act = () => sp.GetRequiredService<IOptions<EmailOptions>>().Value;
act.Should().Throw<OptionsValidationException>().WithMessage("*FromAddress*");
}
[Fact]
public void IsEmailEnabled_FollowsTheHost()
{
new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?> { ["Email:Smtp:Host"] = "x" }).Build()
.IsEmailEnabled().Should().BeTrue();
new ConfigurationBuilder().Build().IsEmailEnabled().Should().BeFalse();
}
}
@@ -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));
}