| | | 1 | | using System.Net; |
| | | 2 | | using System.Net.Mail; |
| | | 3 | | using Microsoft.Extensions.Logging; |
| | | 4 | | using Microsoft.Extensions.Options; |
| | | 5 | | using SlqStudio.Application.Services.EmailService.Models; |
| | | 6 | | |
| | | 7 | | namespace SlqStudio.Application.Services.EmailService.Implementation; |
| | | 8 | | |
| | 0 | 9 | | public sealed class HtmlEmailSender(IOptions<SmtpSettings> options, ILogger<HtmlEmailSender> logger) : IHtmlEmailSender |
| | | 10 | | { |
| | | 11 | | public async Task<bool> SendAsync(string toAddress, string subject, string htmlBody, CancellationToken ct = default) |
| | | 12 | | { |
| | 0 | 13 | | var smtpSettings = options.Value; |
| | | 14 | | try |
| | | 15 | | { |
| | 0 | 16 | | using var message = new MailMessage( |
| | 0 | 17 | | new MailAddress(smtpSettings.SenderEmail ?? string.Empty, smtpSettings.SenderName), |
| | 0 | 18 | | new MailAddress(toAddress)) |
| | 0 | 19 | | { |
| | 0 | 20 | | Subject = subject, |
| | 0 | 21 | | Body = htmlBody, |
| | 0 | 22 | | IsBodyHtml = true |
| | 0 | 23 | | }; |
| | | 24 | | |
| | 0 | 25 | | using var smtp = new SmtpClient(smtpSettings.Server, smtpSettings.Port) |
| | 0 | 26 | | { |
| | 0 | 27 | | Credentials = new NetworkCredential(smtpSettings.SenderEmail, smtpSettings.Password), |
| | 0 | 28 | | EnableSsl = smtpSettings.EnableSsl |
| | 0 | 29 | | }; |
| | | 30 | | |
| | 0 | 31 | | await smtp.SendMailAsync(message, ct); |
| | 0 | 32 | | return true; |
| | | 33 | | } |
| | 0 | 34 | | catch (Exception ex) |
| | | 35 | | { |
| | | 36 | | // Адрес получателя в журнал не пишем: достаточно причины сбоя. |
| | 0 | 37 | | logger.LogWarning(ex, "Не удалось отправить письмо через SMTP"); |
| | 0 | 38 | | return false; |
| | | 39 | | } |
| | 0 | 40 | | } |
| | | 41 | | } |