Files
rm-ventas/services-externos/src/ServicesExternos.API/Services/EmailService.cs
T
Nurfog c43dbcce8b feat: fase 2 - services externos (dte, transbank, email)
- New solution ServicesExternos.slnx with standalone API project
- DteService + DteController (LibreDTE: emitir, generar PDF, consultar folio)
- TransbankService + TransbankController (crear transacción, confirmar, voucher SP)
- EmailService + EmailController (MailKit: send with HTML + attachments)
- Models for DTE, Transbank, Email requests/responses
- Dockerfile + appsettings.json with all service configs
- HttpClient factory for Transbank and LibreDTE
- Build: 0 errors
2026-07-08 10:33:21 -04:00

71 lines
2.4 KiB
C#

using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using ServicesExternos.API.Models;
namespace ServicesExternos.API.Services;
public class EmailService
{
private readonly string _smtpHost;
private readonly int _smtpPort;
private readonly string _smtpUser;
private readonly string _smtpPassword;
public EmailService(IConfiguration configuration)
{
_smtpHost = configuration["Email:Host"] ?? "smtp.gmail.com";
_smtpPort = int.Parse(configuration["Email:Port"] ?? "587");
_smtpUser = configuration["Email:User"] ?? "noresponder@norteamericano.cl";
_smtpPassword = configuration["Email:Password"] ?? "";
}
public async Task<string> SendAsync(EmailRequest request)
{
try
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Norteamericano", _smtpUser));
message.To.Add(new MailboxAddress("", request.To));
message.Subject = request.Subject;
var body = new TextPart(request.IsHtml ? "html" : "plain")
{
Text = request.Body
};
if (request.AttachmentPaths != null && request.AttachmentPaths.Count > 0)
{
var multipart = new Multipart("mixed") { body };
foreach (var path in request.AttachmentPaths)
{
if (File.Exists(path))
multipart.Add(new MimePart("application", "pdf")
{
Content = new MimeContent(File.OpenRead(path), ContentEncoding.Default),
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
FileName = Path.GetFileName(path)
});
}
message.Body = multipart;
}
else
{
message.Body = body;
}
using var client = new SmtpClient();
await client.ConnectAsync(_smtpHost, _smtpPort, SecureSocketOptions.StartTls);
await client.AuthenticateAsync(_smtpUser, _smtpPassword);
await client.SendAsync(message);
await client.DisconnectAsync(true);
return "ok";
}
catch (Exception ex)
{
return $"Error: {ex.Message}";
}
}
}