using back.Options; using Microsoft.Extensions.Options; using System.Net; using System.Net.Mail; namespace back.services.engine.mailing; public class EmailService(IOptions options) : IEmailService { public async Task SendEmailAsync(List tos, string from, string subject, string body, Dictionary? attachments = null, CancellationToken cancellationToken = default) { try { await Parallel.ForEachAsync(tos, async (to, cancellationToken) => { await SendEmailAsync(to, from, subject, body, attachments, cancellationToken); }); } catch (Exception ex) { // Log the exception or handle it as needed Console.WriteLine($"Error sending email to multiple recipients: {ex.Message}"); } } public async Task SendEmailAsync(string to, string from, string subject, string body, Dictionary? attachments = null, CancellationToken cancellationToken = default) { try { using var message = new MailMessage(); message.From = new MailAddress(from); message.To.Add(to); message.Subject = subject; message.Body = body; message.IsBodyHtml = true; message.Priority = MailPriority.Normal; message.DeliveryNotificationOptions = DeliveryNotificationOptions.Never; if (attachments != null) { foreach (var attachment in attachments) { if (attachment.Value is FileStream fileStream) { message.Attachments.Add(new Attachment(fileStream, attachment.Key)); } if (attachment.Value is string filePath && File.Exists(filePath)) { message.Attachments.Add(new Attachment(filePath)); } } } using var cliente = new SmtpClient(options.Value.SmtpServer, options.Value.Puerto); cliente.UseDefaultCredentials = false; cliente.Credentials = new NetworkCredential(options.Value.Usuario, options.Value.Password); cliente.EnableSsl = options.Value.EnableSsl; cliente.DeliveryMethod = SmtpDeliveryMethod.Network; await cliente.SendMailAsync(message, cancellationToken); } catch (Exception ex) { // Log the exception or handle it as needed Console.WriteLine($"Error sending email: {ex.Message}"); } } }