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,38 @@
using System.Text.RegularExpressions;
namespace SlpModularCms.Core.Email;
/// <summary>
/// Validation of the values that end up in mail headers. Strict on purpose (allowlist, no control
/// characters): a sender address or display name is a header, and a header is an injection target.
/// </summary>
public static partial class EmailAddressRules
{
public const int MaxAddressLength = 254;
public const int MaxDisplayNameLength = 80;
// Plain ASCII local@domain.tld: deliberately narrower than RFC 5322 (no quoted strings, no comments).
[GeneratedRegex(@"^[A-Za-z0-9._%+\-]{1,64}@(?:[A-Za-z0-9](?:[A-Za-z0-9\-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}$")]
private static partial Regex AddressRegex();
[GeneratedRegex(@"^#[0-9A-Fa-f]{6}$")]
private static partial Regex ColourRegex();
public static bool IsValidAddress(string? value) =>
!string.IsNullOrEmpty(value) && value.Length <= MaxAddressLength && AddressRegex().IsMatch(value);
public static bool IsValidDisplayName(string? value) =>
!string.IsNullOrWhiteSpace(value) && value.Trim().Length <= MaxDisplayNameLength && !ContainsControlCharacters(value);
public static bool IsValidColour(string? value) => !string.IsNullOrEmpty(value) && ColourRegex().IsMatch(value);
/// <summary>True for CR, LF, NUL and any other control character (header injection and friends).</summary>
public static bool ContainsControlCharacters(string value) => value.Any(char.IsControl);
public static bool IsAllowedSender(string? address, string defaultAddress, IEnumerable<string> allowed)
{
if (!IsValidAddress(address)) return false;
if (string.Equals(address, defaultAddress, StringComparison.OrdinalIgnoreCase)) return true;
return allowed.Any(a => string.Equals(a, address, StringComparison.OrdinalIgnoreCase));
}
}
@@ -0,0 +1,65 @@
using System.Diagnostics.CodeAnalysis;
namespace SlpModularCms.Core.Email;
/// <summary>
/// Mail configuration (section <c>Email</c>). Mail is enabled when <see cref="SmtpOptions.Host"/> is set;
/// without a host every flow behaves as it did before mail existed.
/// </summary>
/// <remarks>
/// Same shape and names as SimpleDeckApp's options on purpose, extended with the settings this CMS
/// needs (allowlist of sender addresses, brand, timeout). Credentials come from the environment
/// (<c>Email__Smtp__Username</c>, <c>Email__Smtp__Password</c>), never from a committed file.
/// </remarks>
public sealed class EmailOptions
{
public const string SectionName = "Email";
/// <summary>Default sender address when the site settings hold none.</summary>
public string FromAddress { get; set; } = "";
/// <summary>Default sender display name; also used as the site name inside the mail.</summary>
public string FromName { get; set; } = "";
/// <summary>
/// Sender addresses a site may choose in its settings. Mandatory: a free address could send as a
/// domain the SMTP account is not authorised for (SPF/DKIM mismatch, spoofing). Empty means only
/// <see cref="FromAddress"/> is allowed.
/// </summary>
public string[] AllowedFromAddresses { get; set; } = [];
/// <summary>Optional logo for the mail header, absolute or relative to <c>App:PublicBaseUrl</c>.</summary>
public string LogoUrl { get; set; } = "";
/// <summary>Optional brand colour, <c>#rrggbb</c>.</summary>
public string BrandColor { get; set; } = "";
public SmtpOptions Smtp { get; set; } = new();
[ExcludeFromCodeCoverage]
public override string ToString() => $"Email(From={FromAddress}, Host={Smtp.Host})"; // never the credentials
}
public sealed class SmtpOptions
{
public string Host { get; set; } = "";
public int Port { get; set; } = 587;
public bool EnableSsl { get; set; } = true;
public string Username { get; set; } = "";
public string Password { get; set; } = "";
/// <summary>Connect and send are bounded by this, because mail is sent inside the request.</summary>
public int TimeoutSeconds { get; set; } = 10;
}
/// <summary>Site-level settings around mail (section <c>App</c>).</summary>
public sealed class AppMailOptions
{
public const string SectionName = "App";
/// <summary>Public https address of the site, used to build links in mails (for example https://test.andreaslop.nl).</summary>
public string PublicBaseUrl { get; set; } = "";
/// <summary>Default language of the site for mails: nl or en.</summary>
public string DefaultLanguage { get; set; } = "nl";
}
@@ -0,0 +1,63 @@
using Microsoft.Extensions.Options;
namespace SlpModularCms.Core.Email;
/// <summary>
/// Start-up validation of the mail configuration. Only runs checks when mail is enabled (an SMTP host
/// is set); a host without mail configuration starts exactly as before. Messages never contain the
/// credentials.
/// </summary>
public sealed class EmailOptionsValidator(IOptions<AppMailOptions> app) : IValidateOptions<EmailOptions>
{
public ValidateOptionsResult Validate(string? name, EmailOptions options)
{
if (string.IsNullOrWhiteSpace(options.Smtp.Host))
return ValidateOptionsResult.Success; // mail disabled
var failures = new List<string>();
if (!EmailAddressRules.IsValidAddress(options.FromAddress))
failures.Add("Email:FromAddress must be a valid e-mail address.");
if (!EmailAddressRules.IsValidDisplayName(options.FromName))
failures.Add($"Email:FromName is required (1..{EmailAddressRules.MaxDisplayNameLength} characters, no control characters).");
if (options.Smtp.Port is < 1 or > 65535)
failures.Add("Email:Smtp:Port must be between 1 and 65535.");
if (options.Smtp.TimeoutSeconds is < 1 or > 60)
failures.Add("Email:Smtp:TimeoutSeconds must be between 1 and 60.");
if (!string.IsNullOrEmpty(options.Smtp.Username) && string.IsNullOrEmpty(options.Smtp.Password))
failures.Add("Email:Smtp:Password is required when Email:Smtp:Username is set.");
if (!string.IsNullOrEmpty(options.BrandColor) && !EmailAddressRules.IsValidColour(options.BrandColor))
failures.Add("Email:BrandColor must look like #rrggbb.");
foreach (var allowed in options.AllowedFromAddresses)
{
if (!EmailAddressRules.IsValidAddress(allowed))
failures.Add("Email:AllowedFromAddresses contains an invalid e-mail address.");
}
var baseUrl = app.Value.PublicBaseUrl;
if (!IsValidPublicBaseUrl(baseUrl))
failures.Add("App:PublicBaseUrl must be an absolute https URL (http only for localhost) without a path.");
if (!MailLanguages.IsSupported(app.Value.DefaultLanguage))
failures.Add("App:DefaultLanguage must be 'nl' or 'en'.");
if (!string.IsNullOrEmpty(options.LogoUrl) && !IsValidLogoUrl(options.LogoUrl))
failures.Add("Email:LogoUrl must be an https URL or a path starting with '/'.");
return failures.Count == 0 ? ValidateOptionsResult.Success : ValidateOptionsResult.Fail(failures);
}
public static bool IsValidPublicBaseUrl(string? value)
{
if (string.IsNullOrWhiteSpace(value) || !Uri.TryCreate(value, UriKind.Absolute, out var uri)) return false;
var local = uri.IsLoopback;
if (uri.Scheme != Uri.UriSchemeHttps && !(local && uri.Scheme == Uri.UriSchemeHttp)) return false;
return (uri.AbsolutePath == "/" || uri.AbsolutePath == "") && string.IsNullOrEmpty(uri.Query) && string.IsNullOrEmpty(uri.Fragment)
&& string.IsNullOrEmpty(uri.UserInfo);
}
private static bool IsValidLogoUrl(string value)
{
if (value.StartsWith('/') && !value.StartsWith("//") && !value.Any(char.IsControl)) return true;
return Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps;
}
}
@@ -0,0 +1,37 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.SiteSettings;
namespace SlpModularCms.Core.Email;
public static class EmailServiceCollectionExtensions
{
/// <summary>
/// Registers the mail building blocks. Mail is on when <c>Email:Smtp:Host</c> is set; otherwise a
/// <see cref="NullEmailSender"/> is registered and every flow behaves as before mail existed.
/// The options are validated at start-up (only when mail is on).
/// </summary>
public static IServiceCollection AddCmsEmail(this IServiceCollection services, IConfiguration configuration)
{
services.AddOptions<AppMailOptions>().Bind(configuration.GetSection(AppMailOptions.SectionName));
services.AddOptions<EmailOptions>().Bind(configuration.GetSection(EmailOptions.SectionName)).ValidateOnStart();
services.AddSingleton<IValidateOptions<EmailOptions>, EmailOptionsValidator>();
var enabled = !string.IsNullOrWhiteSpace(configuration[$"{EmailOptions.SectionName}:Smtp:Host"]);
if (enabled)
services.TryAddSingleton<IEmailSender, SmtpEmailSender>();
else
services.TryAddSingleton<IEmailSender, NullEmailSender>();
services.TryAddSingleton<IMailTemplateRenderer, MailTemplateRenderer>();
services.TryAddSingleton<ILanguageResolver, LanguageResolver>();
services.TryAddScoped<ISiteSettingsService, SiteSettingsService>();
return services;
}
/// <summary>True when an SMTP host is configured.</summary>
public static bool IsEmailEnabled(this IConfiguration configuration) =>
!string.IsNullOrWhiteSpace(configuration[$"{EmailOptions.SectionName}:Smtp:Host"]);
}
@@ -0,0 +1,26 @@
namespace SlpModularCms.Core.Email;
/// <summary>
/// Sends one mail. Same name and first four parameters as SimpleDeckApp's <c>IEmailSender.SendAsync</c>
/// (see the extension below); differs on purpose in that it returns a <see cref="MailSendResult"/>
/// instead of throwing, because in this CMS a mail failure must never fail the action that triggered it.
/// </summary>
public interface IEmailSender
{
Task<MailSendResult> SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default);
}
public static class EmailSenderExtensions
{
/// <summary>SimpleDeckApp-shaped call: to, subject, html body.</summary>
public static Task<MailSendResult> SendAsync(
this IEmailSender sender, string toAddress, string subject, string htmlBody, CancellationToken cancellationToken = default) =>
sender.SendAsync(new OutgoingMail(toAddress, subject, htmlBody), cancellationToken);
}
/// <summary>Registered when no SMTP host is configured: reports "disabled" so callers never null-check.</summary>
public sealed class NullEmailSender : IEmailSender
{
public Task<MailSendResult> SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default) =>
Task.FromResult(MailSendResult.Fail(MailSendResult.Disabled));
}
@@ -0,0 +1,201 @@
using System.Net;
using System.Text;
using Microsoft.Extensions.Options;
namespace SlpModularCms.Core.Email;
public interface IMailTemplateRenderer
{
RenderedMail Render(MailKind kind, string language, MailModel model);
}
public interface ILanguageResolver
{
/// <summary>The user's language if supported, else the site default, else Dutch.</summary>
string Resolve(string? preferredLanguage);
}
public sealed class LanguageResolver(IOptions<AppMailOptions> options) : ILanguageResolver
{
public string Resolve(string? preferredLanguage) =>
MailLanguages.Normalize(preferredLanguage)
?? MailLanguages.Normalize(options.Value.DefaultLanguage)
?? MailLanguages.Dutch;
}
/// <summary>
/// One shared layout, texts per language kept in code. Every dynamic value is HTML-encoded for the
/// HTML part; the subject and plain-text part carry the raw values (no markup there). A missing
/// language or key falls back to Dutch. Table layout and inline CSS only, so it renders in mail clients.
/// </summary>
public sealed class MailTemplateRenderer : IMailTemplateRenderer
{
private const string DefaultColour = "#1f2937";
private sealed record Texts(
string Subject, string Heading, string Intro, string? Button, string? Note, string Footer);
// {0} = site name, {1} = role, {2} = minutes/hours text. Keys: kind, then language.
private static readonly Dictionary<MailKind, Dictionary<string, Texts>> Catalog = new()
{
[MailKind.Invitation] = new()
{
["nl"] = new("Uitnodiging voor {0}", "Je bent uitgenodigd",
"Je bent uitgenodigd om een account aan te maken voor {0}. Kies met de knop hieronder je wachtwoord om je account te activeren.",
"Account activeren", "Deze link is {2} geldig. Is hij verlopen, vraag dan de beheerder om een nieuwe uitnodiging.",
"Deze mail is automatisch verstuurd door {0}."),
["en"] = new("Invitation to {0}", "You have been invited",
"You have been invited to create an account for {0}. Use the button below to choose your password and activate your account.",
"Activate account", "This link is valid for {2}. If it has expired, ask the administrator for a new invitation.",
"This message was sent automatically by {0}.")
},
[MailKind.NewInvitationLink] = new()
{
["nl"] = new("Nieuwe uitnodigingslink voor {0}", "Je hebt een nieuwe uitnodigingslink",
"Er is een nieuwe uitnodigingslink voor je aangemaakt voor {0}. De vorige link werkt niet meer.",
"Account activeren", "Deze link is {2} geldig.",
"Deze mail is automatisch verstuurd door {0}."),
["en"] = new("New invitation link for {0}", "You have a new invitation link",
"A new invitation link has been created for you for {0}. The previous link no longer works.",
"Activate account", "This link is valid for {2}.",
"This message was sent automatically by {0}.")
},
[MailKind.PasswordReset] = new()
{
["nl"] = new("Wachtwoord opnieuw instellen voor {0}", "Wachtwoord opnieuw instellen",
"Er is gevraagd om het wachtwoord van je account bij {0} opnieuw in te stellen. Gebruik de knop hieronder om een nieuw wachtwoord te kiezen.",
"Nieuw wachtwoord kiezen", "Deze link is {2} geldig en werkt één keer. Heb jij dit niet gevraagd? Negeer deze mail dan: je wachtwoord blijft ongewijzigd.",
"Deze mail is automatisch verstuurd door {0}."),
["en"] = new("Reset your password for {0}", "Reset your password",
"A request was made to reset the password of your account at {0}. Use the button below to choose a new password.",
"Choose a new password", "This link is valid for {2} and works once. Did you not ask for this? Ignore this message: your password stays unchanged.",
"This message was sent automatically by {0}.")
},
[MailKind.AccountDeactivated] = new()
{
["nl"] = new("Je account bij {0} is gedeactiveerd", "Account gedeactiveerd",
"Een beheerder heeft je account bij {0} gedeactiveerd. Je kunt niet meer inloggen.",
null, "Denk je dat dit niet klopt? Neem dan contact op met de beheerder.",
"Deze mail is automatisch verstuurd door {0}."),
["en"] = new("Your account at {0} has been deactivated", "Account deactivated",
"An administrator has deactivated your account at {0}. You can no longer sign in.",
null, "Think this is a mistake? Please contact the administrator.",
"This message was sent automatically by {0}.")
},
[MailKind.AccountReactivated] = new()
{
["nl"] = new("Je account bij {0} is weer actief", "Account weer actief",
"Een beheerder heeft je account bij {0} weer geactiveerd. Je kunt weer inloggen.",
"Inloggen", null, "Deze mail is automatisch verstuurd door {0}."),
["en"] = new("Your account at {0} is active again", "Account active again",
"An administrator has reactivated your account at {0}. You can sign in again.",
"Sign in", null, "This message was sent automatically by {0}.")
},
[MailKind.RoleChanged] = new()
{
["nl"] = new("Je rol bij {0} is gewijzigd", "Rol gewijzigd",
"Een beheerder heeft je rol bij {0} gewijzigd naar: {1}.",
null, "Denk je dat dit niet klopt? Neem dan contact op met de beheerder.",
"Deze mail is automatisch verstuurd door {0}."),
["en"] = new("Your role at {0} has changed", "Role changed",
"An administrator has changed your role at {0} to: {1}.",
null, "Think this is a mistake? Please contact the administrator.",
"This message was sent automatically by {0}.")
}
};
private static readonly Dictionary<string, Dictionary<string, string>> Roles = new()
{
["nl"] = new() { ["Owner"] = "Eigenaar", ["Administrator"] = "Beheerder", ["User"] = "Gebruiker" },
["en"] = new() { ["Owner"] = "Owner", ["Administrator"] = "Administrator", ["User"] = "User" }
};
public RenderedMail Render(MailKind kind, string language, MailModel model)
{
var lang = MailLanguages.Normalize(language) ?? MailLanguages.Dutch;
var perKind = Catalog[kind];
var t = perKind.TryGetValue(lang, out var found) ? found : perKind[MailLanguages.Dutch];
var site = Plain(model.SiteName);
var role = RoleName(lang, model.Detail);
var validity = Validity(lang, model.ValidForMinutes);
string F(string template) => string.Format(template, site, role, validity);
var subject = Plain(F(t.Subject));
var heading = F(t.Heading);
var intro = F(t.Intro);
var note = t.Note is null ? null : F(t.Note);
var footer = F(t.Footer);
var greeting = string.IsNullOrWhiteSpace(model.RecipientName)
? null
: (lang == "en" ? $"Hello {model.RecipientName.Trim()}," : $"Hallo {model.RecipientName.Trim()},");
var colour = EmailAddressRules.IsValidColour(model.BrandColor) ? model.BrandColor! : DefaultColour;
var hasAction = t.Button is not null && !string.IsNullOrEmpty(model.ActionUrl);
return new RenderedMail(subject, BuildHtml(model, site, colour, greeting, heading, intro, hasAction ? t.Button : null, note, footer),
BuildText(greeting, heading, intro, hasAction ? model.ActionUrl : null, note, footer));
}
private static string RoleName(string lang, string? key) =>
key is not null && Roles[lang].TryGetValue(key, out var name) ? name : (key ?? "");
private static string Validity(string lang, int? minutes)
{
if (minutes is null) return "";
var m = minutes.Value;
if (m % 60 == 0)
{
var h = m / 60;
return lang == "en" ? $"{h} hour{(h == 1 ? "" : "s")}" : $"{h} uur";
}
return lang == "en" ? $"{m} minutes" : $"{m} minuten";
}
/// <summary>For the subject and text: no markup, and no line breaks (a subject is a header).</summary>
private static string Plain(string value) => new(value.Where(c => !char.IsControl(c)).ToArray());
private static string E(string value) => WebUtility.HtmlEncode(value);
private static string BuildHtml(
MailModel model, string site, string colour, string? greeting, string heading, string intro,
string? button, string? note, string footer)
{
var sb = new StringBuilder();
sb.Append("<!DOCTYPE html><html><body style=\"margin:0;padding:0;background:#f3f4f6;\">");
sb.Append("<table role=\"presentation\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"background:#f3f4f6;padding:24px 0;\"><tr><td align=\"center\">");
sb.Append("<table role=\"presentation\" width=\"560\" cellpadding=\"0\" cellspacing=\"0\" style=\"max-width:560px;width:100%;background:#ffffff;border-radius:8px;font-family:Arial,Helvetica,sans-serif;color:#111827;\">");
sb.Append($"<tr><td style=\"padding:24px 32px;border-bottom:3px solid {colour};\">");
if (!string.IsNullOrEmpty(model.LogoUrl))
sb.Append($"<img src=\"{E(model.LogoUrl)}\" alt=\"{E(site)}\" height=\"48\" style=\"display:block;height:48px;width:auto;border:0;\">");
else
sb.Append($"<span style=\"font-size:20px;font-weight:bold;color:{colour};\">{E(site)}</span>");
sb.Append("</td></tr><tr><td style=\"padding:32px;font-size:15px;line-height:1.5;\">");
sb.Append($"<h1 style=\"margin:0 0 16px 0;font-size:22px;color:{colour};\">{E(heading)}</h1>");
if (greeting is not null) sb.Append($"<p style=\"margin:0 0 12px 0;\">{E(greeting)}</p>");
sb.Append($"<p style=\"margin:0 0 24px 0;\">{E(intro)}</p>");
if (button is not null && !string.IsNullOrEmpty(model.ActionUrl))
{
sb.Append($"<p style=\"margin:0 0 24px 0;\"><a href=\"{E(model.ActionUrl)}\" style=\"display:inline-block;background:{colour};color:#ffffff;text-decoration:none;padding:12px 24px;border-radius:6px;font-weight:bold;\">{E(button)}</a></p>");
sb.Append($"<p style=\"margin:0 0 24px 0;font-size:13px;color:#4b5563;word-break:break-all;\">{E(model.ActionUrl)}</p>");
}
if (note is not null) sb.Append($"<p style=\"margin:0 0 24px 0;font-size:13px;color:#4b5563;\">{E(note)}</p>");
sb.Append("</td></tr>");
sb.Append($"<tr><td style=\"padding:16px 32px;font-size:12px;color:#6b7280;border-top:1px solid #e5e7eb;\">{E(footer)}</td></tr>");
sb.Append("</table></td></tr></table></body></html>");
return sb.ToString();
}
private static string BuildText(string? greeting, string heading, string intro, string? url, string? note, string footer)
{
var sb = new StringBuilder();
sb.AppendLine(heading).AppendLine();
if (greeting is not null) sb.AppendLine(greeting).AppendLine();
sb.AppendLine(intro).AppendLine();
if (url is not null) sb.AppendLine(url).AppendLine();
if (note is not null) sb.AppendLine(note).AppendLine();
sb.AppendLine("--").AppendLine(footer);
return sb.ToString();
}
}
+63
View File
@@ -0,0 +1,63 @@
namespace SlpModularCms.Core.Email;
/// <summary>Outcome of one send. Sending never throws into the caller: a failure is a value.</summary>
public readonly record struct MailSendResult(bool Sent, string? ErrorCode)
{
public const string Disabled = "disabled";
public const string NotConfigured = "not_configured";
public const string Timeout = "timeout";
public const string AuthFailed = "auth_failed";
public const string Rejected = "rejected";
public const string Unknown = "unknown";
public static MailSendResult Ok { get; } = new(true, null);
public static MailSendResult Fail(string code) => new(false, code);
}
/// <summary>One message to send. <see cref="FromAddress"/>/<see cref="FromName"/> null means the configured defaults.</summary>
public sealed record OutgoingMail(
string ToAddress,
string Subject,
string HtmlBody,
string? TextBody = null,
string? FromAddress = null,
string? FromName = null);
public enum MailKind
{
Invitation,
NewInvitationLink,
PasswordReset,
AccountDeactivated,
AccountReactivated,
RoleChanged
}
/// <summary>Values the template needs. <see cref="Detail"/> carries the role key for <see cref="MailKind.RoleChanged"/>.</summary>
public sealed record MailModel(
string SiteName,
string? RecipientName = null,
string? ActionUrl = null,
int? ValidForMinutes = null,
string? Detail = null,
string? LogoUrl = null,
string? BrandColor = null);
public sealed record RenderedMail(string Subject, string Html, string Text);
public static class MailLanguages
{
public const string Dutch = "nl";
public const string English = "en";
public static bool IsSupported(string? value) => Normalize(value) is not null;
/// <summary>Returns "nl" or "en" for a supported value (case-insensitive, region tags allowed), otherwise null.</summary>
public static string? Normalize(string? value)
{
var v = value?.Trim().ToLowerInvariant();
if (string.IsNullOrEmpty(v)) return null;
var primary = v.Split('-', '_')[0];
return primary is Dutch or English ? primary : null;
}
}
@@ -0,0 +1,82 @@
using MailKit;
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MimeKit;
namespace SlpModularCms.Core.Email;
/// <summary>
/// MailKit/MimeKit sender, following SimpleDeckApp: StartTls when <c>EnableSsl</c>, authenticate only
/// when a username is configured. Every failure is caught here and mapped to a short error code; the
/// exception text is never logged or returned because it can quote addresses.
/// </summary>
public sealed class SmtpEmailSender(IOptions<EmailOptions> options, ILogger<SmtpEmailSender> logger) : IEmailSender
{
private readonly EmailOptions _options = options.Value;
public async Task<MailSendResult> SendAsync(OutgoingMail mail, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(_options.Smtp.Host))
return MailSendResult.Fail(MailSendResult.NotConfigured);
var fromAddress = mail.FromAddress ?? _options.FromAddress;
var fromName = mail.FromName ?? _options.FromName;
// Everything that becomes a header is checked first: a bad value is refused, never sent.
if (!EmailAddressRules.IsValidAddress(mail.ToAddress)
|| !EmailAddressRules.IsValidAddress(fromAddress)
|| EmailAddressRules.ContainsControlCharacters(mail.Subject)
|| EmailAddressRules.ContainsControlCharacters(fromName))
{
logger.LogWarning("identity_mail_failed code={Code} reason=invalid_header", MailSendResult.Rejected);
return MailSendResult.Fail(MailSendResult.Rejected);
}
var message = new MimeMessage();
message.From.Add(new MailboxAddress(fromName, fromAddress));
message.To.Add(MailboxAddress.Parse(mail.ToAddress));
message.Subject = mail.Subject;
message.Body = new BodyBuilder { HtmlBody = mail.HtmlBody, TextBody = mail.TextBody }.ToMessageBody();
var timeout = TimeSpan.FromSeconds(_options.Smtp.TimeoutSeconds);
using var timeoutSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeoutSource.CancelAfter(timeout);
try
{
using var client = new SmtpClient { Timeout = (int)timeout.TotalMilliseconds };
await client.ConnectAsync(
_options.Smtp.Host,
_options.Smtp.Port,
_options.Smtp.EnableSsl ? SecureSocketOptions.StartTls : SecureSocketOptions.None,
timeoutSource.Token);
if (!string.IsNullOrEmpty(_options.Smtp.Username))
await client.AuthenticateAsync(_options.Smtp.Username, _options.Smtp.Password, timeoutSource.Token);
await client.SendAsync(message, timeoutSource.Token);
await client.DisconnectAsync(true, timeoutSource.Token);
return MailSendResult.Ok;
}
catch (Exception ex)
{
var code = Map(ex, cancellationToken);
// The exception TYPE only: its message may contain the recipient or server replies.
logger.LogWarning("identity_mail_failed code={Code} exception={ExceptionType}", code, ex.GetType().Name);
return MailSendResult.Fail(code);
}
}
private static string Map(Exception ex, CancellationToken callerToken) => ex switch
{
OperationCanceledException when !callerToken.IsCancellationRequested => MailSendResult.Timeout,
TimeoutException => MailSendResult.Timeout,
OperationCanceledException => MailSendResult.Unknown,
AuthenticationException => MailSendResult.AuthFailed,
SmtpCommandException or SmtpProtocolException or SslHandshakeException => MailSendResult.Rejected,
ServiceNotConnectedException or ServiceNotAuthenticatedException => MailSendResult.Rejected,
_ => MailSendResult.Unknown
};
}