BusinessLogics / Add Mail service

This commit is contained in:
parent 11f911b2af
commit f57a08bc31
8 changed files with 296 additions and 6 deletions

View File

@ -0,0 +1,108 @@
using HospitalContracts.BindingModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalBusinessLogics.MailWorker
{
/// <summary>
/// Абстрактный класс для работы с письмами
/// </summary>
public abstract class AbstractMailWorker
{
/// <summary>
/// Логгер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Логин для доступа к почтовому сервису
/// </summary>
protected string _mailLogin = string.Empty;
/// <summary>
/// Пароль для доступа к почтовому сервису
/// </summary>
protected string _mailPassword = string.Empty;
/// <summary>
/// Хост SMTP-клиента
/// </summary>
protected string _smtpClientHost = string.Empty;
/// <summary>
/// Порт SMTP-клиента
/// </summary>
protected int _smtpClientPort;
/// <summary>
/// Хост протокола POP3
/// </summary>
protected string _popHost = string.Empty;
/// <summary>
/// Порт протокола POP3
/// </summary>
protected int _popPort;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="logger"></param>
public AbstractMailWorker(ILogger<AbstractMailWorker> logger)
{
_logger = logger;
}
/// <summary>
/// Настроить почтовый сервис
/// </summary>
/// <param name="config"></param>
public void MailConfig(MailConfigBindingModel config)
{
_mailLogin = config.MailLogin;
_mailPassword = config.MailPassword;
_smtpClientHost = config.SmtpClientHost;
_smtpClientPort = config.SmtpClientPort;
_popHost = config.PopHost;
_popPort = config.PopPort;
_logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPort}, {popHost}, {popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort);
}
/// <summary>
/// Проверить и отправить письмо
/// </summary>
/// <param name="info"></param>
public async void MailSendAsync(MailSendInfoBindingModel info)
{
if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
{
return;
}
if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0)
{
return;
}
if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Path))
{
return;
}
_logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject);
await SendMailAsync(info);
}
/// <summary>
/// Отправить письмо
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
protected abstract Task SendMailAsync(MailSendInfoBindingModel info);
}
}

View File

@ -0,0 +1,57 @@
using HospitalContracts.BindingModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace HospitalBusinessLogics.MailWorker
{
/// <summary>
/// Реализация абстрактного класса для работы с письмами
/// </summary>
public class MailKitWorker : AbstractMailWorker
{
/// <summary>
/// Конструктор
/// </summary>
/// <param name="logger"></param>
public MailKitWorker(ILogger<MailKitWorker> logger) : base(logger) { }
/// <summary>
/// Отправить письмо
/// </summary>
/// <param name="info"></param>
/// <returns></returns>
protected override async Task SendMailAsync(MailSendInfoBindingModel info)
{
using var objMailMessage = new MailMessage();
using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort);
try
{
// Указываем данные для отправки письма
objMailMessage.From = new MailAddress(_mailLogin);
objMailMessage.To.Add(new MailAddress(info.MailAddress));
objMailMessage.Subject = info.Subject;
objMailMessage.Body = info.Text;
objMailMessage.Attachments.Add(new Attachment(info.Path));
// Указываем параметры
objMailMessage.SubjectEncoding = Encoding.UTF8;
objMailMessage.BodyEncoding = Encoding.UTF8;
objSmtpClient.UseDefaultCredentials = false;
objSmtpClient.EnableSsl = true;
objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword);
// Отправляем письмо
await Task.Run(() => objSmtpClient.Send(objMailMessage));
}
catch (Exception)
{
throw;
}
}
}
}

View File

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalContracts.BindingModels
{
/// <summary>
/// Модель привязки для настройки почтового сервиса
/// </summary>
public class MailConfigBindingModel
{
/// <summary>
/// Логин для доступа к почтовому сервису
/// </summary>
public string MailLogin { get; set; } = string.Empty;
/// <summary>
/// Пароль для доступа к почтовому сервису
/// </summary>
public string MailPassword { get; set; } = string.Empty;
/// <summary>
/// Хост SMTP-клиента
/// </summary>
public string SmtpClientHost { get; set; } = string.Empty;
/// <summary>
/// Порт SMTP-клиента
/// </summary>
public int SmtpClientPort { get; set; }
/// <summary>
/// Хост протокола POP3
/// </summary>
public string PopHost { get; set; } = string.Empty;
/// <summary>
/// Порт протокола POP3
/// </summary>
public int PopPort { get; set; }
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HospitalContracts.BindingModels
{
/// <summary>
/// Модель привязки для отправки письма
/// </summary>
public class MailSendInfoBindingModel
{
/// <summary>
/// Адрес электронной почты
/// </summary>
public string MailAddress { get; set; } = string.Empty;
/// <summary>
/// Заголовок письма
/// </summary>
public string Subject { get; set; } = string.Empty;
/// <summary>
/// Текст письма
/// </summary>
public string Text { get; set; } = string.Empty;
/// <summary>
/// Путь до файла
/// </summary>
public string Path { get; set; } = string.Empty;
}
}

View File

@ -1,4 +1,5 @@
using HospitalContracts.BindingModels;
using HospitalBusinessLogics.MailWorker;
using HospitalContracts.BindingModels;
using HospitalContracts.BusinessLogicsContracts;
using HospitalContracts.SearchModels;
using HospitalContracts.ViewModels;
@ -29,17 +30,24 @@ namespace HospitalWebApp.Controllers
/// </summary>
private readonly IReportLogic _reportLogic;
/// <summary>
/// Бизнес-логика для отправки писем
/// </summary>
private readonly AbstractMailWorker _mailLogic;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="logger"></param>
/// <param name="doctorLogic"></param>
/// <param name="reportLogic"></param>
public HomeController(ILogger<HomeController> logger, IDoctorLogic doctorLogic, IReportLogic reportLogic)
/// <param name="mailLogic"></param>
public HomeController(ILogger<HomeController> logger, IDoctorLogic doctorLogic, IReportLogic reportLogic, AbstractMailWorker mailLogic)
{
_logger = logger;
_doctorLogic = doctorLogic;
_reportLogic = reportLogic;
_mailLogic = mailLogic;
}
/// <summary>
@ -325,16 +333,33 @@ namespace HospitalWebApp.Controllers
/// <summary>
/// Отправить по почте отчёт
/// </summary>
/// <param name="fileUpload"></param>
/// <exception cref="Exception"></exception>
[HttpPost]
public void SendReport()
public void SendReport(IFormFile fileUpload)
{
if (APIClient.Doctor == null)
{
throw new Exception("Необходимо авторизоваться!");
}
// TODO
if (fileUpload == null || fileUpload.Length <= 0)
{
throw new Exception("Файл не выбран или пуст!");
}
// Путь до файла
var uploadPath = @"D:\ULSTU\Семестр 4\РПП Coursework\Reports\";
var fileName = Path.GetFileName(fileUpload.FileName);
var fullPath = Path.Combine(uploadPath, fileName);
_mailLogic.MailSendAsync(new MailSendInfoBindingModel
{
MailAddress = APIClient.Doctor.Email,
Subject = $"{fileName.Split('.')[0]}",
Text = $"Отчёт отправлен {DateTime.Now}",
Path = fullPath
});
Response.Redirect("/Home/Reports");
}

View File

@ -1,6 +1,8 @@
using HospitalBusinessLogics.BusinessLogics;
using HospitalBusinessLogics.MailWorker;
using HospitalBusinessLogics.OfficePackage;
using HospitalBusinessLogics.OfficePackage.Implements;
using HospitalContracts.BindingModels;
using HospitalContracts.BusinessLogicsContracts;
using HospitalContracts.StoragesContracts;
using HospitalDatabaseImplement.Implements;
@ -26,6 +28,7 @@ builder.Services.AddTransient<IRecipeLogic, RecipeLogic>();
builder.Services.AddTransient<IDiseaseLogic, DiseaseLogic>();
builder.Services.AddTransient<IProcedureLogic, ProcedureLogic>();
builder.Services.AddTransient<IMedicineLogic, MedicineLogic>();
builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
// BusinessLogic Reports services
builder.Services.AddTransient<IReportLogic, ReportLogic>();
@ -35,6 +38,18 @@ builder.Services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
var app = builder.Build();
// Configuration for MailService
var mailSender = app.Services.GetService<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() ?? string.Empty,
MailPassword = builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? string.Empty,
SmtpClientHost = builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? string.Empty,
SmtpClientPort = Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()),
PopHost = builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ?? string.Empty,
PopPort = Convert.ToInt32(builder.Configuration?.GetSection("PopPort")?.Value?.ToString())
});
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{

View File

@ -10,7 +10,7 @@
<h2 class="display-4">Отчеты</h2>
</div>
<form method="post" style="margin-top: 50px">
<form method="post" enctype="multipart/form-data" style="margin-top: 50px">
<!-- Сохранить отчеты в формате Word и Excel -->
<div class="d-flex justify-content-center" style="gap: 30px">
<div class="text-center">

View File

@ -5,5 +5,12 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"SmtpClientHost": "smtp.gmail.com",
"SmtpClientPort": "587",
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "besick73@gmail.com",
"MailPassword": "jmcp rbai teqa ltmc"
}