Worker для отправки email

This commit is contained in:
Olga Nemt 2023-12-21 10:50:26 +05:00
parent d7464a03c7
commit 371ff37d2e
2 changed files with 83 additions and 51 deletions

View File

@ -0,0 +1,73 @@
using AsbCloudApp.Data;
using AsbCloudApp.Exceptions;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Background
{
internal class WorkToSendEmail : Work
{
private NotificationDto notification;
private string sender;
private string smtpPassword;
private string smtpServer;
public WorkToSendEmail(string workId, NotificationDto notification, string sender, string smtpPassword, string smtpServer) : base(workId)
{
this.notification = notification;
this.sender = sender;
this.smtpPassword = smtpPassword;
this.smtpServer = smtpServer;
}
protected override async Task Action(string id, IServiceProvider services, Action<string, double?> onProgressCallback, CancellationToken token)
{
var notificationRepository = services.GetRequiredService<INotificationRepository>();
var userRepository = services.GetRequiredService<IUserRepository>();
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}");
}
}
}

View File

@ -10,6 +10,7 @@ using AsbCloudApp.Exceptions;
using AsbCloudApp.Repositories; using AsbCloudApp.Repositories;
using AsbCloudApp.Services.Notifications; using AsbCloudApp.Services.Notifications;
using AsbCloudInfrastructure.Background; using AsbCloudInfrastructure.Background;
using AsbCloudInfrastructure.Background.PeriodicWorks;
using DocumentFormat.OpenXml.Presentation; using DocumentFormat.OpenXml.Presentation;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@ -24,6 +25,7 @@ namespace AsbCloudInfrastructure.Services.Email
private readonly string sender; private readonly string sender;
private readonly string smtpServer; private readonly string smtpServer;
private readonly string smtpPassword; private readonly string smtpPassword;
private IConfiguration configuration;
public EmailNotificationTransportService(BackgroundWorker backgroundWorker, public EmailNotificationTransportService(BackgroundWorker backgroundWorker,
IConfiguration configuration) IConfiguration configuration)
@ -32,6 +34,7 @@ namespace AsbCloudInfrastructure.Services.Email
smtpPassword = configuration.GetValue("email:password", string.Empty); smtpPassword = configuration.GetValue("email:password", string.Empty);
smtpServer = configuration.GetValue("email:smtpServer", string.Empty); smtpServer = configuration.GetValue("email:smtpServer", string.Empty);
var configError = string.IsNullOrEmpty(sender) || var configError = string.IsNullOrEmpty(sender) ||
string.IsNullOrEmpty(smtpPassword) || string.IsNullOrEmpty(smtpPassword) ||
string.IsNullOrEmpty(smtpServer); string.IsNullOrEmpty(smtpServer);
@ -45,19 +48,18 @@ namespace AsbCloudInfrastructure.Services.Email
public Task SendAsync(NotificationDto notification, CancellationToken cancellationToken) public Task SendAsync(NotificationDto notification, CancellationToken cancellationToken)
{ {
if (!IsConfigured) //if (!IsConfigured)
{ //{
Trace.TraceWarning("smtp is not configured"); // Trace.TraceWarning("smtp is not configured");
return Task.CompletedTask; // return Task.CompletedTask;
} //}
var workId = MakeWorkId(notification.IdUser, notification.Title, notification.Message); var workId = MakeWorkId(notification.IdUser, notification.Title, notification.Message);
if (!backgroundWorker.Works.Any(w=>w.Id==workId)) if (!backgroundWorker.Works.Any(w=>w.Id==workId))
{ {
var workAction = MakeEmailSendWorkAction(notification); var work = new WorkToSendEmail(workId, notification, sender, smtpPassword, smtpServer);
var work = Work.CreateByDelegate(workId, workAction);
backgroundWorker.Enqueue(work); backgroundWorker.Enqueue(work);
} }
return Task.CompletedTask; return Task.CompletedTask;
@ -71,49 +73,6 @@ namespace AsbCloudInfrastructure.Services.Email
return Task.WhenAll(tasks); return Task.WhenAll(tasks);
} }
private Func<string, IServiceProvider, Action<string, double?>, CancellationToken, Task> MakeEmailSendWorkAction(NotificationDto notification)
{
return async (_, serviceProvider, onProgress, token) =>
{
var notificationRepository = serviceProvider.GetRequiredService<INotificationRepository>();
var userRepository = serviceProvider.GetRequiredService<IUserRepository>();
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(int idUser, string subject, string content) private static string MakeWorkId(int idUser, string subject, string content)
{ {
var hash = idUser.GetHashCode(); var hash = idUser.GetHashCode();