/// <summary> /// /// </summary> /// <param name="collectionMessageAttach">Коллекция календарей</param> /// <param name="mimeMessage">Письмо из почты</param> public string CalendarParser(List <MimeEntity> collectionMessageAttach, MimeMessage mimeMessage) { var mailCalendar = new MailLogicLotus(); var calendar = new Calendar(); var option = FormatOptions.Default.Clone(); option.AllowMixedHeaderCharsets = false; foreach (var mimeEntity in collectionMessageAttach) { try { string contentDecode; using (var stream = new MemoryStream()) { mimeEntity.WriteTo(option, stream); contentDecode = Encoding.UTF8.GetString(stream.ToArray()); } string[] separator = { Environment.NewLine }; contentDecode = string.Join(" ", contentDecode.Split(separator, StringSplitOptions.RemoveEmptyEntries)); var descriptionFull = Regex.Match((contentDecode), @"DESCRIPTION:(.+)DTEND").Value; var descriptionAll = Regex.Match(descriptionFull, @"([^DESCRIPTION:](.+)[^DTEND])").Value; var description = Regex.Match(descriptionAll, @"(.+=)").Value.TrimEnd(new[] { '=', 'И', 'Д', 'I', 'D', 'n', '\\' }); var idVks = Regex.Match(descriptionFull, "([^=][0-9]{3,6})").Value; var dateEndPresumably = Regex.Match(contentDecode, "DTEND;TZID=\"Russian Standard Time\":([0-9]+T[0-9]+Z?)").Value; var dateStartPresumably = Regex.Match(contentDecode, "DTSTART;TZID=\"Russian Standard Time\":([0-9]+T[0-9]+Z?)").Value; var dateEnd = Regex.Match(dateEndPresumably, "([0-9]+T[0-9]+Z?)").Value; var dateStart = Regex.Match(dateStartPresumably, "([0-9]+T[0-9]+Z?)").Value; calendar.DescriptionVKS = $"{description} {mimeMessage.Subject}"; calendar.FullDescription = descriptionAll; calendar.IdMail = mimeMessage.MessageId; calendar.DateStart = Convert.ToDateTime(dateStart.Insert(4, "-").Insert(7, "-").Insert(13, ":").Insert(16, ":")); calendar.DateFinish = Convert.ToDateTime(dateEnd.Insert(4, "-").Insert(7, "-").Insert(13, ":").Insert(16, ":")); calendar.IdVKS = idVks; mailCalendar.AddModelCalendar(calendar); } catch (Exception ex) { Loggers.Log4NetLogger.Error(new Exception($"Во время работы с календарем по письму {mimeMessage.MessageId} произошла ошибка!")); Loggers.Log4NetLogger.Error(ex); } } mailCalendar.Dispose(); return($"Добавлено в календарь запись о ВКС {calendar.FullDescription} ID {calendar.IdVKS} Дата начала {calendar.DateStart} Дата окончания {calendar.DateFinish}"); }
/// <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); } }