39 lines
1.5 KiB
C#
39 lines
1.5 KiB
C#
using MailKit.Net.Smtp;
|
|
using MailKit.Security;
|
|
using Microsoft.Extensions.Options;
|
|
using MimeKit;
|
|
|
|
namespace ROLAC.API.Services.Notifications;
|
|
|
|
/// <summary>Sends a single email via MailKit using the configured SMTP server.</summary>
|
|
public sealed class MailKitSmtpDispatcher : ISmtpDispatcher
|
|
{
|
|
private readonly SmtpOptions _options;
|
|
|
|
public MailKitSmtpDispatcher(IOptions<SmtpOptions> options) => _options = options.Value;
|
|
|
|
public async Task SendAsync(OutboundEmail email, CancellationToken ct = default)
|
|
{
|
|
var message = new MimeMessage();
|
|
message.From.Add(new MailboxAddress(_options.FromName, _options.FromAddress));
|
|
message.To.Add(MailboxAddress.Parse(email.ToAddress));
|
|
message.Subject = email.Subject;
|
|
|
|
var builder = new BodyBuilder { HtmlBody = email.HtmlBody };
|
|
foreach (var attachment in email.Attachments)
|
|
{
|
|
builder.Attachments.Add(
|
|
attachment.FileName, attachment.Content, ContentType.Parse(attachment.ContentType));
|
|
}
|
|
message.Body = builder.ToMessageBody();
|
|
|
|
using var client = new SmtpClient();
|
|
var socketOptions = _options.UseSsl ? SecureSocketOptions.StartTls : SecureSocketOptions.Auto;
|
|
await client.ConnectAsync(_options.Host, _options.Port, socketOptions, ct);
|
|
if (!string.IsNullOrEmpty(_options.User))
|
|
await client.AuthenticateAsync(_options.User, _options.Password, ct);
|
|
await client.SendAsync(message, ct);
|
|
await client.DisconnectAsync(true, ct);
|
|
}
|
|
}
|