using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace SlpModularCms.Core.Email; /// /// Whether this host can send mail. THE single answer: the sender, the mail service, the site settings and /// the capabilities endpoint all ask this, so they can never disagree. /// public interface IMailAvailability { /// True only when an SMTP host is set AND the whole mail configuration is valid. bool IsEnabled { get; } /// Why mail is off although a host was set (setting names only, never values). Empty otherwise. IReadOnlyList Problems { get; } } /// /// Decides once, at start-up. A host without mail settings simply has mail off. A host with a half-finished or /// wrong mail configuration does NOT fail to start (mail is secondary to the site being up): it starts with mail /// off and one clear Error log line naming each missing or invalid setting. No secret or value is ever logged. /// public sealed class MailAvailability : IMailAvailability { public bool IsEnabled { get; } public IReadOnlyList Problems { get; } public MailAvailability(IOptions email, IOptions app, ILogger logger) { if (string.IsNullOrWhiteSpace(email.Value.Smtp.Host)) { Problems = []; IsEnabled = false; return; } Problems = EmailOptionsValidator.Check(email.Value, app.Value); IsEnabled = Problems.Count == 0; if (!IsEnabled) { // The messages name settings (for example "App:PublicBaseUrl"), never their values. logger.LogError( "mail_configuration_invalid: an SMTP host is set but the mail configuration is incomplete or invalid, so mail stays OFF and the site runs without it. Fix these settings and restart: {Problems}", string.Join(" | ", Problems)); } } } /// Makes the decision (and its Error log line) happen at start-up instead of at the first mail. public sealed class MailStartupCheck(IMailAvailability availability, IOptions email, ILogger logger) : IHostedService { public Task StartAsync(CancellationToken cancellationToken) { var o = email.Value; if (availability.IsEnabled) { // Where mail goes through and with which default sender DOMAIN (not the address): what a refused // MAIL FROM is checked against. A sender chosen in the site settings can differ from this default. var at = o.FromAddress.LastIndexOf('@'); logger.LogInformation( "mail_status enabled=true smtp_host={Host} smtp_port={Port} starttls={StartTls} default_from_domain={FromDomain}", o.Smtp.Host, o.Smtp.Port, o.Smtp.EnableSsl, at >= 0 ? o.FromAddress[(at + 1)..] : "?"); } else { logger.LogInformation("mail_status enabled=false"); } return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; }