Files
UniVerse/backend/UniVerse.Infrastructure/Notifications/EmailNotificationProvider.cs
T
serega404 a0a0575a99
🚀 Create and publish a Docker image / Detect changes in backend and frontend (push) Successful in 10s
🚀 Create and publish a Docker image / Build & publish backend image (push) Successful in 1m17s
🚀 Create and publish a Docker image / Build & publish frontend image (push) Successful in 12s
🚀 Create and publish a Docker image / Update stack on Portainer (push) Successful in 6s
feat: добавил отправку уведомлений по почте
2026-05-11 05:09:00 +03:00

58 lines
2.0 KiB
C#

using System.Net;
using System.Net.Mail;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using UniVerse.Application.DTOs.Notifications;
using UniVerse.Application.Interfaces;
namespace UniVerse.Infrastructure.Notifications;
public class EmailNotificationProvider : INotificationProvider
{
private readonly EmailNotificationOptions _options;
private readonly ILogger<EmailNotificationProvider> _logger;
public EmailNotificationProvider(IOptions<EmailNotificationOptions> options, ILogger<EmailNotificationProvider> logger)
{
_options = options.Value;
_logger = logger;
}
public string Channel => NotificationChannels.Email;
public async Task SendAsync(NotificationMessage message, CancellationToken cancellationToken = default)
{
ValidateOptions();
using var mailMessage = new MailMessage
{
From = new MailAddress(_options.FromAddress, _options.FromName),
Subject = message.Subject,
Body = message.Body,
IsBodyHtml = false
};
mailMessage.To.Add(new MailAddress(message.Recipient, message.RecipientName));
using var client = new SmtpClient(_options.Host, _options.Port)
{
EnableSsl = _options.EnableSsl
};
if (!string.IsNullOrWhiteSpace(_options.UserName))
{
client.Credentials = new NetworkCredential(_options.UserName, _options.Password);
}
_logger.LogInformation("Sending email notification to {Recipient}", message.Recipient);
await client.SendMailAsync(mailMessage, cancellationToken);
}
private void ValidateOptions()
{
if (string.IsNullOrWhiteSpace(_options.Host))
throw new InvalidOperationException("Email:Smtp:Host is not configured.");
if (string.IsNullOrWhiteSpace(_options.FromAddress))
throw new InvalidOperationException("Email:Smtp:FromAddress is not configured.");
}
}