Files
Heimdall/src/Heimdall.Infrastructure/Services/EmailService.cs
T
Arnaud Dartois 97d0b76a5e feat(settings): NtfyService/EmailService/AiHealthCheck lisent les AppSettings (partiel #80)
- Source de vérité DB (ntfy.*, email.*, ai.cpaiUrl, ai.ollamaUrl) avec
  fallback config/env pour migration douce — relu à chaque appel, une
  modification UI est prise en compte sans redémarrage
- Nouveau helper AppSettingReader (lecture async + parse int/bool, silencieux
  si DB indisponible), pattern StorageProviderFactory (scope + DbContext)
- Les env vars restent en fallback uniquement
2026-08-12 11:04:04 +02:00

117 lines
5.0 KiB
C#

using System.Net;
using System.Net.Mail;
using Heimdall.Application.Common;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Settings;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Services;
public class EmailService : IEmailService
{
private readonly ILogger<EmailService> _logger;
private readonly IServiceProvider _services;
private readonly IConfiguration _configuration;
public EmailService(IServiceProvider services, IConfiguration configuration, ILogger<EmailService> logger)
{
_services = services;
_configuration = configuration;
_logger = logger;
}
public async Task SendEmailAsync(string recipient, string subject, string bodyHtml, CancellationToken ct = default)
{
var (smtpHost, smtpPort, username, password, fromAddress, fromName, useSsl) =
await ResolveConfigAsync(ct).ConfigureAwait(false);
if (string.IsNullOrEmpty(smtpHost))
{
_logger.LogWarning("Email not sent: SMTP not configured (set Email:SmtpHost). To={To}, Subject={Subject}", recipient, subject);
return;
}
try
{
using var message = new MailMessage
{
From = new MailAddress(fromAddress!, fromName),
Subject = subject,
Body = bodyHtml,
IsBodyHtml = true
};
message.To.Add(recipient);
using var client = new SmtpClient(smtpHost, smtpPort)
{
EnableSsl = useSsl,
DeliveryMethod = SmtpDeliveryMethod.Network
};
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
client.Credentials = new NetworkCredential(username, password);
}
await client.SendMailAsync(message, ct).ConfigureAwait(false);
_logger.LogDebug("Email sent to {To}: {Subject}", recipient, subject);
}
catch (OperationCanceledException)
{
_logger.LogDebug("Email cancelled for {To}: {Subject}", recipient, subject);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send email to {To}: {Subject}", recipient, subject);
throw; // Re-throw so Hangfire can retry
}
}
/// <summary>
/// Source de vérité : AppSettings en base (email.*), avec fallback
/// config/appsettings puis env (migration douce, ticket #80). Relu à
/// chaque envoi pour prendre en compte les modifications de l'UI.
/// </summary>
private async Task<(string? SmtpHost, int SmtpPort, string? Username, string? Password,
string? FromAddress, string? FromName, bool UseSsl)> ResolveConfigAsync(CancellationToken ct)
{
using var scope = _services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
var smtpHost = await AppSettingReader.GetAsync(db, "email.smtpHost", ct).ConfigureAwait(false)
?? _configuration.GetValue<string>("Email:SmtpHost")
?? Environment.GetEnvironmentVariable("EMAIL__SMTP_HOST");
var smtpPort = await AppSettingReader.GetIntAsync(db, "email.smtpPort", -1, ct).ConfigureAwait(false);
if (smtpPort < 0)
smtpPort = _configuration.GetValue<int?>("Email:SmtpPort")
?? (int.TryParse(Environment.GetEnvironmentVariable("EMAIL__SMTP_PORT"), out var port) ? port : 587);
var username = await AppSettingReader.GetAsync(db, "email.username", ct).ConfigureAwait(false)
?? _configuration.GetValue<string>("Email:Username")
?? Environment.GetEnvironmentVariable("EMAIL__USERNAME");
var password = await AppSettingReader.GetAsync(db, "email.password", ct).ConfigureAwait(false)
?? _configuration.GetValue<string>("Email:Password")
?? Environment.GetEnvironmentVariable("EMAIL__PASSWORD");
var fromAddress = await AppSettingReader.GetAsync(db, "email.fromAddress", ct).ConfigureAwait(false)
?? _configuration.GetValue<string>("Email:FromAddress")
?? Environment.GetEnvironmentVariable("EMAIL__FROM_ADDRESS") ?? "noreply@heimdall.local";
var fromName = await AppSettingReader.GetAsync(db, "email.fromName", ct).ConfigureAwait(false)
?? _configuration.GetValue<string>("Email:FromName")
?? Environment.GetEnvironmentVariable("EMAIL__FROM_NAME") ?? "Heimdall";
var useSsl = await AppSettingReader.GetBoolAsync(db, "email.useSsl", true, ct).ConfigureAwait(false);
if (_configuration.GetValue<bool?>("Email:UseSsl") is { } cfgSsl)
useSsl = cfgSsl;
else if (bool.TryParse(Environment.GetEnvironmentVariable("EMAIL__USE_SSL"), out var envSsl))
useSsl = envSsl;
return (smtpHost, smtpPort, username, password, fromAddress, fromName, useSsl);
}
}