using System.Net; using System.Net.Mail; using Heimdall.Application.Common; using Heimdall.Application.Services; using Heimdall.Infrastructure.Settings; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Heimdall.Infrastructure.Services; public class EmailService : IEmailService { private readonly ILogger _logger; private readonly IServiceProvider _services; public EmailService(IServiceProvider services, ILogger logger) { _services = services; _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)) { throw new InvalidOperationException("SMTP is not configured; email delivery cannot be completed."); } 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) { throw; } 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 globaux en base (email.*), relus à /// chaque envoi pour prendre en compte les modifications de l'IHM. /// 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); var smtpPort = await AppSettingReader.GetIntAsync(db, "email.smtpPort", -1, ct).ConfigureAwait(false); if (smtpPort < 0) smtpPort = 587; var username = await AppSettingReader.GetAsync(db, "email.username", ct).ConfigureAwait(false); var password = await AppSettingReader.GetAsync(db, "email.password", ct).ConfigureAwait(false); var fromAddress = await AppSettingReader.GetAsync(db, "email.fromAddress", ct).ConfigureAwait(false) ?? "noreply@heimdall.local"; var fromName = await AppSettingReader.GetAsync(db, "email.fromName", ct).ConfigureAwait(false) ?? "Heimdall"; var useSsl = await AppSettingReader.GetBoolAsync(db, "email.useSsl", true, ct).ConfigureAwait(false); return (smtpHost, smtpPort, username, password, fromAddress, fromName, useSsl); } }