using MailKit.Net.Smtp;
using MediatR;
using MimeKit;
using Quotifyr.Commands;
namespace Quotifyr.Handlers;
public class SendEmailHandler : IRequestHandler<MailMessageCommand>
{
public async Task Handle(MailMessageCommand request, CancellationToken cancellationToken)
{
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress("Quotifyr", SecretSettings.EmailAddress));
mimeMessage.To.Add(new MailboxAddress(request.UserName, request.To));
mimeMessage.Subject = request.Subject;
var bodyBuilder = new BodyBuilder();
if (request.IsHtml)
bodyBuilder.HtmlBody = request.Body;
else
bodyBuilder.TextBody = request.Body;
mimeMessage.Body = bodyBuilder.ToMessageBody();
using var client = new SmtpClient();
await client.ConnectAsync(SecretSettings.SmtpServer, SecretSettings.SmtpPort,
cancellationToken: cancellationToken);
await client.AuthenticateAsync(SecretSettings.EmailAddress, SecretSettings.EmailAddressPassword,
cancellationToken);
await client.SendAsync(mimeMessage, cancellationToken);
await client.DisconnectAsync(true, cancellationToken);
}
}