c5c33f7023
CI / backend (push) Successful in 53s
CI / frontend (push) Successful in 14s
Deploy Staging / deploy (push) Successful in 28s
Security / secrets (push) Successful in 3s
Security / dependencies (push) Successful in 59s
CI / backend (pull_request) Successful in 51s
CI / frontend (pull_request) Successful in 15s
Security / secrets (pull_request) Successful in 3s
Security / dependencies (pull_request) Successful in 56s
47 lines
1.7 KiB
C#
47 lines
1.7 KiB
C#
using InboxIntel.Application.Abstractions;
|
|
using InboxIntel.Infrastructure.Configuration;
|
|
using MailKit.Net.Smtp;
|
|
using MailKit.Security;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
using MimeKit;
|
|
|
|
namespace InboxIntel.Infrastructure.Notifications;
|
|
|
|
public class SmtpEmailSender : IEmailSender
|
|
{
|
|
private readonly SmtpOptions _options;
|
|
private readonly ILogger<SmtpEmailSender> _logger;
|
|
|
|
public SmtpEmailSender(IOptions<SmtpOptions> options, ILogger<SmtpEmailSender> logger)
|
|
{
|
|
_options = options.Value;
|
|
_logger = logger;
|
|
}
|
|
|
|
public bool IsEnabled => _options.Enabled && !string.IsNullOrWhiteSpace(_options.Host);
|
|
|
|
public async Task SendAsync(string toAddress, string subject, string htmlBody, CancellationToken ct = default)
|
|
{
|
|
if (!IsEnabled)
|
|
{
|
|
_logger.LogDebug("SMTP not configured; skipping email \"{Subject}\" to {To}", subject, toAddress);
|
|
return;
|
|
}
|
|
|
|
var message = new MimeMessage();
|
|
message.From.Add(new MailboxAddress(_options.FromName, _options.FromAddress));
|
|
message.To.Add(MailboxAddress.Parse(toAddress));
|
|
message.Subject = subject;
|
|
message.Body = new BodyBuilder { HtmlBody = htmlBody }.ToMessageBody();
|
|
|
|
using var client = new SmtpClient();
|
|
var socketOptions = _options.UseSsl ? SecureSocketOptions.StartTls : SecureSocketOptions.None;
|
|
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);
|
|
}
|
|
}
|