/// <summary> /// Отправка отчета в офис Консультант плюс на анализ наличия ошибок в системе /// </summary> /// <param name="parameters">Параметры конфигурации</param> public void SendSmtpConsultantPlusReport(ConfigFile.ConfigFile parameters) { try { ZipAttachments zipAttach = new ZipAttachments(); var builder = new BodyBuilder() { TextBody = $"Автоматическая отправка отчетов Консультант плюс (Раз в сутки в {parameters.Hours} часов {parameters.Minutes} минут)" }; var pathListReport = new List <string>() { parameters.PathConsultantPlusReceive, parameters.PathConsultantPlusReceiveTemp, parameters.PathConsultantPlusSts }; foreach (var pathReport in pathListReport) { var allFileDirectory = Directory.GetFiles(pathReport).Where(s => parameters.ExtensionsFileReport.Contains(Path.GetExtension(s))).ToArray(); var nameFile = pathReport.Split(Path.DirectorySeparatorChar).Last() + ".zip"; var fullPathZip = Path.Combine(parameters.PathSaveArchive, nameFile); zipAttach.StartZipArchiveOut(allFileDirectory, fullPathZip, false); builder.Attachments.Add(fullPathZip); } MimeMessage mailToClient = new MimeMessage(); mailToClient.To.Add(new MailboxAddress(parameters.MailReport)); mailToClient.Subject = "Отчеты по папкам Receive, ReceiveTemp, Sts "; mailToClient.From.Add(new MailboxAddress("Автоматическая рассылка писем!", parameters.LoginR7751)); //Сюда идентификатор mailToClient.Headers[HeaderId.MessageId] = mailToClient.MessageId; mailToClient.Headers[HeaderId.ResentMessageId] = mailToClient.MessageId; mailToClient.Headers[HeaderId.DispositionNotificationTo] = parameters.LoginR7751; mailToClient.Headers[HeaderId.ReturnReceiptTo] = parameters.LoginR7751; mailToClient.Body = builder.ToMessageBody(); try { using (var smtp = new SmtpCustomClient.SmtpCustomClient()) { smtp.DeliveryStatusNotificationType = DeliveryStatusNotificationType.Full; smtp.CheckCertificateRevocation = false; smtp.Connect(parameters.Pop3Address, 465, true); smtp.Authenticate(parameters.LoginR7751, parameters.PasswordR7751); smtp.Send(mailToClient); smtp.Disconnect(true); } Loggers.Log4NetLogger.Info(new Exception($"Отправка письма отчетов консультант плюс на адрес {parameters.MailReport}")); } catch (Exception ex) { Loggers.Log4NetLogger.Error(ex); } //Очистить временную папку с файлами zipAttach.DropAllFileToPath(parameters.PathSaveArchive); Loggers.Log4NetLogger.Info(new Exception("Отправка отчетов Консультант плюс закончена успешно!")); } catch (Exception ex) { Loggers.Log4NetLogger.Error(ex); } }
/// <summary> /// Пересылка с почты oit на пользователей Lotus /// </summary> /// <param name="parameters"></param> public void StartMessageOit(ConfigFile.ConfigFile parameters) { try { int count = 0; ZipAttachments zip = new ZipAttachments(); using (Pop3Client client = new Pop3Client()) { client.CheckCertificateRevocation = false; client.Connect(parameters.Pop3Address, 995, true); MailSender mail = new MailSender(); Loggers.Log4NetLogger.Info(new Exception($"Соединение с сервером eups.tax.nalog.ru установлено (OIT)")); client.Authenticate(parameters.LoginOit, parameters.PasswordOit); Loggers.Log4NetLogger.Info(new Exception($"Пользователь проверен (OIT)")); if (client.IsConnected) { MailLogicLotus mailSave = new MailLogicLotus(); SelectSql select = new SelectSql(); UserLotus userSqlDefault = select.FindUserGroup(7); int messageCount = client.GetMessageCount(); for (int i = 0; i < messageCount; i++) { MimeMessage message = client.GetMessage(i); var messageAttaches = message.Attachments as List <MimeEntity> ?? new List <MimeEntity>(); var messageBodyAttaches = new List <MimeEntity>(); messageBodyAttaches.AddRange(message.BodyParts); var calendar = messageBodyAttaches.Where(x => x.ContentType.MimeType == "text/calendar").ToList(); var file = messageBodyAttaches.Where(x => x.ContentType.MediaType == "image" || x.ContentType.MediaType == "application").ToList(); if (file.Count > 0) { messageAttaches.AddRange(file); } string body; var isHtmlMime = false; if (string.IsNullOrWhiteSpace(message.TextBody)) { body = message.HtmlBody; isHtmlMime = true; } else { body = message.TextBody; } var date = message.Date; if (date.Date >= DateTime.Now.Date) { if (!mailSave.IsExistsBdMail(message.MessageId)) { if (calendar.Count > 0) { var calendarVks = new CalendarVks(); body = calendarVks.CalendarParser(calendar, message); } var address = (MailboxAddress)message.From[0]; var mailSender = address.Address; var nameFile = date.ToString("dd.MM.yyyy_HH.mm.ss") + "_" + mailSender.Split('@')[0] + ".zip"; var fullPath = Path.Combine(parameters.PathSaveArchive, nameFile); MailLotusOutlookIn mailMessage = new MailLotusOutlookIn() { IdMail = message.MessageId, MailAdressSend = parameters.LoginOit, SubjectMail = message.Subject, Body = body, MailAdress = mailSender, DateInputServer = date.DateTime, NameFile = nameFile, FullPathFile = fullPath, FileMail = zip.StartZipArchive(messageAttaches, fullPath) }; mailSave.AddModelMailIn(mailMessage); var mailUsers = mail.FindUserLotusMail(select.FindUserOnUserGroup(userSqlDefault, mailMessage.SubjectMail), "(OIT)"); if (!string.IsNullOrWhiteSpace(message.HtmlBody)) { var math = Regex.Match(body, @"CN=(.+)МНС"); if (!string.IsNullOrWhiteSpace(math.Value)) { mailUsers.Add(math.Value); } } if (isHtmlMime) { mail.SendMailMimeHtml(mailMessage, mailUsers); } else { mail.SendMailIn(mailMessage, mailUsers); } count++; Loggers.Log4NetLogger.Info(new Exception($"УН: {mailMessage.IdMail} Дата/Время: {date} От кого: {mailMessage.MailAdress}")); } } else { //Удаление сообщения/письма client.DeleteMessage(i); } } mailSave.Dispose(); Loggers.Log4NetLogger.Info(new Exception("Количество пришедшей (OIT) почты:" + count)); } mail.Dispose(); client.Disconnect(true); } //Очистить временную папку с файлами zip.DropAllFileToPath(parameters.PathSaveArchive); foreach (FileInfo file in new DirectoryInfo(parameters.PathSaveArchive).GetFiles()) { Loggers.Log4NetLogger.Info(new Exception($"Наименование удаленных файлов: {file.FullName}")); file.Delete(); } Loggers.Log4NetLogger.Info(new Exception("Очистили папку от файлов (OIT)!")); Loggers.Log4NetLogger.Info(new Exception("Перерыв 5 минут (OIT)")); } catch (Exception x) { Loggers.Log4NetLogger.Debug(x); } }
/// <summary> /// Отправка писем абоненту внешней почты /// </summary> /// <param name="parameters">Параметры конфигурации</param> public void SendSmtpMessage(ConfigFile.ConfigFile parameters) { try { Mail = new MailSender(); ZipAttachments zipAttach = new ZipAttachments(); MailLogicLotus mailSave = new MailLogicLotus(); var dbSend = Mail.SendMailOut(parameters.PathSaveArchive); foreach (var mailLotusOutlookOut in dbSend) { //Сначала манипуляции с файлами и архивами а потом отправка var builder = new BodyBuilder() { TextBody = mailLotusOutlookOut.Body }; if (mailLotusOutlookOut.FullPathListFile != null) { foreach (var fullFileName in mailLotusOutlookOut.FullPathListFile.Split(';')) { builder.Attachments.Add(fullFileName); } var nameFile = DateTime.Today.ToString("dd.MM.yyyy_HH.mm.ss") + ".zip"; var fullPathZip = Path.Combine(parameters.PathSaveArchive, nameFile); mailLotusOutlookOut.FileMailZip = zipAttach.StartZipArchiveOut(mailLotusOutlookOut.FullPathListFile.Split(';'), fullPathZip); mailLotusOutlookOut.NameFileZip = nameFile; } //Проверка почты var user = new List <string>() { mailLotusOutlookOut.MailAdressIn }; var arrayMail = MailArraySubject(mailLotusOutlookOut.MailAdressOut); if (arrayMail.Length > 0) { mailLotusOutlookOut.ErrorMail = $"Письмо отправлено адресатам {string.Join("/", arrayMail)}"; foreach (var mail in arrayMail) { MimeMessage mailToClient = new MimeMessage(); mailToClient.To.Add(new MailboxAddress(mail)); mailToClient.Subject = string.IsNullOrWhiteSpace(mailLotusOutlookOut.SubjectMail) ? "" : mailLotusOutlookOut.SubjectMail; mailToClient.From.Add(new MailboxAddress(mailLotusOutlookOut.MailAdressIn, parameters.LoginR7751)); //Сюда идентификатор mailToClient.Headers[HeaderId.MessageId] = mailToClient.MessageId; mailToClient.Headers[HeaderId.ResentMessageId] = mailToClient.MessageId; mailToClient.Headers[HeaderId.DispositionNotificationTo] = parameters.LoginR7751; mailToClient.Headers[HeaderId.ReturnReceiptTo] = parameters.LoginR7751; mailToClient.Body = builder.ToMessageBody(); try { using (var smtp = new SmtpCustomClient.SmtpCustomClient()) { smtp.DeliveryStatusNotificationType = DeliveryStatusNotificationType.Full; smtp.CheckCertificateRevocation = false; smtp.Connect(parameters.Pop3Address, 465, true); smtp.Authenticate(parameters.LoginR7751, parameters.PasswordR7751); smtp.Send(mailToClient); smtp.Disconnect(true); } Loggers.Log4NetLogger.Info(new Exception($"Отправка письма {mailLotusOutlookOut.IdMail} на адрес {mail}")); } catch (Exception ex) { Loggers.Log4NetLogger.Error(ex); mailLotusOutlookOut.ErrorMail = $"Письмо не отправлено адресату возникли ошибки во время отправки"; } } Mail.SendMailAutoOutput(user, $"Отправка писем произведена!!!", $"Адреса участники рассылки \r\n {string.Join("\r\n", arrayMail)}"); } else { Mail.SendMailAutoOutput(user, $"Отправка писем на адрес(а) не возможна {mailLotusOutlookOut.MailAdressOut} !!!", $"Ошибка почты {mailLotusOutlookOut.MailAdressOut} !!!"); mailLotusOutlookOut.ErrorMail = $"Почтовый ящик(и) не прошел(и) проверку отправка не возможна!"; Loggers.Log4NetLogger.Error(new Exception($"Отправка письма {mailLotusOutlookOut.IdMail} не прошла проверку внешних адресов")); } mailSave.AddModelMailOut(mailLotusOutlookOut); } //Очистить временную папку с файлами zipAttach.DropAllFileToPath(parameters.PathSaveArchive); Loggers.Log4NetLogger.Info(new Exception("Отправка почты внешнем абонентам закончена!")); } catch (Exception e) { Console.WriteLine(e); throw; } finally { Mail.Dispose(); } }