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 _logger; private readonly IServiceProvider _services; private readonly IConfiguration _configuration; public EmailService(IServiceProvider services, IConfiguration configuration, ILogger 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 } } /// /// 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. /// 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(); var smtpHost = await AppSettingReader.GetAsync(db, "email.smtpHost", ct).ConfigureAwait(false) ?? _configuration.GetValue("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("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("Email:Username") ?? Environment.GetEnvironmentVariable("EMAIL__USERNAME"); var password = await AppSettingReader.GetAsync(db, "email.password", ct).ConfigureAwait(false) ?? _configuration.GetValue("Email:Password") ?? Environment.GetEnvironmentVariable("EMAIL__PASSWORD"); var fromAddress = await AppSettingReader.GetAsync(db, "email.fromAddress", ct).ConfigureAwait(false) ?? _configuration.GetValue("Email:FromAddress") ?? Environment.GetEnvironmentVariable("EMAIL__FROM_ADDRESS") ?? "noreply@heimdall.local"; var fromName = await AppSettingReader.GetAsync(db, "email.fromName", ct).ConfigureAwait(false) ?? _configuration.GetValue("Email:FromName") ?? Environment.GetEnvironmentVariable("EMAIL__FROM_NAME") ?? "Heimdall"; var useSsl = await AppSettingReader.GetBoolAsync(db, "email.useSsl", true, ct).ConfigureAwait(false); if (_configuration.GetValue("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); } }