Exemple #1
0
        public string findLicenseMails()
        {
            StringBuilder sb = new StringBuilder();

            Microsoft.Office.Interop.Outlook._MailItem InboxMailItem = null;
            Microsoft.Office.Interop.Outlook.Items     oItems        = MyInbox.Items;
            string Query = "[Subject] contains 'Your license order'";

            //string filter = "urn:schemas:mailheader:subject LIKE '%" + wordInSubject + "%'";

            InboxMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oItems.Find(Query);
            while (InboxMailItem != null)
            {
                //ListViewItem myItem = lvwMails.Items.Add(InboxMailItem.SenderName);
                //myItem.SubItems.Add(InboxMailItem.Subject);
                sb.Append(InboxMailItem.SenderName + ": ");
                sb.Append(InboxMailItem.Subject + "\r\n");
                string AttachmentNames = string.Empty;
                foreach (Microsoft.Office.Interop.Outlook.Attachment item in InboxMailItem.Attachments)
                {
                    AttachmentNames += item.DisplayName;
                    sb.Append("\t" + item.DisplayName + "\r\n");
                    //item.SaveAsFile(this.GetAttachmentPath(item.FileName, "c:\\test\\attachments\\"));
                }
                //myItem.SubItems.Add(AttachmentNames);
                //InboxMailItem.Delete();
                InboxMailItem = (Microsoft.Office.Interop.Outlook._MailItem)oItems.FindNext();
            }
            return(sb.ToString());
        }
        private void ProcessMissedItems()
        {
            // We process all items in the folder that we've missed (e.g. Outlook was closed, or too many changes happened at once)
            // We do this by looking for any items that do not have our custom property set

            Outlook.Items missedItems = _watchedFolder.Items;

            // As we're filtering on a custom property that we haven't added to the folder, we need to add the
            // property type (0x0000001f) to the end of the property definition (otherwise, our filter won't work)
            string filter = String.Format("@SQL=NOT \"{0}/0x0000001f\" LIKE 'P-%'", _propItemProcessedDate);
            //AddLog("Filter: " + filter);
            object missedItem = missedItems.Find(filter);

            if (missedItem == null)
            {
                return;
            }

            ProcessItem(missedItem);
            while (missedItem != null)
            {
                missedItem = null;
                missedItem = missedItems.FindNext();
                if (missedItem != null)
                {
                    ProcessItem(missedItem);
                }
            }
        }
Exemple #3
0
        private void SearchInBox()
        {
            Outlook.MAPIFolder inbox = this.Application.ActiveExplorer().Session.
                                       GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

            MessageBox.Show(inbox.Folders.Count.ToString());

            foreach (Outlook.Folder item in inbox.Folders)
            {
                MessageBox.Show(item.Name);
            }

            Outlook.Items    items    = inbox.Items;
            Outlook.MailItem mailItem = null;
            object           folderItem;
            string           subjectName = string.Empty;
            string           filter      = "[Subject] > 's' And [Subject] <'u'";

            folderItem = items.Find(filter);
            while (folderItem != null)
            {
                mailItem = folderItem as Outlook.MailItem;
                if (mailItem != null)
                {
                    subjectName += "\n" + mailItem.Subject;
                }
                folderItem = items.FindNext();
            }
            subjectName = " The following e-mail messages were found: " +
                          subjectName;
            MessageBox.Show(subjectName);
        }
        /// <summary>
        /// Removes a specific event or a series of events
        /// </summary>
        /// <param name="objItems">Contains all the event items in a specific calendar/folder</param>
        /// <param name="subject">Subject of the event to delete</param>
        /// <param name="eventDate">If specified, this specific event is deleted instead of all events with subject</param>
        internal static void RemoveEvent(Outlook.Items objItems, string subject, string eventDate)
        {
            string methodTag = "RemoveEvent";

            LogWriter.WriteInfo(TAG, methodTag, "Starting: " + methodTag + " in " + TAG);

            Outlook.AppointmentItem agendaMeeting = null;

            if (eventDate == null)
            {
                objItems.Sort("[Subject]");
                objItems.IncludeRecurrences = true;

                LogWriter.WriteInfo(TAG, methodTag, "Attempting to find event with subject: " + subject);
                agendaMeeting = objItems.Find("[Subject]=" + subject);

                if (agendaMeeting == null)
                {
                    LogWriter.WriteWarning(TAG, methodTag, "No event found with subject: " + subject);
                }
                else
                {
                    LogWriter.WriteInfo(TAG, methodTag, "Removing all events with subject: " + subject);
                    do
                    {
                        agendaMeeting.Delete();

                        agendaMeeting = objItems.FindNext();

                        LogWriter.WriteInfo(TAG, methodTag, "Event found and deleted, finding next");
                    } while (agendaMeeting != null);

                    LogWriter.WriteInfo(TAG, methodTag, "All events with subject: " + subject + " found and deleted");
                }
            }
            else
            {
                LogWriter.WriteInfo(TAG, methodTag, "Finding event with subject" + subject + " and date: " + eventDate);
                agendaMeeting = objItems.Find("[Subject]=" + subject);

                if (agendaMeeting == null)
                {
                    LogWriter.WriteWarning(TAG, methodTag, "No event found with subject: " + subject);
                }
                else
                {
                    Outlook.RecurrencePattern recurrPatt = agendaMeeting.GetRecurrencePattern();
                    agendaMeeting = recurrPatt.GetOccurrence(DateTime.Parse(eventDate));

                    agendaMeeting.Delete();

                    LogWriter.WriteInfo(TAG, methodTag, "Event found and deleted");
                }
            }
        }
        private static List <EmailParsingData> GetDeliveryReportList(string filter)
        {
            try
            {
                var           mailBoxContent = new List <EmailParsingData>();
                Outlook.Items folderItems    = null;

                Outlook.MAPIFolder inboxFolder = null;
                foreach (dynamic folder in ThisAddIn.thisApplication.GetNamespace("MAPI").Folders)
                {
                    var subFolders = GpiOutlookWrapper.GetFolder(folder.FolderPath);
                    foreach (Outlook.MAPIFolder subFolder in subFolders.Folders)
                    {
                        if (subFolder.FullFolderPath.Contains("Уведомления о прочтении") &&
                            (subFolder.FullFolderPath.Contains("Канцелярия") || subFolder.FullFolderPath.Contains("kancelaria")))
                        {
                            inboxFolder = subFolder;
                        }
                    }

                    Marshal.ReleaseComObject(subFolders);
                }

                if (inboxFolder == null)
                {
                    return(mailBoxContent);
                }

                folderItems = inboxFolder.Items;
                folderItems.Sort("[CreationTime]", true);

                var item = folderItems.Find(filter);
                while (item != null)
                {
                    var parsingData = new EmailParsingData();
                    parsingData.Subject      = item.Subject;
                    parsingData.ItemClass    = item.MessageClass;
                    parsingData.CreationTime = item.CreationTime;
                    mailBoxContent.Add(parsingData);
                    Marshal.ReleaseComObject(item);
                    item = folderItems.FindNext();
                }

                return(mailBoxContent);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemple #6
0
        //####################################### TESTING ###########################################

        /*
         * public void getLicenseMails() //see http://blogs.msdn.com/b/philliphoff/archive/2008/03/03/filter-outlook-items-by-date-with-linq-to-dasl.aspx
         * {
         *  Microsoft.Office.Interop.Outlook.Folder folder = (Microsoft.Office.Interop.Outlook.Folder)MailNS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
         *
         *  string subject = sLicenseSubject;// "Your license order";
         *
         *  var results =
         *
         *          from item in folder.Items.AsQueryable<Microsoft.Office.Interop.Outlook.Extensions.Linq.Mail>()
         *
         *          where item.Subject.Contains(subject) && item.Attachments.Count>0 //item.CreationTime <= DateTime.Now - new TimeSpan(7, 0, 0, 0)
         *
         *          select item;
         *
         *  foreach (var result in results)
         *  {
         *      System.Diagnostics.Debug.WriteLine(String.Format("Body: {0}", result));
         *  }
         * }
         */

        private void SearchRecurringAppointments()
        {
            Microsoft.Office.Interop.Outlook.AppointmentItem appt   = null;
            Microsoft.Office.Interop.Outlook.Folder          folder = MailNS.GetDefaultFolder(OlDefaultFolders.olFolderInbox)
                                                                      //Microsoft.Office.Interop.Outlook.Application.Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar)
                                                                      as Microsoft.Office.Interop.Outlook.Folder;
            // Set start value
            DateTime start =
                new DateTime(2006, 8, 9, 0, 0, 0);
            // Set end value
            DateTime end =
                new DateTime(2006, 12, 14, 0, 0, 0);
            // Initial restriction is Jet query for date range
            string filter1 = "[Start] >= '" +
                             start.ToString("g")
                             + "' AND [End] <= '" +
                             end.ToString("g") + "'";

            Microsoft.Office.Interop.Outlook.Items calendarItems = folder.Items.Restrict(filter1);
            calendarItems.IncludeRecurrences = true;
            calendarItems.Sort("[Start]", Type.Missing);
            // Must use 'like' comparison for Find/FindNext
            string filter2;

            filter2 = "@SQL="
                      + "\"" + "urn:schemas:httpmail:subject" + "\""
                      + " like '%Office%'";
            // Create DASL query for additional Restrict method
            string filter3;

            if (MailNS.DefaultStore.IsInstantSearchEnabled)// Microsoft.Office.Interop.Outlook.Application.Session.DefaultStore.IsInstantSearchEnabled)
            {
                filter3 = "@SQL="
                          + "\"" + "urn:schemas:httpmail:subject" + "\""
                          + " ci_startswith 'Office'";
            }
            else
            {
                filter3 = "@SQL="
                          + "\"" + "urn:schemas:httpmail:subject" + "\""
                          + " like '%Office%'";
            }
            // Use Find and FindNext methods
            appt = calendarItems.Find(filter2)
                   as Microsoft.Office.Interop.Outlook.AppointmentItem;
            while (appt != null)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(appt.Subject);
                sb.AppendLine("Start: " + appt.Start);
                sb.AppendLine("End: " + appt.End);
                System.Diagnostics.Debug.WriteLine(sb.ToString());
                // Find the next appointment
                appt = calendarItems.FindNext()
                       as Microsoft.Office.Interop.Outlook.AppointmentItem;
            }
            // Restrict calendarItems with DASL query
            Microsoft.Office.Interop.Outlook.Items restrictedItems =
                calendarItems.Restrict(filter3);
            foreach (Microsoft.Office.Interop.Outlook.AppointmentItem apptItem in restrictedItems)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(apptItem.Subject);
                sb.AppendLine("Start: " + apptItem.Start);
                sb.AppendLine("End: " + apptItem.End);
                sb.AppendLine();
                System.Diagnostics.Debug.WriteLine(sb.ToString());
            }
        }
        public string GetOneMail(string EmailAddress, string Profile, string LogPath, string LogData, string FolderName, string EmailType, string AttachmentSavePath = "", string RetainOriginalAttName = "true", string EmailSavePath = "", string EmailExtension = "", string MarkAsRead = "", string MoveEmailToFolder = "")
        {
            string results = "";

            try
            {
                Outlook.Items    folderItems = null;
                Outlook.MailItem foundMail   = null;
                object           foundItem   = null;
                Connection       conn        = null;

                NameSpace      nameSpace    = null;
                string         log          = "";
                Outlook.Folder outboxFolder = null;

                Outlook.MAPIFolder oFolder;


                log  = "Creating new connection to Outlook";
                conn = new Connection();
                Outlook.Application application = conn.InitializeConnection(EmailAddress, Profile, out nameSpace, out outboxFolder, out oFolder);


                MAPIFolder subFolder = null;
                if (FolderName.ToLower() == "inbox")
                {
                    subFolder = oFolder;
                }
                else
                {
                    foreach (MAPIFolder folder in oFolder.Folders)
                    {
                        if (folder.Name == FolderName)
                        {
                            subFolder = folder;
                            break;
                        }
                    }
                }
                //Console.WriteLine(subFolder.UnReadItemCount.ToString() );
                log = "Connected to folder " + subFolder.Name;
                File.AppendAllText(LogPath, LogData + log + Environment.NewLine);

                if (subFolder.DefaultItemType == Outlook.OlItemType.olMailItem)
                {
                    folderItems = subFolder.Items;

                    //Creating filter for unread/read or all
                    if (EmailType.ToLower() == "unread")
                    {
                        foundItem = folderItems.Find("[Unread]=true");
                        //Console.WriteLine(subFolder.UnReadItemCount.ToString() );
                        log = "Obtaining only UNREAD emails. Total found: " + subFolder.UnReadItemCount.ToString();
                    }
                    else if (EmailType.ToLower() == "read")
                    {
                        foundItem = folderItems.Find("[Unread]=false");
                        log       = "Obtaining only READ emails";
                    }
                    else if (EmailType.ToLower() == "all")
                    {
                        foundItem = (Outlook.MailItem)subFolder.Items.GetFirst();
                        log       = "Obtaining ALL emails";
                    }
                    else
                    {
                        return("Incorrect filter. Allowed only: read/unread/all");
                    }

                    string SenderEmailAddress = "";

                    File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                    while (foundItem != null)
                    {
                        try
                        {
                            if (foundItem is Outlook.MailItem)
                            {
                                foundMail = foundItem as Outlook.MailItem;

                                if (foundMail.Sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry || foundMail.Sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
                                {
                                    Outlook.ExchangeUser exchUser = foundMail.Sender.GetExchangeUser();
                                    if (exchUser != null)
                                    {
                                        SenderEmailAddress = exchUser.PrimarySmtpAddress;
                                    }
                                }
                                else
                                {
                                    SenderEmailAddress = foundMail.SenderEmailAddress.ToString();
                                }

                                log = "Found email - Subject: " + foundMail.Subject + " From: " + foundMail.SenderEmailAddress.ToString() + " Received date: " + foundMail.ReceivedTime.ToString();
                                File.AppendAllText(LogPath, LogData + log + Environment.NewLine);

                                if (AttachmentSavePath != "")
                                {
                                    int fileID = 0;
                                    log = "Attachment saving requested";
                                    File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                                    foreach (Attachment attachment in foundMail.Attachments)
                                    {
                                        int strCID =
                                            (int)attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37140003");
                                        if (strCID != 0)
                                        {
                                            continue;
                                        }
                                        if (RetainOriginalAttName.ToLower() == "false")
                                        {
                                            fileID++;
                                            string extension = Path.GetExtension(attachment.FileName);
                                            log = "Saving: " + AttachmentSavePath + attachment.FileName;
                                            File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                                            attachment.SaveAsFile(AttachmentSavePath + fileID + extension);
                                        }
                                        else
                                        {
                                            log = "Saving: " + AttachmentSavePath + attachment.FileName;
                                            File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                                            attachment.SaveAsFile(AttachmentSavePath + attachment.FileName);
                                        }
                                    }
                                }

                                if (EmailSavePath != "")
                                {
                                    log = "Email saving requested";
                                    File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                                    Regex  rgx           = new Regex("[^a-zA-Z0-9 ]");
                                    string emailfilename = rgx.Replace(foundMail.Subject.ToString(), "");

                                    log = "Email name changed to: " + emailfilename;
                                    File.AppendAllText(LogPath, LogData + log + Environment.NewLine);

                                    if (EmailExtension != "")
                                    {
                                        if (EmailExtension.ToLower() == "mht")
                                        {
                                            foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension, OlSaveAsType.olMHTML);
                                        }
                                        else if (EmailExtension.ToLower() == "msg")
                                        {
                                            foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension, OlSaveAsType.olMSG);
                                        }
                                        else if (EmailExtension.ToLower() == "html")
                                        {
                                            foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension, OlSaveAsType.olHTML);
                                        }
                                        else if (EmailExtension.ToLower() == "txt")
                                        {
                                            foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension, OlSaveAsType.olTXT);
                                        }
                                        else if (EmailExtension.ToLower() == "rtd")
                                        {
                                            foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension, OlSaveAsType.olRTF);
                                        }
                                        //foundMail.SaveAs(EmailSavePath + emailfilename + "." + EmailExtension);

                                        log = "Saving email: " + EmailSavePath + emailfilename + "." + EmailExtension;
                                        File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                                    }
                                    else
                                    {
                                        log = "Saving email: " + EmailSavePath + emailfilename + ".msg";
                                        File.AppendAllText(LogPath, LogData + log + Environment.NewLine);
                                        foundMail.SaveAs(EmailSavePath + emailfilename + ".msg");
                                    }
                                }

                                if (MarkAsRead.ToLower() == "true")
                                {
                                    foundMail.UnRead = false;
                                    foundMail.Save();
                                }

                                if (MoveEmailToFolder != "")
                                {
                                    foreach (MAPIFolder folder in oFolder.Folders)
                                    {
                                        if (folder.Name == MoveEmailToFolder)
                                        {
                                            foundMail.Move(folder);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (foundItem != null)
                                {
                                    Marshal.ReleaseComObject(foundItem);
                                }
                                foundItem = folderItems.FindNext();
                                continue;
                            }
                            try
                            {
                                //results = SenderEmailAddress.ToString() + "|#|" + foundMail.Subject.ToString() + "|#|" + foundMail.ReceivedTime.ToString();
                                results = foundMail.SenderEmailAddress.ToString() + "|#|" + foundMail.Subject + "|#|" + foundMail.ReceivedTime.ToString();
                            }
                            catch (System.Exception)
                            {
                            }
                            if (foundItem != null)
                            {
                                Marshal.ReleaseComObject(foundItem);
                            }
                        }
                        catch (System.Exception)
                        {
                        }
                        //

                        //Console.WriteLine(foundItem.ToString());
                        break;
                    }
                }
                else
                {
                    foundItem = folderItems.FindNext();
                }

                if (results == "")
                {
                    return("No emails for processing");
                }

                return(results);
            }
            catch (System.Exception ex)
            {
                return("Failed: " + ex.ToString());
            }
        }
        /// <summary>
        /// Adds new appointment for the specified date range
        /// </summary>
        /// <param name="PobjItem"></param>
        private void getAppointments(ExtendedRecipient PobjRecipient,
                                     DateTime PobjDay,
                                     bool PbolMeetingsOnly,
                                     bool PbolExcludePrivate)
        {
            try
            {
                // Start filling in the rest...
                Outlook.MAPIFolder LobjFolder = null;
                try
                {
                    LobjFolder = Common.IsRecipientValid(PobjRecipient.InteropRecipient);
                    if (LobjFolder == null)
                    {
                        throw new Exception();
                    }
                }
                catch (Exception PobjEx)
                {
                    throw new Exception("Recipient calendar folder cannot be found. " +
                                        "This might be because you have not added them as a shared calendar. " +
                                        PobjEx.Message);
                }

                Outlook.Items LobjItems = LobjFolder.Items;
                if (LobjItems == null)
                {
                    throw new Exception("Unable to access recipient items. You may not have permission.");
                }

                try
                {
                    LobjItems.Sort("[Start]"); // sort the items
                }
                catch (Exception PobjEx)
                {
                    throw new Exception("Recipient calendar folder cannot be accessed or sorted. " +
                                        "This might be because you might not have permission. " +
                                        PobjEx.Message);
                }
                LobjItems.IncludeRecurrences = true; // be sure to include recurrences

                string LstrDay = PobjDay.ToShortDateString();
                // set the find string to today 0:00 to 23:59:59
                string LstrFind = "[Start] <= \"" + LstrDay + " 11:59 PM\"" +
                                  " AND [End] > \"" + LstrDay + " 12:00 AM\"";
                // find the first appointment for the day
                Outlook.AppointmentItem LobjAppt = LobjItems.Find(LstrFind);

                while (LobjAppt != null)
                {
                    if (LobjAppt.MeetingStatus == Outlook.OlMeetingStatus.olNonMeeting &&
                        PbolMeetingsOnly)
                    {
                        // skip - this is an appointment only
                        // and we are limiting to only meetings
                    }
                    else if (PbolExcludePrivate == true &&
                             LobjAppt.Sensitivity == Microsoft.Office.Interop.Outlook.OlSensitivity.olPrivate)
                    {
                        // skip - this is an private item
                        // and we are not includeing private items
                    }
                    else
                    {
                        ExtendedAppointment LobjNew = new ExtendedAppointment(LobjAppt, PobjRecipient);
                        if (!Appointments.Contains(LobjNew))
                        {
                            // now add the appointment
                            Appointments.Add(LobjNew);
                        }
                        else
                        {
                            Appointments.FindItem(LobjNew).AddRecipient(PobjRecipient);
                        }
                    }
                    // get the next item
                    LobjAppt = LobjItems.FindNext();
                }
            }
            catch (Exception PobjEx)
            {
                throw new Exception("Failed while processing " + PobjDay.ToLongDateString() + " for " +
                                    PobjRecipient.RecipientName + ". " + PobjEx.Message);
            }
        }
        /// <summary>
        /// The get mail box content.
        /// </summary>
        /// <param name="inboxFolder">
        /// The inbox folder.
        /// </param>
        /// <param name="filterParameters">
        /// The filter Parameters.
        /// </param>
        /// <param name="messageClass">
        /// The message Class.
        /// </param>
        /// <returns>
        /// The list of EmailParsingData.
        /// </returns>
        public static List <EmailParsingData> GetMailBoxContent(Outlook.MAPIFolder inboxFolder, FilterParametersData filterParameters, string messageClass = "IPM.Note")
        {
            var mailBoxContent = new List <EmailParsingData>();

            if (inboxFolder == null)
            {
                return(mailBoxContent);
            }

            Outlook.Items folderItems = null;

            var start = DateTime.MinValue;

            try
            {
                folderItems = inboxFolder.Items;
                folderItems.Sort("[CreationTime]", true);

                start = DateTime.Now;

                var deliveryReportFilter = GenerateFilter(filterParameters, "REPORT.IPM.Note.DR");

                var deliveryReportList = GetDeliveryReportList(deliveryReportFilter);

                var filter = GenerateFilter(filterParameters, messageClass);
                var item   = folderItems.Find(filter);
                while (item != null)
                {
                    if (!CheckSubjectFilter(filterParameters, item.Subject))
                    {
                        Marshal.ReleaseComObject(item);
                        item = folderItems.FindNext();
                        continue;
                    }

                    var parsingData = GetEmailParsingData(item);

                    if (parsingData.Subject.Contains(@"15292"))
                    {
                        var x = 0;
                    }

                    parsingData.Status = GetEmailStatusFromConversation(item, parsingData.CreationTime);
                    if (parsingData.Status == EmailStatus.Unknown)
                    {
                        parsingData.Status = GetEmailStatusFromSubject(item.Subject, deliveryReportList);
                    }

                    if (!CheckStatusFilter(filterParameters, parsingData.Status))
                    {
                        Marshal.ReleaseComObject(item);
                        item = folderItems.FindNext();
                        continue;
                    }

                    mailBoxContent.Add(parsingData);

                    Marshal.ReleaseComObject(item);
                    item = folderItems.FindNext();
                }
            }
            catch (Exception ex)
            {
                ErrorList.Add(MethodBase.GetCurrentMethod().Name + " " + ex.Message);
            }
            finally
            {
                if (folderItems != null)
                {
                    Marshal.ReleaseComObject(folderItems);
                }
            }

            var dyration = (DateTime.Now - start).TotalSeconds;

            return(mailBoxContent.OrderByDescending(c => c.CreationTime).ToList());
        }
        public void GetEmails()
        {
            //MessageBox.Show("In GetEmails");
            Outlook.MAPIFolder inbox          = null;
            Outlook.NameSpace  ns             = null;
            Outlook.Items      items          = null;
            Outlook.MailItem   mailItem       = null;
            string             subjectName    = string.Empty;
            DateTime           lastrunDate    = Convert.ToDateTime(File.ReadLines("log.txt").Last());
            string             subjectFilter  = "[Subject] = 'Cutler / (1) DEFICIT EXECUTIONS'";
            string             subjectFilter2 = "[Subject] = 'STOCK LOAN EXECUTION'";
            string             subjectFilter3 = "[Subject] = 'CUTLER/ (1) DEFICIT EXECUTIONS'";
            List <string>      subjectFilters = new List <string>();

            subjectFilters.Add(subjectFilter);
            subjectFilters.Add(subjectFilter2);
            subjectFilters.Add(subjectFilter3);

            try
            {
                if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
                {
                    //Check if Outlook is open.
                    //MessageBox.Show("Outlook Is Open");
                    Outlook.Application applic = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
                    inbox = applic.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                }
                else
                {
                    //Open Outlook if closed.
                    //MessageBox.Show("Outlook is Closed...Opening an instance of Outlook");
                    Outlook.Application app = new Outlook.Application();
                    ns    = app.GetNamespace("MAPI");
                    inbox = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                    ns    = null;
                }

                foreach (string subject in subjectFilters)
                {
                    object folderItem;
                    items      = inbox.Items;
                    folderItem = items.Find(subject);
                    //MessageBox.Show("Checking for Emails since " + lastrunDate + " with subject " + subject);

                    while (folderItem != null)
                    {
                        mailItem = folderItem as Outlook.MailItem;
                        //Check if email rcvd after last run date.
                        if (mailItem != null && Convert.ToDateTime(mailItem.ReceivedTime) > lastrunDate)
                        {
                            emails.Add(mailItem);
                            subjectName += "\n" + mailItem.Subject + mailItem.SenderEmailAddress + mailItem.SentOn;
                        }
                        folderItem = items.FindNext();
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("{0} Exception caught.", e.Message);
            }
            finally
            {
                if (items != null)
                {
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(items);
                }
                if (inbox != null)
                {
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(inbox);
                }
            }
            if (emails.Count == 0)
            {
                MessageBox.Show("No Emails Found");
                Environment.Exit(0);
            }
            else
            {
                MessageBox.Show("Found " + emails.Count + " Emails");
            }
            return;
        }