using AsbCloudApp.Data; using AsbCloudApp.Exceptions; using AsbCloudApp.Repositories; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Diagnostics; using System.Net.Mail; using System.Threading; using System.Threading.Tasks; namespace AsbCloudInfrastructure.Background { /// /// Класс для отправки email /// internal class WorkToSendEmail : Work { private NotificationDto notification; private string sender; private string smtpPassword; private string smtpServer; private bool IsConfigured; public WorkToSendEmail(NotificationDto notification, IConfiguration configuration) : base(MakeWorkId(notification)) { this.notification = notification; sender = configuration.GetValue("email:sender", string.Empty); smtpPassword = configuration.GetValue("email:password", string.Empty); smtpServer = configuration.GetValue("email:smtpServer", string.Empty); var configError = string.IsNullOrEmpty(sender) || string.IsNullOrEmpty(smtpPassword) || string.IsNullOrEmpty(smtpServer); IsConfigured = !configError; } protected override async Task Action(string id, IServiceProvider services, Action onProgressCallback, CancellationToken token) { if (!IsConfigured) { Trace.TraceWarning("smtp is not configured"); return; } var notificationRepository = services.GetRequiredService(); var userRepository = services.GetRequiredService(); var user = await userRepository.GetOrDefaultAsync(notification.IdUser, token) ?? throw new ArgumentInvalidException(nameof(notification.IdUser), "Пользователь не найден"); if (!MailAddress.TryCreate(user.Email, out var mailAddress)) { Trace.TraceWarning($"Mail {user.Email} is not correct."); throw new ArgumentInvalidException(nameof(user.Email), $"Mail {user.Email} is not null."); } var from = new MailAddress(sender); var message = new MailMessage { From = from }; message.To.Add(mailAddress.Address); message.BodyEncoding = System.Text.Encoding.UTF8; message.Body = notification.Message; message.Subject = notification.Title; message.IsBodyHtml = true; using var client = new SmtpClient(smtpServer); client.EnableSsl = true; client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential(sender, smtpPassword); await client.SendMailAsync(message, token); notification.SentDate = DateTime.UtcNow; await notificationRepository.UpdateAsync(notification, token); Trace.TraceInformation($"Send email to {user.Email} subj:{notification.Title} html body count {notification.Message.Length}"); } private static string MakeWorkId(NotificationDto notification) { var hash = notification.IdUser.GetHashCode(); hash ^= notification.Title.GetHashCode(); hash ^= notification.Message.GetHashCode(); return hash.ToString("x"); } } }