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 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}"; } } }