diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/App.config b/BlacksmithWorkshop/BlacksmithWorkshop/App.config new file mode 100644 index 0000000..07336cc --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshop/App.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/BlacksmithWorkshopView.csproj b/BlacksmithWorkshop/BlacksmithWorkshop/BlacksmithWorkshopView.csproj index 884c371..0093495 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/BlacksmithWorkshopView.csproj +++ b/BlacksmithWorkshop/BlacksmithWorkshop/BlacksmithWorkshopView.csproj @@ -9,11 +9,15 @@ + + + Always + Always diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/FormMails.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshop/FormMails.Designer.cs new file mode 100644 index 0000000..f45cd0a --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormMails.Designer.cs @@ -0,0 +1,90 @@ +namespace BlacksmithWorkshopView +{ + partial class FormMails + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.dataGridView = new System.Windows.Forms.DataGridView(); + this.menuStrip1 = new System.Windows.Forms.MenuStrip(); + this.refToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.menuStrip1.SuspendLayout(); + this.SuspendLayout(); + // + // dataGridView + // + this.dataGridView.BackgroundColor = System.Drawing.SystemColors.ControlLightLight; + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Location = new System.Drawing.Point(0, 27); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.RowTemplate.Height = 25; + this.dataGridView.Size = new System.Drawing.Size(802, 426); + this.dataGridView.TabIndex = 0; + // + // menuStrip1 + // + this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.refToolStripMenuItem}); + this.menuStrip1.Location = new System.Drawing.Point(0, 0); + this.menuStrip1.Name = "menuStrip1"; + this.menuStrip1.Size = new System.Drawing.Size(800, 24); + this.menuStrip1.TabIndex = 1; + this.menuStrip1.Text = "menuStrip1"; + // + // refToolStripMenuItem + // + this.refToolStripMenuItem.Name = "refToolStripMenuItem"; + this.refToolStripMenuItem.Size = new System.Drawing.Size(73, 20); + this.refToolStripMenuItem.Text = "Обновить"; + this.refToolStripMenuItem.Click += new System.EventHandler(this.RefToolStripMenuItem_Click); + // + // FormMails + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.dataGridView); + this.Controls.Add(this.menuStrip1); + this.MainMenuStrip = this.menuStrip1; + this.Name = "FormMails"; + this.Text = "Письма"; + this.Load += new System.EventHandler(this.FormMails_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.menuStrip1.ResumeLayout(false); + this.menuStrip1.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private DataGridView dataGridView; + private MenuStrip menuStrip1; + private ToolStripMenuItem refToolStripMenuItem; + } +} \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/FormMails.cs b/BlacksmithWorkshop/BlacksmithWorkshop/FormMails.cs new file mode 100644 index 0000000..13936eb --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormMails.cs @@ -0,0 +1,41 @@ +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; + +namespace BlacksmithWorkshopView +{ + public partial class FormMails : Form + { + private readonly ILogger _logger; + private readonly IMessageInfoLogic _messageLogic; + public FormMails(ILogger logger, IMessageInfoLogic messageLogic) + { + _logger = logger; + _messageLogic = messageLogic; + InitializeComponent(); + } + private void LoadData() + { + try + { + _logger.LogInformation("Загрузка списка писем"); + dataGridView.DataSource = _messageLogic.ReadList(null); + dataGridView.Columns["MessageId"].Visible = false; + dataGridView.Columns["ClientId"].Visible = false; + dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + catch (Exception ex) + { + _logger.LogWarning("Ошибка загрузки писем"); + MessageBox.Show($"Не удалось загрузить письма: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void FormMails_Load(object sender, EventArgs e) + { + LoadData(); + } + private void RefToolStripMenuItem_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/FormMails.resx b/BlacksmithWorkshop/BlacksmithWorkshop/FormMails.resx new file mode 100644 index 0000000..938108a --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormMails.resx @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.Designer.cs b/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.Designer.cs index 892e72d..cd4bbac 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.Designer.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.Designer.cs @@ -43,6 +43,7 @@ this.buttonCreateOrder = new System.Windows.Forms.Button(); this.buttonIssuedOrder = new System.Windows.Forms.Button(); this.buttonRef = new System.Windows.Forms.Button(); + this.mailsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); this.SuspendLayout(); @@ -52,7 +53,8 @@ this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.refbooksToolStripMenuItem, this.reportsToolStripMenuItem, - this.doWorkToolStripMenuItem}); + this.doWorkToolStripMenuItem, + this.mailsToolStripMenuItem}); this.menuStrip.Location = new System.Drawing.Point(0, 0); this.menuStrip.Name = "menuStrip"; this.menuStrip.Size = new System.Drawing.Size(1795, 24); @@ -179,6 +181,13 @@ this.buttonRef.UseVisualStyleBackColor = true; this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click); // + // mailsToolStripMenuItem + // + this.mailsToolStripMenuItem.Name = "mailsToolStripMenuItem"; + this.mailsToolStripMenuItem.Size = new System.Drawing.Size(62, 20); + this.mailsToolStripMenuItem.Text = "Письма"; + this.mailsToolStripMenuItem.Click += new System.EventHandler(this.MailsToolStripMenuItem_Click); + // // FormMain // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); @@ -218,5 +227,6 @@ private ToolStripMenuItem clientsToolStripMenuItem; private ToolStripMenuItem implementersToolStripMenuItem; private ToolStripMenuItem doWorkToolStripMenuItem; + private ToolStripMenuItem mailsToolStripMenuItem; } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.cs b/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.cs index 6d248c0..0e83f74 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshop/FormMain.cs @@ -13,7 +13,7 @@ namespace BlacksmithWorkshopView private readonly IReportLogic _reportLogic; private readonly IImplementerLogic _implementerLogic; private readonly IWorkProcess _workProcess; - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IImplementerLogic implementerLogic) + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess, IImplementerLogic implementerLogic, IMessageInfoLogic messageInfoLogic) { InitializeComponent(); _logger = logger; @@ -204,5 +204,15 @@ namespace BlacksmithWorkshopView { _workProcess.DoWork(_implementerLogic, _orderLogic); } + + private void MailsToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMails)); + if (service is FormMails form) + { + form.ShowDialog(); + LoadData(); + } + } } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs b/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs index 83f6bd9..1273bd2 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshop/Program.cs @@ -1,7 +1,9 @@ using BlacksmithWorkshopBusinessLogic.BusinessLogics; +using BlacksmithWorkshopBusinessLogic.MailWorker; using BlacksmithWorkshopBusinessLogic.OfficePackage; using BlacksmithWorkshopBusinessLogic.OfficePackage.Implements; using BlacksmithWorkShopBusinessLogic.BusinessLogics; +using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.BusinessLogicContracts; using BlacksmithWorkshopContracts.BusinessLogicsContracts; using BlacksmithWorkshopContracts.StoragesContracts; @@ -25,7 +27,27 @@ namespace BlacksmithWorkshopView var services = new ServiceCollection(); ConfigureServices(services); _serviceProvider = services.BuildServiceProvider(); - Application.Run(_serviceProvider.GetRequiredService()); + try + { + var mailSender = _serviceProvider.GetService(); + mailSender?.MailConfig(new MailConfigBindingModel + { + MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, + MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, + SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, + SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), + PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, + PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) + }); + // + var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); + } + catch (Exception ex) + { + var logger = _serviceProvider.GetService(); + logger?.LogError(ex, " "); + } + Application.Run(_serviceProvider.GetRequiredService()); } private static void ConfigureServices(ServiceCollection services) { @@ -39,6 +61,7 @@ namespace BlacksmithWorkshopView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -46,6 +69,8 @@ namespace BlacksmithWorkshopView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddSingleton(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -61,6 +86,8 @@ namespace BlacksmithWorkshopView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } - } + private static void MailCheck(object obj) => ServiceProvider?.GetService()?.MailCheck(); + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BlacksmithWorkshopBusinessLogic.csproj b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BlacksmithWorkshopBusinessLogic.csproj index 56d6e19..61ece1e 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BlacksmithWorkshopBusinessLogic.csproj +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BlacksmithWorkshopBusinessLogic.csproj @@ -8,6 +8,7 @@ + diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/ClientLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/ClientLogic.cs index f40ffba..d81283b 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/ClientLogic.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/ClientLogic.cs @@ -6,6 +6,7 @@ using BlacksmithWorkshopContracts.ViewModels; using DocumentFormat.OpenXml.InkML; using Microsoft.Extensions.Logging; using System.Net; +using System.Text.RegularExpressions; namespace BlacksmithWorkshopBusinessLogic.BusinessLogics { @@ -104,6 +105,14 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogics { throw new InvalidOperationException("Клиент с таким адресом электронной почты уже есть"); } + if (!Regex.IsMatch(model.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$")) + { + throw new ArgumentException("Некорретно введенный email", nameof(model.Email)); + } + if (!Regex.IsMatch(model.Password, @"^(?=.*\d)(?=.*\W)(?=.*[^\d\s]).+$")) + { + throw new ArgumentException("Некорректно введенный пароль. Пароль должен содержать хотя бы одну букву, цифру и не буквенный символ", nameof(model.Password)); + } } } } diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs new file mode 100644 index 0000000..a5e9c64 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/MessageInfoLogic.cs @@ -0,0 +1,43 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using BlacksmithWorkshopContracts.SearchModels; +using BlacksmithWorkshopContracts.StoragesContracts; +using BlacksmithWorkshopContracts.ViewModels; +using Microsoft.Extensions.Logging; + +namespace BlacksmithWorkshopBusinessLogic.BusinessLogics +{ + public class MessageInfoLogic : IMessageInfoLogic + { + private readonly ILogger _logger; + private readonly IMessageInfoStorage _messageInfoStorage; + public MessageInfoLogic(ILogger logger, IMessageInfoStorage MessageInfoStorage) + { + _logger = logger; + _messageInfoStorage = MessageInfoStorage; + } + + public bool Create(MessageInfoBindingModel model) + { + if (_messageInfoStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public List? ReadList(MessageInfoSearchModel? model) + { + _logger.LogInformation("ReadList. MessageId: {MessageId}. ClientId:{ClientId} ", model?.MessageId, model?.ClientId); + var list = (model == null) ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs index c17cb9a..a14c3e6 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -1,5 +1,7 @@ -using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopBusinessLogic.MailWorker; +using BlacksmithWorkshopContracts.BindingModels; using BlacksmithWorkshopContracts.BusinessLogicContracts; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; using BlacksmithWorkshopContracts.SearchModels; using BlacksmithWorkshopContracts.StoragesContracts; using BlacksmithWorkshopContracts.ViewModels; @@ -12,10 +14,14 @@ namespace BlacksmithWorkShopBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + private readonly AbstractMailWorker _mailWorker; + private readonly IClientLogic _clientLogic; + public OrderLogic(ILogger logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic) { _logger = logger; _orderStorage = orderStorage; + _mailWorker = mailWorker; + _clientLogic = clientLogic; } public List? ReadList(OrderSearchModel? model) { @@ -62,10 +68,11 @@ namespace BlacksmithWorkShopBusinessLogic.BusinessLogics } if (_orderStorage.Update(model) != null) { + SendMail(vm?.ClientId ?? 0, $"Информация о заказе №{model.Id}", $"Заказ №{model.Id} {model.Status}"); return true; } } - _logger.LogWarning($"Changing order status of order {model.Id} to {newstatus} failed"); + _logger.LogWarning("Changing order status of order {Id} to {NewStatus} failed", model.Id, newstatus); return false; } public bool CreateOrder(OrderBindingModel model) @@ -76,7 +83,8 @@ namespace BlacksmithWorkShopBusinessLogic.BusinessLogics model.Status = OrderStatus.Принят; if (_orderStorage.Insert(model) != null) { - return true; + SendMail(model.ClientId, $"Новый заказ создан. Номер заказа: {model.Id}", $"Заказ №{model.Id} от {model.DateCreate} на сумму {model.Sum} принят"); + return true; } } _logger.LogWarning("Create order operation failed"); @@ -113,5 +121,20 @@ namespace BlacksmithWorkShopBusinessLogic.BusinessLogics throw new InvalidOperationException("Изделие с таким ID уже есть"); } } - } + private bool SendMail(int clientId, string subject, string text) + { + var client = _clientLogic.ReadElement(new() { Id = clientId }); + if (client == null) + { + return false; + } + _mailWorker.MailSendAsync(new() + { + MailAddress = client.Email, + Subject = subject, + Text = text + }); + return true; + } + } } \ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs new file mode 100644 index 0000000..4918bc9 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/AbstractMailWorker.cs @@ -0,0 +1,73 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; + +namespace BlacksmithWorkshopBusinessLogic.MailWorker +{ + public abstract class AbstractMailWorker + { + protected string _mailLogin = string.Empty; + protected string _mailPassword = string.Empty; + protected string _smtpClientHost = string.Empty; + protected int _smtpClientPort; + protected string _popHost = string.Empty; + protected int _popPort; + private readonly IMessageInfoLogic _messageInfoLogic; + private readonly ILogger _logger; + public AbstractMailWorker(ILogger logger, IMessageInfoLogic messageInfoLogic) + { + _logger = logger; + _messageInfoLogic = messageInfoLogic; + } + 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); + } + 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.Text)) + { + return; + } + _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); + await SendMailAsync(info); + } + public async void MailCheck() + { + if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) + { + return; + } + if (string.IsNullOrEmpty(_popHost) || _popPort == 0) + { + return; + } + if (_messageInfoLogic == null) + { + return; + } + var list = await ReceiveMailAsync(); + _logger.LogDebug("Check Mail: {Count} new mails", list.Count); + foreach (var mail in list) + { + _messageInfoLogic.Create(mail); + } + } + protected abstract Task SendMailAsync(MailSendInfoBindingModel info); + protected abstract Task> ReceiveMailAsync(); + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/MailKitWorker.cs b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/MailKitWorker.cs new file mode 100644 index 0000000..aa504e2 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopBusinessLogic/MailWorker/MailKitWorker.cs @@ -0,0 +1,76 @@ +using BlacksmithWorkshopContracts.BindingModels; +using BlacksmithWorkshopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System.Net.Mail; +using System.Net; +using System.Security.Authentication; +using System.Text; +using MailKit.Net.Pop3; +using MailKit.Security; + +namespace BlacksmithWorkshopBusinessLogic.MailWorker +{ + public class MailKitWorker : AbstractMailWorker + { + public MailKitWorker(ILogger logger, IMessageInfoLogic messageInfoLogic) : base(logger, messageInfoLogic) { } + 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.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; + } + } + protected override async Task> ReceiveMailAsync() + { + var list = new List(); + using var client = new Pop3Client(); + await Task.Run(() => + { + try + { + client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); + client.Authenticate(_mailLogin, _mailPassword); + for (int i = 0; i < client.Count; i++) + { + var message = client.GetMessage(i); + foreach (var mail in message.From.Mailboxes) + { + list.Add(new MessageInfoBindingModel + { + DateDelivery = message.Date.DateTime, + MessageId = message.MessageId, + SenderName = mail.Address, + Subject = message.Subject, + Body = message.TextBody + }); + } + } + } + catch (MailKit.Security.AuthenticationException) + { } + finally + { + client.Disconnect(true); + } + }); + return list; + } + } +} diff --git a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/BlacksmithWorkshopClientApp.csproj b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/BlacksmithWorkshopClientApp.csproj index d2be2f5..af201b1 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/BlacksmithWorkshopClientApp.csproj +++ b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/BlacksmithWorkshopClientApp.csproj @@ -14,4 +14,10 @@ + + + Always + + + diff --git a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Home/Mails.cshtml b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Home/Mails.cshtml new file mode 100644 index 0000000..e7f77c5 --- /dev/null +++ b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Home/Mails.cshtml @@ -0,0 +1,51 @@ +@using BlacksmithWorkshopContracts.ViewModels +@model List +@{ + ViewData["Title"] = "Mails"; +} +
+

Заказы

+
+
+ @{ + if (Model == null) + { +

Авторизируйтесь

+ return; + } + + + + + + + + + + @foreach (var item in Model) + { + + + + + + } + +
+ Дата письма + + Заголовок + + Текст +
+ @Html.DisplayFor(modelItem => + item.DateDelivery) + + @Html.DisplayFor(modelItem => + item.Subject) + + @Html.DisplayFor(modelItem => + item.Body) +
+ } +
\ No newline at end of file diff --git a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Shared/_Layout.cshtml b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Shared/_Layout.cshtml index 0cff161..5c4090e 100644 --- a/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Shared/_Layout.cshtml +++ b/BlacksmithWorkshop/BlacksmithWorkshopClientApp/Views/Shared/_Layout.cshtml @@ -27,6 +27,9 @@ Личные данные +