50 lines
1.9 KiB
C#
50 lines
1.9 KiB
C#
|
|
using GestionIntegral.Api.Models.Comunicaciones;
|
||
|
|
using MailKit.Net.Smtp;
|
||
|
|
using MailKit.Security;
|
||
|
|
using Microsoft.Extensions.Options;
|
||
|
|
using MimeKit;
|
||
|
|
|
||
|
|
namespace GestionIntegral.Api.Services.Comunicaciones
|
||
|
|
{
|
||
|
|
public class EmailService : IEmailService
|
||
|
|
{
|
||
|
|
private readonly MailSettings _mailSettings;
|
||
|
|
private readonly ILogger<EmailService> _logger;
|
||
|
|
|
||
|
|
public EmailService(IOptions<MailSettings> mailSettings, ILogger<EmailService> logger)
|
||
|
|
{
|
||
|
|
_mailSettings = mailSettings.Value;
|
||
|
|
_logger = logger;
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task EnviarEmailAsync(string destinatarioEmail, string destinatarioNombre, string asunto, string cuerpoHtml)
|
||
|
|
{
|
||
|
|
var email = new MimeMessage();
|
||
|
|
email.Sender = new MailboxAddress(_mailSettings.SenderName, _mailSettings.SenderEmail);
|
||
|
|
email.From.Add(email.Sender);
|
||
|
|
email.To.Add(new MailboxAddress(destinatarioNombre, destinatarioEmail));
|
||
|
|
email.Subject = asunto;
|
||
|
|
|
||
|
|
var builder = new BodyBuilder { HtmlBody = cuerpoHtml };
|
||
|
|
email.Body = builder.ToMessageBody();
|
||
|
|
|
||
|
|
using var smtp = new SmtpClient();
|
||
|
|
try
|
||
|
|
{
|
||
|
|
await smtp.ConnectAsync(_mailSettings.SmtpHost, _mailSettings.SmtpPort, SecureSocketOptions.StartTls);
|
||
|
|
await smtp.AuthenticateAsync(_mailSettings.SmtpUser, _mailSettings.SmtpPass);
|
||
|
|
await smtp.SendAsync(email);
|
||
|
|
_logger.LogInformation("Email enviado exitosamente a {Destinatario}", destinatarioEmail);
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
_logger.LogError(ex, "Error al enviar email a {Destinatario}", destinatarioEmail);
|
||
|
|
throw; // Relanzar para que el servicio que lo llamó sepa que falló
|
||
|
|
}
|
||
|
|
finally
|
||
|
|
{
|
||
|
|
await smtp.DisconnectAsync(true);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|