Files
Heimdall/src/Heimdall.Infrastructure/Services/EmailService.cs
T
Arnaud Dartois 71e869a011
Heimdall Gitea / Build and scan server image (pull_request) Canceled after 0s
Heimdall Gitea / Build and scan agent image (pull_request) Canceled after 0s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Canceled after 0s
Heimdall Gitea / Publish versioned release (pull_request) Canceled after 0s
Heimdall Gitea / Build and tests (pull_request) Canceled after 43s
feat(notifications): persist external deliveries in outbox
2026-10-24 22:27:53 +02:00

116 lines
4.8 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))
{
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
}
}
/// <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);
}
}