70 lines
2.4 KiB
C#
70 lines
2.4 KiB
C#
using MailKit.Net.Smtp;
|
|
using MailKit.Security;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
using MimeKit;
|
|
using MotoresArgentinosV2.Core.Interfaces;
|
|
using MotoresArgentinosV2.Core.Models;
|
|
using System.Net.Security;
|
|
|
|
namespace MotoresArgentinosV2.Infrastructure.Services;
|
|
|
|
public class SmtpEmailService : IEmailService
|
|
{
|
|
private readonly MailSettings _mailSettings;
|
|
private readonly ILogger<SmtpEmailService> _logger;
|
|
|
|
public SmtpEmailService(IOptions<MailSettings> mailSettings, ILogger<SmtpEmailService> logger)
|
|
{
|
|
_mailSettings = mailSettings.Value;
|
|
_logger = logger;
|
|
}
|
|
|
|
public async Task SendEmailAsync(string to, string subject, string htmlBody)
|
|
{
|
|
var email = new MimeMessage();
|
|
email.Sender = new MailboxAddress(_mailSettings.SenderName, _mailSettings.SenderEmail);
|
|
email.From.Add(email.Sender);
|
|
email.To.Add(new MailboxAddress(to, to)); // Usamos el email como nombre si no lo tenemos
|
|
email.Subject = subject;
|
|
|
|
var builder = new BodyBuilder { HtmlBody = htmlBody };
|
|
email.Body = builder.ToMessageBody();
|
|
|
|
using var smtp = new SmtpClient();
|
|
try
|
|
{
|
|
// Bypass de SSL para red interna / certificados autofirmados
|
|
smtp.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
|
|
|
|
// Conectar
|
|
// SecureSocketOptions.StartTls es lo estándar para puerto 587
|
|
// Si el servidor es muy viejo y no soporta TLS, usa SecureSocketOptions.None
|
|
await smtp.ConnectAsync(_mailSettings.SmtpHost, _mailSettings.SmtpPort, SecureSocketOptions.StartTls);
|
|
|
|
// Autenticar
|
|
if (!string.IsNullOrEmpty(_mailSettings.SmtpUser))
|
|
{
|
|
await smtp.AuthenticateAsync(_mailSettings.SmtpUser, _mailSettings.SmtpPass);
|
|
}
|
|
|
|
// Enviar
|
|
await smtp.SendAsync(email);
|
|
|
|
_logger.LogInformation("Email enviado exitosamente a {To}", to);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error crítico enviando email a {To} mediante MailKit", to);
|
|
// Re-lanzar para que el IdentityService sepa que falló
|
|
throw;
|
|
}
|
|
finally
|
|
{
|
|
if (smtp.IsConnected)
|
|
{
|
|
await smtp.DisconnectAsync(true);
|
|
}
|
|
}
|
|
}
|
|
} |