Example #1
0
        private void EnumerateConversation(System.Collections.Generic.Stack <MailItem> st, object item, Outlook.Conversation conversation)
        {
            Outlook.SimpleItems items =
                conversation.GetChildren(item);
            if (items.Count > 0)
            {
                foreach (object myItem in items)
                {
                    // In this example, enumerate only MailItem type.
                    // Other types such as PostItem or MeetingItem
                    // can appear in the conversation.
                    if (myItem is Outlook.MailItem)
                    {
                        Outlook.MailItem mailItem = myItem as Outlook.MailItem;
                        Outlook.Folder   inFolder = mailItem.Parent as Outlook.Folder;

                        string msg = mailItem.Subject + " in folder [" + inFolder.Name + "] EntryId [" + (mailItem.EntryID.ToString() ?? "NONE") + "]";
                        _logger.Debug(msg);
                        _logger.Debug(mailItem.Sender);
                        _logger.Debug(mailItem.ReceivedByEntryID);

                        if (mailItem.EntryID != null && (mailItem.Sender != null || mailItem.ReceivedByEntryID != null))
                        {
                            st.Push(mailItem);
                        }
                    }
                    // Continue recursion.
                    EnumerateConversation(st, myItem, conversation);
                }
            }
        }
Example #2
0
        private static bool IsMailItemOrAnyItsChildrenFlagged(Outlook.MailItem mailItem, Outlook.Conversation conv)
        {
            bool answer = false;

            if ((mailItem.FlagRequest != null) && (mailItem.FlagRequest != ""))
            {
                answer = true;
            }

            try {
                Outlook.SimpleItems items = conv.GetChildren(mailItem);
                if (items.Count > 0)
                {
                    foreach (object myItem in items)
                    {
                        if (myItem is Outlook.MailItem)
                        {
                            bool result = IsMailItemOrAnyItsChildrenFlagged(myItem as Outlook.MailItem, conv);
                            if (result == true)
                            {
                                answer = true;
                            }
                        }
                    }
                }
            } catch (System.Runtime.InteropServices.COMException ex) {
                Debug.Print(ex.ToString());
            }

            ClearMailItemFlagIfItsInSentItemFolder(mailItem);
            return(answer);
        }
Example #3
0
        private static bool IsMailItemHasFlaggedPreviousMail(Outlook.MailItem mailItem)
        {
            bool answer = false;

            if (mailItem is Outlook.MailItem)
            {
                Outlook.Folder folder = mailItem.Parent as Outlook.Folder;
                Debug.Assert(folder != null);
                Outlook.Store store = folder.Store;

                if ((store != null) && (store.IsConversationEnabled == true))
                {
                    Outlook.Conversation conv = mailItem.GetConversation();
                    if (conv != null)
                    {
                        Outlook.SimpleItems simpleItems = conv.GetRootItems();
                        foreach (object item in simpleItems)
                        {
                            if (item is Outlook.MailItem)
                            {
                                bool result = IsMailItemOrAnyItsChildrenFlagged(item as Outlook.MailItem, conv);
                                if (result == true)
                                {
                                    answer = true;
                                }
                            }
                        }
                    }
                }
            }

            return(answer);
        }
Example #4
0
        private void EnumerateConversation(object item, Outlook.Conversation conversation, Outlook.MailItem filter, ref Dictionary <string, Outlook.MailItem> mailsFound)
        {
            Outlook.SimpleItems items = conversation.GetChildren(item);
            if (items.Count > 0)
            {
                foreach (object myItem in items)
                {
                    //  enumerate only MailItem type.
                    if (myItem is Outlook.MailItem)
                    {
                        Outlook.MailItem m        = myItem as Outlook.MailItem;
                        Outlook.Folder   inFolder = m.Parent as Outlook.Folder;
                        string           msg      = m.Subject + " in folder " + inFolder.Name;

                        Debug.WriteLine(msg);

                        if (!mailsFound.ContainsKey(m.EntryID) && MailItemEquals(m, filter) && inFolder != deletedMailsFolder)
                        {
                            mailsFound.Add(m.EntryID, m);
                        }
                    }
                    // Continue recursion.
                    EnumerateConversation(myItem, conversation, filter, ref mailsFound);
                }
            }
        }
Example #5
0
        private string getConversationCategories(Outlook.MailItem mail)
        {
            string convCats = "";

            Outlook.Conversation conv = mail.GetConversation();
            if (conv == null)
            {
                return("");
            }

            Outlook.SimpleItems simpleItems = conv.GetRootItems();
            foreach (object item in simpleItems)
            {
                if (item is Outlook.MailItem)
                {
                    Outlook.MailItem smail = item as Outlook.MailItem;
                    if (smail.Categories == null)
                    {
                        continue;
                    }
                    string[] scats = smail.Categories.Split(ThisAddIn.CATEGORY_SEPERATOR[0]);
                    foreach (string scat in scats)
                    {
                        string tscat = scat.Trim();
                        if (!tscat.StartsWith("!") && !tscat.StartsWith("@") && !tscat.StartsWith("#"))
                        {
                            convCats += ThisAddIn.CATEGORY_SEPERATOR + tscat;
                        }
                    }
                }
            }

            return(convCats);
        }
Example #6
0
 static void EnumerateConversation(object item, Outlook.Conversation conversation)
 {
     Outlook.SimpleItems items = conversation.GetChildren(item);
     if (items.Count > 0)
     {
         foreach (object myItem in items)
         {
             // In this example, enumerate only MailItem type.
             // Other types such as PostItem or MeetingItem
             // can appear in Conversation.
             if (myItem is Outlook.MailItem)
             {
                 Outlook.MailItem mailItem =
                     myItem as Outlook.MailItem;
                 Outlook.Folder inFolder =
                     mailItem.Parent as Outlook.Folder;
                 string msg = mailItem.Subject
                              + " in folder " + inFolder.Name;
                 Debug.WriteLine(msg);
             }
             // Continue recursion.
             EnumerateConversation(myItem, conversation);
         }
     }
 }
Example #7
0
        private void updateEntireConversation(Outlook.MailItem mail)
        {
            string persTags = getPersistantCategories(mail.Categories);

            Outlook.Conversation conv = mail.GetConversation();
            if (conv == null)
            {
                return;
            }

            Outlook.SimpleItems simpleItems = conv.GetRootItems();
            foreach (object item in simpleItems)
            {
                if (item is Outlook.MailItem smail)
                {
                    string cats = persTags;
                    cats            += getSenderCategory(smail.SenderName);
                    cats            += getAttachmentCategories(mail.Attachments);
                    smail.Categories = getUniqueTags(cats);
                    smail.Save();
                }

                Outlook.SimpleItems OlChildren = conv.GetChildren(item);
                foreach (object rci in OlChildren)
                {
                    if (rci is Outlook.MailItem icr)
                    {
                        string cats = persTags;
                        cats          += getSenderCategory(icr.SenderName);
                        cats          += getAttachmentCategories(mail.Attachments);
                        icr.Categories = getUniqueTags(cats);
                        icr.Save();
                    }
                }
            }
        }
Example #8
0
        private void GetAttachmentsFromConversation(MailItem mailItem)
        {
            if (mailItem == null)
            {
                return;
            }

            if (mailItem.Attachments.CountNonEmbeddedAttachments() > 0)
            {
                return;
            }

            System.Collections.Generic.Stack <MailItem> st = new System.Collections.Generic.Stack <MailItem>();

            // Determine the store of the mail item.
            Outlook.Folder folder = mailItem.Parent as Outlook.Folder;
            Outlook.Store  store  = folder.Store;
            if (store.IsConversationEnabled == true)
            {
                // Obtain a Conversation object.
                Outlook.Conversation conv = mailItem.GetConversation();
                // Check for null Conversation.
                if (conv != null)
                {
                    // Obtain Table that contains rows
                    // for each item in the conversation.
                    Outlook.Table table = conv.GetTable();
                    _logger.Debug("Conversation Items Count: " + table.GetRowCount().ToString());
                    _logger.Debug("Conversation Items from Root:");

                    // Obtain root items and enumerate the conversation.
                    Outlook.SimpleItems simpleItems = conv.GetRootItems();
                    foreach (object item in simpleItems)
                    {
                        // In this example, enumerate only MailItem type.
                        // Other types such as PostItem or MeetingItem
                        // can appear in the conversation.
                        if (item is Outlook.MailItem)
                        {
                            Outlook.MailItem mail     = item as Outlook.MailItem;
                            Outlook.Folder   inFolder = mail.Parent as Outlook.Folder;
                            string           msg      = mail.Subject + " in folder [" + inFolder.Name + "] EntryId [" + (mail.EntryID.ToString() ?? "NONE") + "]";
                            _logger.Debug(msg);
                            _logger.Debug(mail.Sender);
                            _logger.Debug(mail.ReceivedByEntryID);

                            if (mail.EntryID != null && (mail.Sender != null || mail.ReceivedByEntryID != null))
                            {
                                st.Push(mail);
                            }
                        }
                        // Call EnumerateConversation
                        // to access child nodes of root items.
                        EnumerateConversation(st, item, conv);
                    }
                }
            }

            while (st.Count > 0)
            {
                MailItem it = st.Pop();

                if (it.Attachments.CountNonEmbeddedAttachments() > 0)
                {
                    //_logger.Debug(it.Attachments.CountNonEmbeddedAttachments());

                    try
                    {
                        if (mailItem.IsMailItemSignedOrEncrypted())
                        {
                            if (MessageBox.Show(null, "Es handelt sich um eine signierte Nachricht. Soll diese für die Anhänge ohne Zertifikat dupliziert werden?", "Nachricht duplizieren?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                mailItem.Close(OlInspectorClose.olDiscard);
                                mailItem = mailItem.Copy();
                                mailItem.Unsign();
                                mailItem.Save();
                                mailItem.Close(OlInspectorClose.olDiscard);
                                mailItem.Save();
                            }
                            else
                            {
                                st.Clear();
                                break;
                            }
                        }

                        mailItem.CopyAttachmentsFrom(it);
                        mailItem.Save();
                    }
                    catch (System.Exception ex)
                    {
                        //mailItem.Close(OlInspectorClose.olDiscard);
                        MessageBox.Show(ex.Message);
                    }

                    st.Clear();
                }
            }
            st.Clear();

            Marshal.ReleaseComObject(mailItem);
        }
Example #9
0
        /// <summary>
        /// Function searches for email duplicates from a specific email
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        private IEnumerable <Outlook.MailItem> search(Outlook.MailItem filter)
        {
            if (filter.Parent == deletedMailsFolder)
            {
                yield break;
            }

            Dictionary <string, Outlook.MailItem> mailsFound = new Dictionary <string, Outlook.MailItem>()
            {
                { filter.EntryID, filter }
            };

            // Obtain a Conversation object.
            Outlook.Conversation conv = filter.GetConversation();

            // Obtain Table that contains rows
            // for each item in Conversation.
            Outlook.Table table = conv.GetTable();

            //break if there just one
            if (table.GetRowCount() == 1)
            {
                yield break;
            }

            Debug.WriteLine("Conversation Items Count: " + table.GetRowCount().ToString());

            // Obtain root items and enumerate Conversation.
            Outlook.SimpleItems simpleItems = conv.GetRootItems();
            foreach (object item in simpleItems)
            {
                // enumerate only MailItem type.
                if (item is Outlook.MailItem)
                {
                    Outlook.MailItem m        = item as Outlook.MailItem;
                    Outlook.Folder   inFolder = m.Parent as Outlook.Folder;
                    string           msg      = m.Subject + " in folder " + inFolder.Name;

                    Debug.WriteLine(msg);

                    if (!mailsFound.ContainsKey(m.EntryID) && MailItemEquals(m, filter) && inFolder != deletedMailsFolder)
                    {
                        mailsFound.Add(m.EntryID, m);
                    }
                }
                // Call EnumerateConversation
                // to access child nodes of root items.
                EnumerateConversation(item, conv, filter, ref mailsFound);
            }

            if (mailsFound.Count > 1)
            {
                //delete duplicates //O(((n-1)n)/2)
                var mf = mailsFound.ToArray();
                for (int i = 0; i < mf.Length - 1; i++)
                {
                    for (int j = i + 1; j < mf.Length; j++)
                    {
                        if (app.Session.CompareEntryIDs(mf[i].Key, mf[j].Key))
                        {
                            mailsFound.Remove(mf[j].Key);
                        }
                    }
                }

                List <Outlook.MailItem> mGelesen      = new List <Outlook.MailItem>(); //List for readed emails
                List <Outlook.MailItem> mNichtGelesen = new List <Outlook.MailItem>(); //List for unreaded
                foreach (Outlook.MailItem m in mailsFound.Values)
                {
                    if (m.UnRead)
                    {
                        mNichtGelesen.Add(m);
                    }
                    else
                    {
                        mGelesen.Add(m);
                    }
                }
                if (mGelesen.Count > 0) // if there are readed emails, move the new unreaded to trash
                {
                    foreach (Outlook.MailItem m in mNichtGelesen)
                    {
                        m.Move(deletedMailsFolder); //move to deleted folder
                        yield return(m);
                    }
                }
                else
                {                                                 //no email were already readed
                    bool first = false;
                    foreach (Outlook.MailItem m in mNichtGelesen) //delete just n-1
                    {
                        if (first)
                        {
                            m.Move(deletedMailsFolder); //move to deleted folder
                        }
                        yield return(m);

                        first = true;
                    }
                }
                //clear readed mails too
                bool first2 = false;
                foreach (Outlook.MailItem m in mGelesen) //delete just n-1
                {
                    if (first2)
                    {
                        m.Move(deletedMailsFolder); //move to deleted folder
                    }
                    yield return(m);

                    first2 = true;
                }
            }
        }
Example #10
0
        public IEnumerable <Outlook.MailItem> GetSelectedMailItems()
        {
            if (inspector != null)
            {
                if (inspector.CurrentItem is Outlook.MailItem)
                {
                    yield return(inspector.CurrentItem as Outlook.MailItem);
                }
            }
            else // (explorer != null)
            {
                Outlook.Selection headers = null;
                try
                {
                    headers = explorer.Selection.GetSelection(Outlook.OlSelectionContents.olConversationHeaders);
                }
                catch (COMException err)
                {
                    // ^ failed once when moving only part of the message.
                    Logger.Error(err, "Error with GetSelection().");
                }


                if (headers != null && headers.Count > 0)
                {
                    // If they are in conversation view, need to iterate through the conversations in case they have the header selected. Only returns items in the current folder which is what we want.
                    foreach (Outlook.ConversationHeader header in headers)
                    {
                        // System.Runtime.InteropServices.COMException
                        // Message = The operation failed.
                        // after ?moving? a conversation and definitely after ?deleting? a conversation.
                        Outlook.SimpleItems items = null;
                        try
                        {
                            items = header.GetItems();
                        }
                        catch (COMException err)
                        {
                            // Seen after move sometimes
                            Logger.Error(err, "COMException in header.GetItems().");
                            continue;
                        }
                        for (int i = 1; i <= items.Count; i++)
                        {
                            // Enumerate only MailItems in this example.
                            if (items[i] is Outlook.MailItem)
                            {
                                yield return(items[i] as Outlook.MailItem);
                            }
                        }
                    }
                }
                else
                {
                    // If we are not in conversation view, process selection directly
                    Outlook.Selection selection = null;
                    try
                    {
                        selection = explorer.Selection;
                    }
                    catch (COMException err)
                    {
                        Logger.Error(err, "ComException in explorer.Selection.");
                    }
                    if (selection != null)
                    {
                        for (int i = 1; i <= selection.Count; i++)
                        {
                            var selectionItem = selection[i];
                            if (selectionItem is Outlook.MailItem)
                            {
                                yield return(selectionItem as Outlook.MailItem);
                            }
                        }
                    }
                }
            }
        }
Example #11
0
        internal async Task GuessBestFolder(bool yieldPeriodically = false)
        {
            if (Globals.ThisAddIn.foldersCollection == null)
            {
                // Plugin is still initializing.
                return;
            }

            // Which folder contains the most messages from the conversation?
            Dictionary <String, Tuple <Outlook.Folder, int> > folderVotes = new Dictionary <String, Tuple <Outlook.Folder, int> >();

            void processItem(Outlook.MailItem mailItem)
            {
                Outlook.Conversation conv        = null;
                Outlook.SimpleItems  simpleItems = null;
                try
                {
                    conv = mailItem.GetConversation();
                    if (conv != null)
                    {
                        simpleItems = conv.GetRootItems();
                    }
                }
                catch (COMException)
                {
                    // GetConversation is supposed to return null if there is no converstaion but actually throws and exception.
                    // GetRootItems throws an error for come conversations that have meeting invitations.
                }

                if (simpleItems != null)
                {
                    // Obtain root items and enumerate the conversation.
                    EnumerateConversation(simpleItems, conv);
                }
            }

            void EnumerateConversation(Outlook.SimpleItems items, Outlook.Conversation conversation)
            {
                if (items.Count > 0)
                {
                    foreach (object myItem in items)
                    {
                        if (myItem is Outlook.MailItem)
                        {
                            Outlook.MailItem mailItem = myItem as Outlook.MailItem;
                            Outlook.Folder   inFolder = mailItem.Parent as Outlook.Folder;

                            if (!folderVotes.TryGetValue(inFolder.EntryID, out Tuple <Outlook.Folder, int> value))
                            {
                                value = new Tuple <Outlook.Folder, int>(inFolder, 0);
                            }
                            folderVotes[inFolder.EntryID] = new Tuple <Outlook.Folder, int>(inFolder, value.Item2 + 1);
                        }
                        // Continue recursion.
                        Outlook.SimpleItems children;
                        try
                        {
                            children = conversation.GetChildren(myItem);
                        }
                        catch (COMException err)
                        {
                            var subject = myItem is Outlook.MailItem ? (myItem as Outlook.MailItem).Subject : "<Unknown item>";
                            Logger.Error(err, "Unable to get conversation children for subject {subject}", subject);
                            // I see this with Drafts, meeting invites, and other times.
                            continue;
                        }
                        EnumerateConversation(children, conversation);
                    }
                }
            }

            foreach (Outlook.MailItem mailItem in GetSelectedMailItems())
            {
                processItem(mailItem);
                if (yieldPeriodically)
                {
                    await Dispatcher.Yield(DispatcherPriority.Background);

                    if (guessBestFolderQueued)
                    {
                        return;
                    }
                }
            }

            // Remove distracting folders from consideration.
            var folderBlacklist = new List <Outlook.Folder>(await Globals.ThisAddIn.GetDefaultFoldersCachedAsync(false));

            if (explorer != null)
            {
                folderBlacklist.Add(explorer.CurrentFolder as Outlook.Folder);
            }
            else // inspector
            {
                if (inspector.CurrentItem is Outlook.MailItem)
                {
                    var mailItem = inspector.CurrentItem as Outlook.MailItem;
                    if (mailItem.Parent is Outlook.Folder)
                    {
                        folderBlacklist.Add(mailItem.Parent as Outlook.Folder);
                    }
                }
            }

            // Select best folder
            var sortedFolders = folderVotes.OrderBy(key => - key.Value.Item2);

            Outlook.Folder bestFolder = null;
            foreach (var v in sortedFolders)
            {
                Outlook.Folder folder = v.Value.Item1;
                if (folderBlacklist.FindIndex(f => f.EntryID == folder.EntryID) >= 0)
                {
                    // on blacklist
                    continue;
                }
                bestFolder = folder;
                break;
            }

            // Return folder wrapper
            FolderWrapper best = null;

            if (bestFolder != null)
            {
                try
                {
                    best = Globals.ThisAddIn.foldersCollection.Single(fw => fw.folder.EntryID == bestFolder.EntryID);
                }
                catch (InvalidOperationException err)
                {
                    Logger.Error(err, "Unable to find folder {folderName}.", bestFolder.Name);
                }
            }

            UpdateBestFolderWrapper(best);
        }