@@ -1,21 +1,22 @@
|
||||
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>
|
||||
/// <summary>Sends a single email via MailKit using the current (DB-backed) SMTP settings.</summary>
|
||||
public sealed class MailKitSmtpDispatcher : ISmtpDispatcher
|
||||
{
|
||||
private readonly SmtpOptions _options;
|
||||
private readonly INotificationSettingsService _settings;
|
||||
|
||||
public MailKitSmtpDispatcher(IOptions<SmtpOptions> options) => _options = options.Value;
|
||||
public MailKitSmtpDispatcher(INotificationSettingsService settings) => _settings = settings;
|
||||
|
||||
public async Task SendAsync(OutboundEmail email, CancellationToken ct = default)
|
||||
{
|
||||
var options = _settings.GetSmtp();
|
||||
|
||||
var message = new MimeMessage();
|
||||
message.From.Add(new MailboxAddress(_options.FromName, _options.FromAddress));
|
||||
message.From.Add(new MailboxAddress(options.FromName, options.FromAddress));
|
||||
message.To.Add(MailboxAddress.Parse(email.ToAddress));
|
||||
message.Subject = email.Subject;
|
||||
|
||||
@@ -28,10 +29,10 @@ public sealed class MailKitSmtpDispatcher : ISmtpDispatcher
|
||||
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);
|
||||
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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user