using MailKit; using MailKit.Net.Smtp; using MailKit.Security; using Microsoft.Extensions.Options; using MimeKit; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Tsi1.BusinessLayer.Dtos; using Tsi1.BusinessLayer.Helpers; using Tsi1.BusinessLayer.Interfaces; using Tsi1.DataLayer.Entities; namespace Tsi1.BusinessLayer.Services { public class EmailService : IEmailService { private readonly MailSettings _mailSettings; public EmailService(IOptions<MailSettings> mailSettings) { _mailSettings = mailSettings.Value; } public async Task<ServiceResult<bool>> SendEmailAsync(MimeMessage message) { ServiceResult<bool> result = new ServiceResult<bool>(); message.Sender = MailboxAddress.Parse(_mailSettings.Mail); var client = new SmtpClient(); client.CheckCertificateRevocation = false; try { await client.ConnectAsync(_mailSettings.Host, _mailSettings.Port, SecureSocketOptions.StartTls); } catch (Exception e) { result.HasError = true; result.Message = ErrorMessages.CannotConnectToSmtpServer; return result; } try { await client.AuthenticateAsync(_mailSettings.Mail, _mailSettings.Password); } catch (Exception) { result.HasError = true; result.Message = ErrorMessages.CannotAuthenticateToSmtpServer; return result; } try { await client.SendAsync(message); } catch (Exception) { result.HasError = true; result.Message = string.Format(ErrorMessages.CannotSendEmail, message.Subject); return result; } await client.DisconnectAsync(true); return result; } public async Task<ServiceResult<bool>> NotifyNewPostOrMessage(PostCreateDto postCreateDto, List<string> mails) { var message = new MimeMessage(); foreach (var mail in mails) { message.To.Add(MailboxAddress.Parse(mail)); } message.Subject = $"Nuevo Post: {postCreateDto.Title}"; message.Body = new TextPart("html") { Text = $"<p> Hay un nuevo post perteneciente al foro suscripto." }; var result = await SendEmailAsync(message); return result; } } }