DD.WellWorkover.Cloud/AsbCloudInfrastructure/Background/WorkToSendEmail.cs

74 lines
2.8 KiB
C#
Raw Normal View History

2023-12-21 10:50:26 +05:00
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}");
}
}
}