public void Dispose() { OnStateChanged(new StatusEventArgs(StatusType.ews_stopped, "stopped")); _bRunThread = false; if (_thread != null) { //try to join thread bool b = _thread.Join(1000); if (!b) { _thread.Abort(); } } MailNS.Logoff(); OnStateChanged(new StatusEventArgs(StatusType.ews_stopped, "outlook session ended")); }
/// <summary> /// Get the foldername from the FolderId and StoreId /// </summary> /// <param name="FolderId"></param> /// <param name="StoreId"></param> /// <returns></returns> private string GetFolderById(string FolderId, string StoreId) { object missing = Missing.Value; string foldername = string.Empty; // if invalid input data then exit returning empty string if (FolderId == string.Empty || StoreId == string.Empty) { return(string.Empty); } //get the Outlook Application Object Outlook.Application outlookApplication = new Outlook.Application(); //get the namespace object Outlook.NameSpace nameSpace = outlookApplication.GetNamespace("MAPI"); //Logon to Session, here we use an already opened Outlook session nameSpace.Logon(missing, missing, false, false); //get the InboxFolder Outlook.MAPIFolder Folder = nameSpace.GetFolderFromID(FolderId, StoreId); if (Folder != null) { foldername = Folder.Name; } //release used resources Marshal.ReleaseComObject(Folder); //logof from namespace nameSpace.Logoff(); //release resources Marshal.ReleaseComObject(nameSpace); Marshal.ReleaseComObject(outlookApplication.Application); return(foldername); }
private void DownloadAttachment(string MailSub, string MailFrom, string MailTo, string MailCC, string SMTPServer, ref bool ErrorStatus) { try { string FilePath = Dts.Variables["User::FOLDER_DownloadAttachmentLocation"].Value.ToString(); string FileNamewithPath = null; string Expense_Subj = Dts.Variables["User::MAIL_ExpenseSubject"].Value.ToString(); Outlook.Application OApp = new Outlook.Application(); Outlook.NameSpace ONameSpace = OApp.GetNamespace("MAPI"); //Outlook.MailItem OMail = null; Outlook.MAPIFolder InboxFolder, ExpenseFolder, ExpenseLoadedFolder = null; ArrayList MailCollection = new ArrayList(); ONameSpace.Logon("user/someuser", null, false, true); InboxFolder = ONameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); ExpenseFolder = InboxFolder.Folders["Project"]; ExpenseLoadedFolder = ExpenseFolder.Folders["Downloaded"]; Outlook.Items OItem = InboxFolder.Items; if (ExpenseFolder.Items.Count == 0) { string MailBody; MailSub = "Expense - Couldn't find email in mailbox"; MailBody = ("<html><div style=font-family:Calibri;font-size:11.0pt;color:#000000>"); MailBody += "Hello Team </BR></BR>"; MailBody += "There were no Expense email in the Mailbox to download the required .ZIP attachments</BR></BR>"; MailBody += "Thank you,</BR>"; MailBody += "YourReports"; SendMail(MailFrom, MailTo, MailCC, MailSub, SMTPServer, MailBody); Dts.TaskResult = (int)ScriptResults.Failure; } else { foreach (Outlook.MailItem item in ExpenseFolder.Items) { if (item != null && (item.Subject.Contains(Expense_Subj))) { MailCollection.Add(item); } } foreach (Outlook.MailItem OMItem in MailCollection) { foreach (Outlook.Attachment OAttactment in OMItem.Attachments) { if (OAttactment.FileName.ToString().EndsWith(".zip")) { FileNamewithPath = FilePath + OAttactment.FileName; OAttactment.SaveAsFile(FileNamewithPath); } } OMItem.Move(ExpenseLoadedFolder); } ONameSpace.Logoff(); OItem = null; MailCollection = null; ONameSpace = null; OApp = null; } } catch (Exception ex) { string MailBody; MailSub = "Expense - Download attachment component failed"; MailBody = "Hello Team </BR></BR>"; MailBody += string.Format("Download attachment component failed due to:</BR><b>Error message:</b>{0}</BR></BR>", ex.Message); MailBody += "Thank you,</BR>"; MailBody += "YourReports"; SendMail(MailFrom, MailTo, MailCC, MailSub, SMTPServer, MailBody); UpdateErrorStatus(ref ErrorStatus); } }
/// <summary> /// Imports the items in Outlook calendar folder of current user /// </summary> public ServiceResult <OutlookItemImportServiceResult> ImportOutlookCalendarItems() { Outlook.Application outlookApp = null; Outlook.NameSpace mapiNamespace = null; Outlook.MAPIFolder CalendarFolder = null; Outlook.Items outlookCalendarItems = null; var messages = new List <Message>(); var countOfFailedReminderSchedules = 0; // try to initialize Outlook API and log on try { outlookApp = new Outlook.Application(); mapiNamespace = outlookApp.GetNamespace("MAPI"); CalendarFolder = mapiNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar); mapiNamespace.Logon(Missing.Value, Missing.Value, true, true); } catch (Exception ex) { messages.Add(new Message() { Text = string.Format("Neparedzēta kļūda. ", ex.Message), Severity = MessageSeverity.Error }); } //build a filter from user inputs String filter = String.Format("([Start] >= '{0:g}') AND ([End] <= '{1:g}')", IntervalStart, IntervalEnd); //get the filtered Outlook items including the recurring items and sort them to expand the recurrences automatically outlookCalendarItems = CalendarFolder.Items.Restrict(filter); outlookCalendarItems.Sort("[Start]"); outlookCalendarItems.IncludeRecurrences = true; //if there are no items in the calendar folder within the specified interval, return and notify the user if (outlookCalendarItems.GetFirst() == null) { var message = "Norādītajā laika periodā Jūsu Outlook kalendārā netika atrasts neviens uzdevums"; return(new ServiceResult <OutlookItemImportServiceResult>() { Data = OutlookItemImportServiceResult.NotImported, Messages = new Message[] { new Message() { Text = message, Severity = MessageSeverity.Info } } }); } //iterate through each returned Outlook calendar item and process it foreach (Outlook.AppointmentItem item in outlookCalendarItems) { var existingWorkItem = this.dataContext.WorkItems.Where(o => o.OutlookEntryId != null && o.OutlookEntryId == item.EntryID).FirstOrDefault(); //if item is not recurring, create a new work item or update an exisiting one if (!item.IsRecurring) { if (existingWorkItem == null) { var workItem = CreateNonRecurringWorkItem(item); this.dataContext.WorkItems.Add(workItem); countOfFailedReminderSchedules += ScheduleReminder(workItem); } else { if (existingWorkItem.UpdatedAt <= item.LastModificationTime) { UpdateNonRecurringWorkItem(existingWorkItem, item); countOfFailedReminderSchedules += ScheduleReminder(existingWorkItem); } } this.dataContext.SaveChanges(); } else if (item.IsRecurring) { Outlook.RecurrencePattern recurrencePattern = item.GetRecurrencePattern(); RecurrenceType recurrenceType = 0; //Get all the exceptions in the series of this recurring item, e.g. items which belong to a series of occurrences, but whose properties have been changed List <Outlook.Exception> exceptions = new List <Outlook.Exception>(); foreach (Outlook.Exception exception in recurrencePattern.Exceptions) { exceptions.Add(exception); } int recurTypeId = (int)recurrencePattern.RecurrenceType; bool hasEndDate; if (recurrencePattern.NoEndDate == true) { hasEndDate = false; } else { hasEndDate = true; } //determine the recurrence type of the item switch (recurTypeId) { case 0: recurrenceType = RecurrenceType.Daily; break; case 1: recurrenceType = RecurrenceType.Weekly; break; case 2: recurrenceType = RecurrenceType.Monthly; break; case 3: recurrenceType = RecurrenceType.MonthNth; break; case 4: recurrenceType = RecurrenceType.Yearly; break; case 6: recurrenceType = RecurrenceType.YearNth; break; default: break; } if (existingWorkItem == null) { //Create a new work item that will act as a parent for all of its recurring items var workItem = new WorkItem(); //if recurrence pattern has end date we save it, //else we assume the end date is the end of the year to avoid large data sets if (hasEndDate == true) { workItem.EndDateTime = recurrencePattern.PatternEndDate; } else { workItem.EndDateTime = new DateTime(DateTime.Now.Year, 12, 31); } workItem.Subject = item.Parent.Subject; workItem.Location = item.Parent.Location; workItem.Body = item.Parent.Body; workItem.OutlookEntryId = item.Parent.EntryID; workItem.StartDateTime = recurrencePattern.PatternStartDate; workItem.Duration = item.Parent.Duration / 60; workItem.WorkItemType = WorkItemType.Appointment; workItem.isRecurring = true; //add the recurrence pattern workItem.RecurrencePattern = new WIRecurrencePattern { Interval = recurrencePattern.Interval, DayOfWeekMask = (DayOfWeekMask)Enum.ToObject(typeof(DayOfWeekMask), recurrencePattern.DayOfWeekMask), DayOfMonth = recurrencePattern.DayOfMonth, MonthOfYear = (MonthOfYear)Enum.ToObject(typeof(MonthOfYear), recurrencePattern.MonthOfYear), Instance = (Instance)Enum.ToObject(typeof(Instance), recurrencePattern.Instance) }; //add the recurring item workItem.RecurringItems = new List <RecurringItem>(); workItem.RecurringItems.Add(new RecurringItem { OriginalDate = item.Start, Start = item.Start, End = item.End, Duration = (item.End - item.Start).TotalHours, Origin = this.CurrentUser.BaseLocation, Subject = item.Subject, Body = item.Body, Location = item.Location, UpdatedAt = DateTime.Now }); countOfFailedReminderSchedules += ScheduleReminder(workItem, workItem.RecurringItems.FirstOrDefault()); workItem.RecurrenceType = recurrenceType; workItem.CreatedByUserId = this.CurrentUser.UserId; workItem.UpdatedByUserId = this.CurrentUser.UserId; this.dataContext.WorkItems.Add(workItem); this.dataContext.SaveChanges(); } else { //Check if recurrence pattern has not changed var existingPattern = existingWorkItem.RecurrencePattern; int mismatch = 0; if (existingPattern.Interval != recurrencePattern.Interval) { mismatch = 1; } if ((int)existingPattern.DayOfWeekMask != (int)recurrencePattern.DayOfWeekMask) { mismatch = 1; } if ((int)existingPattern.Instance != recurrencePattern.Instance) { mismatch = 1; } if (existingPattern.DayOfMonth != recurrencePattern.DayOfMonth) { mismatch = 1; } if ((int)existingPattern.MonthOfYear != recurrencePattern.MonthOfYear) { mismatch = 1; } if (mismatch == 1) { //if the pattern has changed delete all of the old recurring items, save the new pattern and asociate it with the work item foreach (var recurringItem in existingWorkItem.RecurringItems.ToList()) { this.dataContext.RecurringItems.Remove(recurringItem); var jobId = this.scheduler.GetJobId(existingWorkItem, recurringItem); scheduler.RemoveReminder(jobId); } this.dataContext.WIRecurrencePatterns.Remove(existingPattern); existingWorkItem.RecurrencePattern = new WIRecurrencePattern { Interval = recurrencePattern.Interval, DayOfWeekMask = (DayOfWeekMask)Enum.ToObject(typeof(DayOfWeekMask), recurrencePattern.MonthOfYear), DayOfMonth = recurrencePattern.DayOfMonth, MonthOfYear = (MonthOfYear)Enum.ToObject(typeof(MonthOfYear), recurrencePattern.MonthOfYear), Instance = (Instance)Enum.ToObject(typeof(Instance), recurrencePattern.MonthOfYear) }; } else { //if pattern hasn`t changed maybe the time span of the pattern has changed, if so, update the datetime values and remove unnecessary recurring items if (recurrencePattern.PatternStartDate != existingWorkItem.StartDateTime || recurrencePattern.PatternEndDate != existingWorkItem.EndDateTime) { foreach (var recurringItem in existingWorkItem.RecurringItems .Where(o => o.Start <recurrencePattern.PatternStartDate || o.End> recurrencePattern.PatternEndDate) .ToList()) { this.dataContext.RecurringItems.Remove(recurringItem); var jobId = this.scheduler.GetJobId(existingWorkItem, recurringItem); scheduler.RemoveReminder(jobId); } existingWorkItem.StartDateTime = recurrencePattern.PatternStartDate; existingWorkItem.StartDateTime = recurrencePattern.PatternEndDate; } } // we only need to look at the exceptions that are not deleted var nonDeletedException = exceptions.Where(o => o.Deleted == true).ToList(); var exception = nonDeletedException.Find(o => o.AppointmentItem.Start == item.Start); if (exception != null) { var existingRecurringItem = this.dataContext.RecurringItems.Where(o => o.OriginalDate == exception.OriginalDate).FirstOrDefault(); if (existingRecurringItem != null) { UpdateRecurringItem(existingRecurringItem, item); countOfFailedReminderSchedules += ScheduleReminder(existingRecurringItem.WorkItem, existingRecurringItem); } else { existingWorkItem.RecurringItems.Add(new RecurringItem { OriginalDate = item.Start, Exception = true, Start = item.Start, End = item.End, Subject = item.Subject, Body = item.Body, Location = item.Location, UpdatedAt = DateTime.Now }); countOfFailedReminderSchedules += ScheduleReminder(existingWorkItem, existingWorkItem.RecurringItems.FirstOrDefault()); } } else { var existingRecurringItem = existingWorkItem.RecurringItems.Where(o => o.OriginalDate == item.Start).FirstOrDefault(); if (existingRecurringItem == null) { existingWorkItem.RecurringItems.Add(new RecurringItem { OriginalDate = item.Start, Exception = false, Start = item.Start, End = item.End, Subject = item.Subject, Body = item.Body, Location = item.Location, UpdatedAt = DateTime.Now }); countOfFailedReminderSchedules += ScheduleReminder(existingWorkItem, existingWorkItem.RecurringItems.FirstOrDefault()); } else { UpdateRecurringItem(existingRecurringItem, item); countOfFailedReminderSchedules += ScheduleReminder(existingRecurringItem.WorkItem, existingRecurringItem); } } this.dataContext.SaveChanges(); } } } //Log off mapiNamespace.Logoff(); if (countOfFailedReminderSchedules > 0) { messages.Add(new Message() { Text = string.Format("{0} no importētajiem uzdevumiem netika ieplānoti atgādinājumi, jo šajā procesā rādās kļūdas", countOfFailedReminderSchedules.ToString()), Severity = MessageSeverity.Warning }); } var result = new ServiceResult <OutlookItemImportServiceResult>(); result.Messages = messages.ToArray(); if (messages.Any(m => m.Severity == MessageSeverity.Error)) { result.Data = OutlookItemImportServiceResult.Error; } else if (messages.Any(m => m.Severity == MessageSeverity.Warning)) { result.Data = OutlookItemImportServiceResult.OkWithWarnings; } else { result.Data = OutlookItemImportServiceResult.Ok; } return(result); }
/* * Process mail items in a given mailstore and its designated folders, see class MailStorConfig for config details */ public bool?process(MailStoreConfig subject, Object controller, IDictionary <string, string> configs = null) { Outlook.Application oApp = null; Outlook.NameSpace oNS = null; Outlook.MAPIFolder rdestFolder = null; Outlook.MAPIFolder destFolder = null; Outlook.MAPIFolder rootf = null; Outlook.Items items = null; Outlook.MailItem mail = null; try { configs = configs ?? new Dictionary <string, string>(); //Interop with Outlook and log on oNS = logOn(oApp = new Outlook.Application()); var store = oApp.Session.Stores[subject.storename]; rootf = store.GetRootFolder(); configs[EPconfigsEnum.storename.ToString()] = subject.storename; // configs[XCDconfigsEnum.dpath.ToString()] = subject.dpath; configs[EPconfigsEnum.saveMailPath.ToString()] = pnc?.execute(subject.savemailpath, null, null) ?? subject.savemailpath; configs[EPconfigsEnum.retfolder.ToString()] = String.IsNullOrWhiteSpace(subject.retfolder) ? "Inbox" : subject.retfolder; configs[EPconfigsEnum.rdestFolder.ToString()] = subject.rejfolder; configs[EPconfigsEnum.sucTemplate.ToString()] = subject.sucTemplate?.FullName; configs[EPconfigsEnum.sucFolder.ToString()] = subject.sucfolder; configs[EPconfigsEnum.sentonbehalf.ToString()] = subject.sentonbehalf; destFolder = rootf.Folders[configs[EPconfigsEnum.destFolder.ToString()] = subject.infolder]; destFolder.Session.SendAndReceive(false); items = String.IsNullOrWhiteSpace(subject.restricter) ? destFolder.Items : destFolder.Items.Restrict(subject.restricter); //Proceed to iterate mails per defined filters if ((mail = items.GetLast() as Outlook.MailItem) != null) { return(new EmailProcessor() { oApp = oApp, sendResponse = true, saveChanges = true, moveFolder = true, validColsCols = subject.validColsCol.SelectMany(vc => vc), vconfigCol = subject.validColsCol, pnc = new ProperNameController() }.process(mail, null, configs)); } return(true); } catch (Exception ex) { Logger.Log(ex); return(false); } finally { if (mail != null) { Marshal.ReleaseComObject(mail); } if (items != null) { Marshal.ReleaseComObject(items); } if (rdestFolder != null) { Marshal.ReleaseComObject(rdestFolder); } if (rootf != null) { Marshal.ReleaseComObject(rootf); } if (oNS != null) { oNS.Logoff(); Marshal.ReleaseComObject(oNS); } if (oApp != null) { Marshal.ReleaseComObject(oApp); } GC.Collect(); GC.WaitForPendingFinalizers(); } }
static void Main(string[] args) { repiat: Console.Clear(); Console.WriteLine("НАчинаю работу приложения"); /************************переменные для логера**************************/ const string Error_ = "Ошибка"; const string Warning_ = "Предупреждение"; const string Event_ = "Событие"; /************************переменные для логера конец********************/ //Logger.Run_(); Logger.WriteLog(Event_, 0, "Старт"); /**********Выполняем батники для отправки**********/ /***********Переменные для батников*********/ string batPuttyOut1 = @"C:\tkM\copyOUTputty.bat"; string batPuttyOut2 = @"C:\tkM\copyOUTarch.bat"; string batInPutty1 = @"C:\tkM\copyOUTarch.bat"; string batInPutty2 = @"C:\tkM\copyOUTarch.bat"; string pathBat = @"C:\tkM"; string descrBatO1 = "fromPuttyToOut1"; string descrBatO2 = "fromPuttyToOut2"; string descrBatI3 = "fromPuttyToIN1"; string descrBatI4 = "fromPuttyToIN2"; //*************батники на отправку*********// FileM.ProcManage(batPuttyOut1, pathBat, descrBatO1); FileM.ProcManage(batPuttyOut2, pathBat, descrBatO2); //try //{ //System.Diagnostics.Process proc = new System.Diagnostics.Process(); //proc.StartInfo.FileName = @"C:\tkM\copyOUTarch.bat"; //proc.StartInfo.WorkingDirectory = @"C:\tkM"; //proc.Start(); //proc.WaitForExit(); // Console.WriteLine("Батники на отправку успешно отработали"); // Logger.WriteLog(Event_ , 0, "Батники на отправку успешно отработали"); // proc = null; //ufc //} //catch(System.Exception ex) //{ // Logger.WriteLog(Error_, 100 , "ошибка выолнения батников" + Convert.ToString(ex.Message)); // Console.WriteLine("ошибка выолнения батников" + Convert.ToString(ex.Message)); //} /********************/ Logger.WriteLog(Event_, 0, "Выполняю модуль отправки писем"); Console.WriteLine("Выполняю модуль отправки писем"); //Outlook.Application application; // Outlook._NameSpace nameSpace; Outlook.MAPIFolder folderInbox; ////////////////////////////////// //Microsoft.Office.Interop.Outlook._Folders oFolders; ///////////////1 модуль отправки файлов/////////////////// string[] dirs; dirs = Directory.GetFiles(@"C:\tkM\OUT"); //дирректория - откуда берём файл String dirs1count = Directory.GetFiles(@"C:\tkM\OUT").Length.ToString(); //если в папке out что то есть то отправляем письмо for (int i = 0; i < dirs.Length; i++) //для отправки 1 письмо + 1 файл { Logger.WriteLog(Event_, 0, "Запускаю цикл обработки и отправки входящих файлов"); if (Convert.ToInt32(dirs1count) > 0) { Logger.WriteLog(Event_, 0, "Колличество файлов на отправку: " + dirs1count); Console.WriteLine("Выполняю модуль отправки писем"); //string dirArch = "C://OUT//ARCH//"; try { //тело отправляемого сообщения Outlook._Application _app = new Outlook.Application(); Outlook.MailItem mail = (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem); mail.To = "*****@*****.**"; //"*****@*****.**"; mail.Subject = "test1567"; // тема mail.Body = "This is test message1156711"; //текст письма mail.Importance = Outlook.OlImportance.olImportanceNormal; //какае то нужная вещь foreach (string s in dirs) { try { Console.WriteLine(s); mail.Attachments.Add(s); //добавляем вложения в письмо - возможно добавить сразу все вложения File.Move(s, s.Replace("OUT", "ARCH")); //После успешного прикрепления файла, переносим их в папку C:\ARCH ((Outlook._MailItem)mail).Send(); //отправляем письмо Console.WriteLine("Файл" + s + "отправлен в ТК"); // если все хорошо, то выдаём в консоль сообщение Logger.WriteLog(Event_, 0, "Файл" + s + "отправлен в ТК"); break; // выхожу из цикла, что бы реализовать фичу 1 фал = 1 письмо, и так сойдёт :) рефакторинг потом } catch (System.Exception ex) { Logger.WriteLog(Warning_, 201, "Системное исключение" + ex.Message); Logger.WriteLog(Warning_, 200, "С таким именем файла уже отправлялось\n" + "Перемещаю файл" + s + "в папку Bad также прочти системное исключение"); Console.WriteLine("С таким именем файла уже отправлялось\n" + "Перемещаю файл в папку Bad"); FileM.MoveReplaceFile(s, s.Replace("OUT", "Bad")); //прописываю каталог C:\tkM\Bad так быстрее не люблю много переменных System.Threading.Thread.Sleep(1000); //спим 1000 мс что б увидеть работу кода } } Logger.WriteLog(Event_, 0, "успешно передан файл" + dirs[i]); _app = null; //убиваем ссылки на экземпляр класса mail = null; //Console.Read(); } catch (System.Exception ex) { Logger.WriteLog(Error_, 111, "Системная информация" + ex.Message); Console.WriteLine("Что то пошло не так"); // если какае то бага то пишем это сообщение Console.WriteLine("Не удалось отправить файлы, переходим к приёму файлов"); System.Threading.Thread.Sleep(1000); Logger.WriteLog(Warning_, 300, "Переходим к модулю обработки входящих писем"); goto importStart; //если модуль отправки не отработал то программа переходит к модулю чтения сообщений } ////////////////////////////Чтение сообщений и копирование вложений/////////////////////////////////////////// } else { Console.WriteLine("Файлов для отправки нет"); Logger.WriteLog(Event_, 0, "Файлов для отправки нет - Переходим к модулю обраюлтки входящих писем"); break; } //если нет файлов во вложении то выходим из цикла dirs1count = Directory.GetFiles(@"C:\tkM\OUT").Length.ToString(); dirs = Directory.GetFiles(@"C:\tkM\OUT"); //переинициализируем переменную с каждым шагом цикла - так как файлов то меньше на 1 System.Threading.Thread.Sleep(1000); } importStart: Logger.WriteLog(Event_, 0, "Обрабатываем входящие письма"); Outlook.Application oApp = new Outlook.Application();// создали новый экземпляр Outlook.NameSpace oNS = oApp.GetNamespace("MAPI"); //Это кусорк для чтения входящих сообщений для теста и понимания как это работает(раюотаем из папки входящие) //oNS.Logon(Missing.Value, Missing.Value, false, true); //Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); //for (int x = 1; x <= oInbox.Items.Count; x++) //{ // if (oInbox.Items[x] is MailItem) // { // //Выводим Имя отправителя // Console.WriteLine(oInbox.Items[x].SenderName + "\n" + "--------------------------------------------" + "\n"); // } //} nameSpace = oApp.GetNamespace("MAPI"); object missingValue = System.Reflection.Missing.Value; folderInbox = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); //Outlook.OlDefaultFolders.olFolderInbox //количество не прочитанных писем в папке Входящие (Inbox) Outlook.MAPIFolder rootFolder = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); //получаем доступ к папке входящие Outlook.MAPIFolder processedFolder = null; //processedFolder это экземпляр класса который выбирает нужную папку foreach (Outlook.MAPIFolder folder in rootFolder.Folders) // ищем циклом папку в OUTLOOK { if (folder.Name == "IN") //берем из папки IN { processedFolder = folder; // выбираю папку с которой будем работать(в OUTLOOK нужно создать правило, что бы все вообщения от почты ТК переносились в папку IN, которую мы заранее создаём в OUTLOOK) break; } } Outlook.Items unreadItems = processedFolder.Items.Restrict("[Unread]=true"); // работаем с данной папкой и ищем не прочитанные письма Console.WriteLine("Непрочитанных писем в папке in = " + unreadItems.Count.ToString()); // выдать в консоль колличество непрочитанных сообщений Logger.WriteLog(Event_, 0, "Непрочитанных писем в папке in = " + unreadItems.Count.ToString()); //////////здесь вываодим в консоль все данные непрочитанные письма в папке in можно заккоментить///////////////////////// StringBuilder str = new StringBuilder(); //читаем текст и данные письма выыодим в консоль не обязательно, но можно оставить для логирования try { DateTime sysdate_ = DateTime.Now; foreach (Outlook.MailItem mailItem in unreadItems) { Logger.WriteLog(Event_, 0, "Читаю письмо"); str.AppendLine("----------------------------------------------------"); str.AppendLine("SenderName: " + mailItem.SenderName); str.AppendLine("To: " + mailItem.To); str.AppendLine("CC: " + mailItem.CC); str.AppendLine("Subject: " + mailItem.Subject); str.AppendLine("Body: " + mailItem.Body); str.AppendLine("CreationTime: " + mailItem.CreationTime); str.AppendLine("ReceivedByName: " + mailItem.ReceivedByName); str.AppendLine("ReceivedTime: " + mailItem.ReceivedTime); str.AppendLine("UnRead: " + mailItem.UnRead); str.AppendLine(mailItem.ReceivedTime.Date.ToShortDateString() + sysdate_.ToShortDateString()); str.AppendLine("----------------------------------------------------"); Console.WriteLine(str.ToString()); Logger.WriteLog(Event_, 0, str.ToString()); } } catch (System.Exception ex) // если письмо бракованное то пробуем ещё раз { //System.Threading.Thread.Sleep(300); //пауза //goto repeatReadMail; Logger.WriteLog(Error_, 102, "Ощибка сохранения письма или" + ex.Message); string errorInfo = (string)ex.Message.Substring(0, 11); Console.WriteLine(errorInfo);// вывести любую ошибку if (errorInfo == "Cannot save") { Console.WriteLine(@"Create Folder C:\TestFileSave"); } Logger.WriteLog(Event_, 0, "Перехожу к чтению вложений"); goto repeatReadAndAddAttachmentIsMail; // перейти к чтению и вытаскиванию вложения в случае ошибки здесь } //foreach (Outlook.MailItem mail in unreadItems) //пометить как прочитанное реализация не удалять //{ // if (mail.UnRead) // { // mail.UnRead = false; // mail.Save(); // } //} //////////////////Вытаскивание вложение и пометить письмо как прочитанное repeatReadAndAddAttachmentIsMail: Outlook.Items inBoxItems = processedFolder.Items.Restrict("[Unread]=true");//show unread message and inicialise varible Outlook.MailItem newEmail = null; try { foreach (object collectionItem in inBoxItems) { newEmail = collectionItem as Outlook.MailItem; DateTime sysdate_ = DateTime.Now; //SYSDATE //mailItem.ReceivedTime.Date.ToShortDateString() + sysdate_.ToShortDateString(); if (newEmail != null /*&& newEmail.ReceivedTime.Date.ToShortDateString() == sysdate_.ToShortDateString()*/) //checj date of mail { if (newEmail.Attachments.Count > 0) { for (int i = 1; i <= newEmail.Attachments.Count; i++) { string fileName = newEmail.Attachments[i].FileName; Console.WriteLine(@"Имя файла:" + fileName); string[] dirsaRCH = Directory.GetFiles(@"C:\tkM\ARCH\");//создадим перепенную с именами файлов в папке ARCH что бы проверять файлы в архиве if (FileM.ValueOf(dirsaRCH, fileName) != "noDuble") { Console.WriteLine(@"Найдено совпаление с файлом: " + fileName + "\n Список файлов в папке:"); Logger.WriteLog(Warning_, 0, @"Найдено совпаление с файлом: " + fileName + "не обратываем"); //for (int i1 = 0; i1 < dirsaRCH.Length; i1++) //{ // Console.Write( dirsaRCH[i1] + " " + File.GetCreationTime(dirsaRCH[i1]) + " - не обратываем" + ";\n"); // Logger.WriteLog(Warning_, 205, dirsaRCH[i1] + " " + File.GetCreationTime(dirsaRCH[i1]) + " - не обратываем" + ";\n"); //} } else { Console.WriteLine(@"нет совпадения файлов"); Logger.WriteLog(Event_, 0, @"Совпадений по имени не найдено"); //Console.WriteLine(@"Имя файла:" + fileName); //for (int i1 = 0; i1 < dirsaRCH.Length; i1++) //{ // Console.Write("Имя файлов(а) в папке:" + dirsaRCH[i1]); //} newEmail.Attachments[i].SaveAsFile(@"C:\tkM\IN\" + newEmail.Attachments[i].FileName); Console.WriteLine(@"Файл сохранён с названием: " + newEmail.Attachments[i].FileName + " По пути:" + @"C:\tkM\IN\"); // выводим инфу об успешно копировании файла Logger.WriteLog(Event_, 0, @"Файл сохранён с названием: " + newEmail.Attachments[i].FileName + " По пути:" + @"C:\tkM\IN\"); } // { Console.WriteLine(@"Обрабатываю письмо как прочитанное"); Logger.WriteLog(Event_, 0, @"Обрабатываю письмо как прочитанное"); System.Threading.Thread.Sleep(1000); if (newEmail.UnRead) // пометить письмо как прочитанное { newEmail.UnRead = false; newEmail.Save(); } /********батники на IN************/ FileM.ProcManage(batInPutty1, pathBat, descrBatI3); FileM.ProcManage(batInPutty2, pathBat, descrBatI4); /********************/ string[] dirIN = Directory.GetFiles(@"C:\tkM\IN"); foreach (string d in dirIN) { FileM.MoveReplaceFile(d, d.Replace("IN", "ARCH")); } Console.WriteLine(@"Завершаю работу"); //} } } } else { Console.WriteLine("Нет писем с вложением"); } } } catch (System.Exception ex) { string errorInfo = (string)ex.Message .Substring(0, 11); Console.WriteLine(errorInfo); if (errorInfo == "Cannot save") { Console.WriteLine(@"Create Folder C:\IN"); } } //////////выход из приложения oNS.Logoff(); //oInbox = null; oNS = null; oApp = null; //Console.ReadKey(); //Удалить все чтения ввода с консоли, для автоматической работы Logger.Flush(); Console.WriteLine($"Закончили обработку в {DateTime.Now} " + $"\nСледующий запуск приложения в {DateTime.Now.Add(TimeSpan.FromMinutes(5))} "); System.Threading.Thread.Sleep(15000); goto repiat; }
static void AutomateOutlook() { object missing = Type.Missing; Outlook.Application oOutlook = null; Outlook.NameSpace oNS = null; Outlook.Folder oCtFolder = null; Outlook.Items oCts = null; Outlook.MailItem oMail = null; try { // Start Microsoft Outlook and log on with your profile. // Create an Outlook application. oOutlook = new Outlook.Application(); Console.WriteLine("Outlook.Application is started"); Console.WriteLine("User logs on ..."); // Get the namespace. oNS = oOutlook.GetNamespace("MAPI"); // Log on by using a dialog box to choose the profile. oNS.Logon(missing, missing, true, true); // Alternative logon method that uses a specific profile. // If you use this logon method, change the profile name to an // appropriate value. The second parameter of Logon is the password // (if any) associated with the profile. This parameter exists only // for backwards compatibility and for security reasons, and it is // not recommended for use. //oNS.Logon("YourValidProfile", missing, false, true); Console.WriteLine("Press ENTER to continue when Outlook is ready."); Console.ReadLine(); // Enumerate the contact items. Console.WriteLine("Enumerate the contact items"); oCtFolder = (Outlook.Folder)oNS.GetDefaultFolder( Outlook.OlDefaultFolders.olFolderContacts); oCts = oCtFolder.Items; // Enumerate the contact items. Be careful with foreach loops. // See: http://tiny.cc/uXw8S. for (int i = 1; i <= oCts.Count; i++) { object oItem = oCts[i]; if (oItem is Outlook.ContactItem) { Outlook.ContactItem oCt = (Outlook.ContactItem)oItem; Console.WriteLine(oCt.Email1Address); // Do not need to Marshal.ReleaseComObject oCt because // (Outlook.ContactItem)oItem is a simple .NET type // casting, instead of a COM QueryInterface. } else if (oItem is Outlook.DistListItem) { Outlook.DistListItem oDl = (Outlook.DistListItem)oItem; Console.WriteLine(oDl.DLName); // Do not need to Marshal.ReleaseComObject oDl because // (Outlook.DistListItem)oItem is a simple .NET type // casting, instead of a COM QueryInterface. } // Release the COM object of the Outlook item. Marshal.FinalReleaseComObject(oItem); oItem = null; } // Create and send a new mail item. Console.WriteLine("Create and send a new mail item"); oMail = (Outlook.MailItem)oOutlook.CreateItem( Outlook.OlItemType.olMailItem); // Set the properties of the email. oMail.Subject = "Feedback of All-In-One Code Framework"; oMail.To = "*****@*****.**"; oMail.HTMLBody = "<b>Feedback:</b><br />"; // Displays a new Inspector object for the item and allows users to // click on the Send button to send the mail manually. // Modal = true makes the Inspector window modal oMail.Display(true); // [-or-] // Automatically send the mail without a new Inspector window. //((Outlook._MailItem)oMail).Send(); // User logs off and quits Outlook. Console.WriteLine("Log off and quit the Outlook application"); oNS.Logoff(); ((Outlook._Application)oOutlook).Quit(); } catch (Exception ex) { Console.WriteLine("AutomateOutlook throws the error: {0}", ex.Message); } finally { // Manually clean up the explicit unmanaged Outlook COM resources by // calling Marshal.FinalReleaseComObject on all accessor objects. // See http://support.microsoft.com/kb/317109. if (oMail != null) { Marshal.FinalReleaseComObject(oMail); oMail = null; } if (oCts != null) { Marshal.FinalReleaseComObject(oCts); oCts = null; } if (oCtFolder != null) { Marshal.FinalReleaseComObject(oCtFolder); oCtFolder = null; } if (oNS != null) { Marshal.FinalReleaseComObject(oNS); oNS = null; } if (oOutlook != null) { Marshal.FinalReleaseComObject(oOutlook); oOutlook = null; } } }
private void ScanButton_Click(object sender, RoutedEventArgs e) { #region Validation if (!IsValidEmail(EmailAddressTextBox.Text)) { Log.Log("No valid email address entered."); EmailAddressTextBox.Background = System.Windows.Media.Brushes.Red; return; } if (String.IsNullOrWhiteSpace(SourceFolderTextBox.Text)) { Log.Log("No source folder name entered."); SourceFolderTextBox.Background = System.Windows.Media.Brushes.Red; return; } if (String.IsNullOrWhiteSpace(DestFolderTextBox.Text)) { Log.Log("No destination folder name entered."); DestFolderTextBox.Background = System.Windows.Media.Brushes.Red; return; } #endregion try { List <string> icList = new List <string>(); #region Outlook Outlook.Application oApp = null; Outlook.NameSpace oNameSpace = null; Outlook.MAPIFolder contractsSourceFolder = null; Outlook.MAPIFolder contractsDestFolder = null; Outlook.Items items = null; List <Outlook.MailItem> messages = null; try { oApp = new Outlook.Application(); oNameSpace = oApp.GetNamespace("mapi"); oNameSpace.Logon(Missing.Value, Missing.Value, false, true); contractsSourceFolder = oNameSpace.Folders[EmailAddressTextBox.Text].Folders[SourceFolderTextBox.Text]; contractsDestFolder = oNameSpace.Folders[EmailAddressTextBox.Text].Folders[DestFolderTextBox.Text]; items = contractsSourceFolder.Items; messages = new List <Outlook.MailItem>(); try { foreach (Outlook.MailItem msg in items) { if (msg.SenderName.Contains("DocuSign")) // DocuSign is an older format that isn't used anymore. just skip them { Log.Log("Encountered DocuSign."); continue; } try { string importantContent = ""; if (msg.SenderName == "HelloSign") { if (msg.Subject.Contains("You've been copied on Zojak")) { importantContent = msg.Body.Substring(msg.Body.IndexOf("@zojakworldwide.com") + 31); //importantContent = importantContent.Substring(0, importantContent.IndexOf("@zojakworldwide.com")); importantContent = importantContent.Substring(0, importantContent.IndexOf("\r\n")); } else if (msg.Subject.Contains("has been signed by")) { importantContent = msg.Body.Substring(msg.Body.IndexOf("Signer") + 11); //importantContent = importantContent.Substring(0, importantContent.IndexOf("@zojakworldwide.com")); importantContent = importantContent.Substring(0, importantContent.IndexOf("\r\n")); } else if (msg.Subject.Contains("Everyone has signed")) { importantContent = msg.Body.Substring(msg.Body.IndexOf("Signers") + 12); //importantContent = importantContent.Substring(0, importantContent.IndexOf("@zojakworldwide.com")); importantContent = importantContent.Substring(0, importantContent.IndexOf("\r\n")); } } else if (msg.Body.Contains("The document is being sent to:")) { importantContent = msg.Body.Substring(msg.Body.IndexOf("The document is being sent to:") + 35); importantContent = importantContent.Substring(0, importantContent.IndexOf("@zojakworldwide.com")); importantContent = importantContent.Substring(0, importantContent.IndexOf("\r\n")); } else if (msg.Body.Contains("The document is being sent in this order:")) { importantContent = msg.Body.Substring(msg.Body.IndexOf("1. ") + 3); //importantContent = importantContent.Substring(0, importantContent.IndexOf("@zojakworldwide.com")); importantContent = importantContent.Substring(0, importantContent.IndexOf("\r\n")); } else { Log.Log("Encountered unknown email format.\n\tFrom: " + msg.SenderName + "\n\tSubject: " + msg.Subject + "\n\tReceived at: " + msg.ReceivedTime); continue; } importantContent = importantContent.Trim(' ', '\r', '\n'); icList.Add(importantContent); messages.Add(msg); } catch (Exception ex) { Log.Error(ex, "Error reading message."); } } Log.Log("Completed scan. Found " + icList.Count + " contracts."); Log.Log("Checked for duplicates. Found " + icList.Distinct().ToList().Count + " unique contracts."); } catch (Exception ex) { Log.Error(ex, "Error walking through MailItems."); return; } } catch (Exception ex) { Log.Error(ex, "Error Setting up or leaving Outlook."); return; } #endregion #region Excel Excel.Application eApp = null; Excel.Workbook workbook = null; Excel.Worksheet worksheet = null; try { eApp = new Excel.Application(); workbook = eApp.Workbooks.Add(); worksheet = workbook.ActiveSheet; int i = 1; foreach (string contract in icList.Distinct().ToList()) { string tempcontract = contract.Trim(')'); string email = ""; foreach (char letter in contract.Substring(0, contract.Length - 1).Reverse()) { tempcontract = tempcontract.Remove(tempcontract.Length - 1); if (letter == '(') { break; } email = email.Insert(0, letter.ToString()); } worksheet.Cells[i, 7] = email; if (tempcontract.Contains("(")) { tempcontract = tempcontract.Trim(')', ' '); // label string name = ""; foreach (char letter in tempcontract.Reverse()) { tempcontract = tempcontract.Remove(tempcontract.Length - 1); if (letter == '(') { break; } name = name.Insert(0, letter.ToString()); } worksheet.Cells[i, 1] = name.Trim(' '); // legal worksheet.Cells[i, 4] = tempcontract.Trim(' '); } else if (tempcontract.Contains("/")) { tempcontract = tempcontract.Trim(')', ' '); // label string name = ""; foreach (char letter in tempcontract.Reverse()) { tempcontract = tempcontract.Remove(tempcontract.Length - 1); if (letter == '/') { break; } name = name.Insert(0, letter.ToString()); } worksheet.Cells[i, 1] = name.Trim(' '); // legal worksheet.Cells[i, 4] = tempcontract.Trim(' '); } else { worksheet.Cells[i, 4] = contract.Substring(0, contract.IndexOf("(")).Trim(' '); worksheet.Cells[i, 1] = contract.Substring(0, contract.IndexOf("(")).Trim(' '); } i++; } } catch (Exception ex) { Log.Error(ex, "Error Setting up or leaving Excel."); return; } eApp.Visible = true; #endregion #if !DEBUG #region Move emails foreach (Outlook.MailItem msg in messages) { msg.Move(contractsDestFolder); msg.UnRead = false; } #endregion #endif #region Global // Release Outlook try { oNameSpace.Logoff(); oApp.Quit(); messages = null; items = null; contractsDestFolder = null; contractsSourceFolder = null; oNameSpace = null; oApp = null; } catch { } // Release Excel try { eApp.Quit(); worksheet = null; workbook = null; eApp = null; } catch { } Settings.Default.EmailAddress = EmailAddressTextBox.Text; Settings.Default.SourceFolder = SourceFolderTextBox.Text; Settings.Default.DestFolder = DestFolderTextBox.Text; Settings.Default.Save(); #endregion } catch (Exception ex) { Log.Error(ex, "Error thrown to higher level to avoid crashing."); } }
private void button1_Click(object sender, EventArgs e) { // Create the Outlook application. // in-line initialization Outlook.Application oApp = new Outlook.Application(); // Get the MAPI namespace. Outlook.NameSpace oNS = oApp.GetNamespace("mapi"); // Log on by using the default profile or existing session (no dialog box). oNS.Logon(Missing.Value, Missing.Value, false, true); // Alternate logon method that uses a specific profile name. // TODO: If you use this logon method, specify the correct profile name // and comment the previous Logon line. //oNS.Logon("profilename",Missing.Value,false,true); //Get the Inbox folder. Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); //Get the Items collection in the Inbox folder. Outlook.Items oItems = oInbox.Items; // Get the first message. // Because the Items folder may contain different item types, // use explicit typecasting with the assignment. Outlook.MailItem oMsg = (Outlook.MailItem)oItems.GetFirst(); //Output some common properties. textBox1.Text = (oMsg.Subject); textBox1.Text += textBox1.Text + oMsg.SenderName; textBox1.Text += textBox1.Text + oMsg.ReceivedTime; textBox1.Text += textBox1.Text + oMsg.Body; //Check for attachments. int AttachCnt = oMsg.Attachments.Count; textBox1.Text += textBox1.Text + ("Attachments: " + AttachCnt.ToString()); //TO DO: If you use the Microsoft Outlook 11.0 Object Library, uncomment the following lines. if (AttachCnt > 0) { for (int i = 1; i <= AttachCnt; i++) { textBox1.Text += textBox1.Text + (i.ToString() + "-" + oMsg.Attachments[i].DisplayName); } } //Display the message. oMsg.Display(false); //modal //Log off. oNS.Logoff(); //Explicitly release objects. oMsg = null; oItems = null; oInbox = null; oNS = null; oApp = null; }
public static int SaveMailAttach(string folder_path, Outlook.OlDefaultFolders opt) { try { // Create the Outlook application. // in-line initialization Outlook.Application oApp = new Outlook.Application(); // Get the MAPI namespace. Outlook.NameSpace oNS = oApp.GetNamespace("mapi"); // Log on by using the default profile or existing session (no dialog box). oNS.Logon(Missing.Value, Missing.Value, false, true); // Alternate logon method that uses a specific profile name. // TODO: If you use this logon method, specify the correct profile name // and comment the previous Logon line. //oNS.Logon("profilename",Missing.Value,false,true); //Get the Inbox folder. Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(opt); //Get the Items collection in the Inbox folder. Outlook.Items oItems = oInbox.Items; foreach (var item in oItems) { Outlook.MailItem msg = item as Outlook.MailItem; if (msg == null) { continue; } for (int i = 1; i <= msg .Attachments.Count; i++) { try { msg.Attachments[i].SaveAsFile (folder_path + msg.Attachments[i].FileName); } //Error handler. catch (Exception e) { Console.WriteLine("{0} Exception caught: ", e); } } } oNS.Logoff(); oItems = null; oInbox = null; oNS = null; oApp = null; } //Error handler. catch (Exception e) { Console.WriteLine("{0} Exception caught: ", e); } return(0); }
static void Main(string[] args) { //Outlook.Application application; // Outlook._NameSpace nameSpace; Outlook.MAPIFolder folderInbox; ////////////////////////////////// //Microsoft.Office.Interop.Outlook._Folders oFolders; ///////////////1 модуль отправки файлов/////////////////// string[] dirs; dirs = Directory.GetFiles(@"C:\tkM\OUT"); //дирректория - откуда берём файл String dirs1 = Directory.GetFiles(@"C:\tkM\OUT").Length.ToString(); //если в папке out что то есть то отправляем письмо for (int i = 0; i <= dirs.Length + 1; i++) //для отправки 1 письмо + 1 файл { if (Convert.ToInt32(dirs1) > 0) { //string dirArch = "C://OUT//ARCH//"; try { //тело отправляемого сообщения Outlook._Application _app = new Outlook.Application(); Outlook.MailItem mail = (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem); mail.To = "*****@*****.**"; //"*****@*****.**"; mail.Subject = "test1567"; // тема mail.Body = "This is test message1156711"; //текст письма mail.Importance = Outlook.OlImportance.olImportanceNormal; //какае то нужная вещь foreach (string s in dirs) { try { Console.WriteLine(s); mail.Attachments.Add(s); //добавляем вложения в письмо - возможно добавить сразу все вложения File.Move(s, s.Replace("OUT", "OUTaRCH")); //После успешного прикрепления файла, переносим их в папку C:\ARCH ((Outlook._MailItem)mail).Send(); //отправляем письмо Console.WriteLine("Файл отправлен в ТК"); // если все хорошо, то выдаём в консоль сообщение break; // выхожу из цикла, что бы реализовать фичу 1 фал = 1 письмо, и так сойдёт :) рефакторинг потом } catch (System.Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine("С таким именем файла уже отправлялось\n" + "Перемещаю файл в папку Bad"); FileM.MoveReplaceFile(s, s.Replace("OUT", "Bad")); //прописываю каталог C:\tkM\Bad так быстрее не люблю много переменных System.Threading.Thread.Sleep(1000); //спим 1000 мс что б увидеть работу кода Console.ReadKey(); } } _app = null; //убиваем ссылки на экземпляр класса mail = null; //Console.Read(); } catch { Console.WriteLine("Что то пошло не так"); // если какае то бага то пишем это сообщение Console.WriteLine("Не удалось отправить файлы, переходим к приёму файлов нажми любую клавишу"); System.Threading.Thread.Sleep(1000); goto importStart; //если модуль отправки не отработал то программа переходит к модулю чтения сообщений } ////////////////////////////Чтение сообщений и копирование вложений/////////////////////////////////////////// } else { Console.WriteLine("Файлов для отправки нет"); break; } //если нет файлов во вложении то выходим из цикла Console.ReadKey(); dirs = Directory.GetFiles(@"C:\tkM\OUT"); //присваивание переменной с каждой итерацией цикла для обновления данных в массиве System.Threading.Thread.Sleep(1000); } importStart: Outlook.Application oApp = new Outlook.Application(); // создали новый экземпляр Outlook.NameSpace oNS = oApp.GetNamespace("MAPI"); //Это кусорк для чтения входящих сообщений для теста и понимания как это работает(раюотаем из папки входящие) oNS.Logon(Missing.Value, Missing.Value, false, true); Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); for (int x = 1; x <= oInbox.Items.Count; x++) { if (oInbox.Items[x] is MailItem) { //Выводим Имя отправителя Console.WriteLine(oInbox.Items[x].SenderName + "\n" + "--------------------------------------------" + "\n"); } } nameSpace = oApp.GetNamespace("MAPI"); object missingValue = System.Reflection.Missing.Value; folderInbox = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); //Outlook.OlDefaultFolders.olFolderInbox //количество не прочитанных писем в папке Входящие (Inbox) Outlook.MAPIFolder rootFolder = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); //получаем доступ к папке входящие Outlook.MAPIFolder processedFolder = null; //processedFolder это экземпляр класса который выбирает нужную папку foreach (Outlook.MAPIFolder folder in rootFolder.Folders) // ищем циклом папку в OUTLOOK { if (folder.Name == "IN") //берем из папки IN { processedFolder = folder; // выбираю папку с которой будем работать(в OUTLOOK нужно создать правило, что бы все вообщения от почты ТК переносились в папку IN, которую мы заранее создаём в OUTLOOK) break; } } Outlook.Items unreadItems = processedFolder.Items.Restrict("[Unread]=true"); // работаем с данной папкой и ищем не прочитанные письма Console.WriteLine("Непрочитанных писем в папке in = " + unreadItems.Count.ToString()); // выдать в консоль колличество непрочитанных сообщений //////////здесь вываодим в консоль все данные непрочитанные письма в папке in можно заккоментить///////////////////////// StringBuilder str = new StringBuilder(); //читаем текст и данные письма выыодим в консоль не обязательно, но можно оставить для логирования try { DateTime sysdate_ = DateTime.Now; foreach (Outlook.MailItem mailItem in unreadItems) { str.AppendLine("----------------------------------------------------"); str.AppendLine("SenderName: " + mailItem.SenderName); str.AppendLine("To: " + mailItem.To); str.AppendLine("CC: " + mailItem.CC); str.AppendLine("Subject: " + mailItem.Subject); str.AppendLine("Body: " + mailItem.Body); str.AppendLine("CreationTime: " + mailItem.CreationTime); str.AppendLine("ReceivedByName: " + mailItem.ReceivedByName); str.AppendLine("ReceivedTime: " + mailItem.ReceivedTime); str.AppendLine("UnRead: " + mailItem.UnRead); str.AppendLine(mailItem.ReceivedTime.Date.ToShortDateString() + sysdate_.ToShortDateString()); str.AppendLine("----------------------------------------------------"); Console.WriteLine(str.ToString()); } } catch (System.Exception ex) // если письмо бракованное то пробуем ещё раз { //System.Threading.Thread.Sleep(300); //пауза //goto repeatReadMail; string errorInfo = (string)ex.Message.Substring(0, 11); Console.WriteLine(errorInfo); // вывести любую ошибку if (errorInfo == "Cannot save") { Console.WriteLine(@"Create Folder C:\TestFileSave"); } goto repeatReadAndAddAttachmentIsMail; // перейти к чтению и вытаскиванию вложения в случае ошибки здесь } //foreach (Outlook.MailItem mail in unreadItems) //пометить как прочитанное реализация не удалять //{ // if (mail.UnRead) // { // mail.UnRead = false; // mail.Save(); // } //} //////////////////Вытаскивание вложение и пометить письмо как прочитанное repeatReadAndAddAttachmentIsMail: Outlook.Items inBoxItems = processedFolder.Items.Restrict("[Unread]=true"); Outlook.MailItem newEmail = null; try { foreach (object collectionItem in inBoxItems) { newEmail = collectionItem as Outlook.MailItem; DateTime sysdate_ = DateTime.Now; //дата текущий день //mailItem.ReceivedTime.Date.ToShortDateString() + sysdate_.ToShortDateString(); if (newEmail != null && newEmail.ReceivedTime.Date.ToShortDateString() == sysdate_.ToShortDateString()) //проарка на дату файла { if (newEmail.Attachments.Count > 0) { for (int i = 1; i <= newEmail.Attachments.Count; i++) { string fileName = newEmail.Attachments[i].FileName; Console.WriteLine(@"Имя файла:" + fileName); string[] dirsINaRCH = Directory.GetFiles(@"C:\tkM\INaRCH\");//создадим перепенную с именами файлов в папке IN или IN_ARCH if (FileM.ValueOf(dirsINaRCH, fileName) != "noDuble") { Console.WriteLine(@"Найдено совпаление с файлом: " + fileName + "\n Список файлов в папке:"); for (int i1 = 0; i1 < dirsINaRCH.Length; i1++) { Console.Write(dirsINaRCH[i1] + " " + File.GetCreationTime(dirsINaRCH[i1]) + ";\n"); } } else { Console.WriteLine(@"нет совпадения файлов"); //Console.WriteLine(@"Имя файла:" + fileName); //for (int i1 = 0; i1 < dirsINaRCH.Length; i1++) //{ // Console.Write("Имя файлов(а) в папке:" + dirsINaRCH[i1]); //} newEmail.Attachments[i].SaveAsFile(@"C:\tkM\IN\" + newEmail.Attachments[i].FileName); Console.WriteLine(@"Файл сохранён с названием: " + newEmail.Attachments[i].FileName + " По пути:" + @"C:\tkM\IN\"); // выводим инфу об успешно копировании файла } // { Console.WriteLine(@"Обрабатываю письмо как прочитанное"); System.Threading.Thread.Sleep(1000); if (newEmail.UnRead) // пометить письмо как прочитанное { newEmail.UnRead = false; newEmail.Save(); } Console.WriteLine(@"Завершаю работу"); //} } } } else { Console.WriteLine("Нет писем с вложением"); } } } catch (System.Exception ex) { string errorInfo = (string)ex.Message .Substring(0, 11); Console.WriteLine(errorInfo); if (errorInfo == "Cannot save") { Console.WriteLine(@"Create Folder C:\IN"); } } //////////выход из приложения oNS.Logoff(); oInbox = null; oNS = null; oApp = null; //Console.ReadKey(); //Удалить все чтения ввода с консоли, для автоматической работы System.Threading.Thread.Sleep(1000); }
private void LoadIncEmail() { Log("Begin Load IncEmail from Local Machine"); var dict = new Dictionary <string, List <IncEmailItem> >(); var otherEmail = new Dictionary <string, List <IncEmailItem> >(); Func <string, IncEmailItem, List <string> > ExtractIncidentName = (s, i) => { s = s.Trim(); var matches1 = Regex.Matches(s, @"ICT_INC\d+"); var matches2 = Regex.Matches(s, @"ICT_WO\d+"); var matchesValues = matches1.Cast <Match>().Where(x => x.Success).Select(x => x.Value).Union(matches2.Cast <Match>().Where(x => x.Success).Select(x => x.Value)).ToList(); foreach (var matchItem in matchesValues) { if (!dict.ContainsKey(matchItem)) { dict.Add(matchItem, new List <IncEmailItem>()); } dict[matchItem].Add(i); } if (!matchesValues.Any()) { var upperTitle = s.ToUpper(); if (upperTitle.StartsWith("FW:") || upperTitle.StartsWith("RE:") || upperTitle.StartsWith("CT:")) { if (upperTitle.Length > 3) { s = s.Substring(3).Trim(); } } if (!otherEmail.ContainsKey(s)) { otherEmail.Add(s, new List <IncEmailItem>()); } otherEmail[s].Add(i); } return(matchesValues); }; oApp = new Microsoft.Office.Interop.Outlook.Application(); oNS = oApp.GetNamespace("mapi"); stores = oNS.Stores; var folders = settings.ScanFolders; foreach (Store store in stores) { // continue; Log("Read Store: " + store.DisplayName); MAPIFolder YOURFOLDERNAME = store.GetRootFolder(); Log("MAPIFolder: " + YOURFOLDERNAME.Name); foreach (MAPIFolder subF in YOURFOLDERNAME.Folders) { var f = subF.Name; Log("MAPIFolder: " + f + "#"); if (folders.Contains(f)) { ScanFolder(ExtractIncidentName, subF); } else { // Log("SKip read Mail in folder " + subF.Name); } } } Log("Proceed mail..."); foreach (var item in dict) { this.incEmails.Add(item.Key, item.Value.OrderByDescending(x => x.ReceivedTime).ToList()); } foreach (var item in otherEmail) { this.otherEmails.Add(item.Key, item.Value.OrderByDescending(x => x.ReceivedTime).ToList()); } Log("Log off outlook..."); //Log off. oNS.Logoff(); }