using MailKit.Net.Smtp; using MimeKit; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System.Threading.Tasks; using System.Collections.Generic; namespace DysonNetwork.Shared.Services; public class EmailService { private readonly IConfiguration _configuration; private readonly ILogger _logger; public EmailService(IConfiguration configuration, ILogger logger) { _configuration = configuration; _logger = logger; } public async Task SendEmailAsync( string toName, string toEmail, string subject, string body, Dictionary? headers = null ) { var message = new MimeMessage(); message.From.Add(new MailboxAddress( _configuration["Email:SenderName"], _configuration["Email:SenderEmail"] )); message.To.Add(new MailboxAddress(toName, toEmail)); message.Subject = subject; var bodyBuilder = new BodyBuilder { HtmlBody = body }; message.Body = bodyBuilder.ToMessageBody(); if (headers != null) { foreach (var header in headers) { message.Headers.Add(header.Key, header.Value); } } using var client = new SmtpClient(); try { await client.ConnectAsync( _configuration["Email:SmtpHost"], int.Parse(_configuration["Email:SmtpPort"]), MailKit.Security.SecureSocketOptions.StartTls ); await client.AuthenticateAsync( _configuration["Email:SmtpUser"], _configuration["Email:SmtpPass"] ); await client.SendAsync(message); _logger.LogInformation("Email sent to {ToEmail}", toEmail); } catch (Exception ex) { _logger.LogError(ex, "Failed to send email to {ToEmail}", toEmail); throw; } finally { await client.DisconnectAsync(true); } } public async Task SendTemplatedEmailAsync(string toName, string toEmail, string subject, string htmlBody) { await SendEmailAsync(toName, toEmail, subject, htmlBody); } }