Filter out the rest with From Addresses, Avoid using Subject line to determine rules as Humans can tend to respond to automated emails and get filtered into the same folder.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices;
using System.Collections;

namespace EmailManager
{
    public partial class ThisAddIn
    {


        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            //this.Application.NewMail += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_NewMailEventHandler(_NewMail);
            this.Application.NewMailEx += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_NewMailExEventHandler(Application_NewMailEx);
            cycle();
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            // Note: Outlook no longer raises this event. If you have code that 
            //    must run when Outlook shuts down, see https://go.microsoft.com/fwlink/?LinkId=506785
        }

        ArrayList Humans = new ArrayList();
        ArrayList NonHumans = new ArrayList();
        object Item = null;
        Outlook._MailItem moveMail = null;
        Outlook.Items resultItems = null;

        private void Application_NewMailEx(string EntryIDCollection)
        {
            /*string senderEmailid = string.Empty;
            Outlook.NameSpace outlookNameSpace = this.Application.GetNamespace("MAPI");
            Outlook.Application myApp = new Outlook.Application();
            Outlook.NameSpace mapiNameSpace = myApp.GetNamespace("MAPI");
            Outlook.MAPIFolder myInbox = mapiNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
            Outlook.Attachments attachments;
            int test = myInbox.Items.Count;
            */
            object Item = Application.Session.GetItemFromID(EntryIDCollection, Type.Missing) as Outlook.MailItem;
            if (Item is Outlook._MailItem)
            {
                ProcessMailItem(Item as Outlook.MailItem);
            }
        }

        private void cycle()
        {
            Outlook.MAPIFolder inBox = (Outlook.MAPIFolder) this.Application.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

            Outlook.Items inboxitems = (Outlook.Items)inBox.Items;


            //sFilter = "[LastModificationTime] > '" & Format("1/15/99 3:30pm", "ddddd h:nn AMPM") & "'"
            //items.Restrict("[UnRead] = true");
            //Outlook.MAPIFolder destFolder = inBox.Folders ["Inbox"];
            //Outlook.MAPIFolder destFolder = this.Application.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
            string Restricting = "([LastModificationTime] > '" + DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd HH:mm") + "' or [ReceivedTime] > '" + DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd HH:mm") + "')";
            //string Restricting = "[UnRead] = true and ([LastModificationTime] > '" + DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd HH:mm") + "' or [ReceivedTime] > '" + DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd HH:mm") + "')";
            //string Restricting = "[UnRead] = true";
            resultItems = inboxitems.Restrict(Restricting);
            //Dictionary<string, string> SenderToAD = new Dictionary<string, string>();

            Item = resultItems.GetFirst();
            while (Item != null)
            {
                if (Item is Outlook._MailItem)
                {
                    ProcessMailItem(Item as Outlook.MailItem);
                }

                Marshal.ReleaseComObject(Item);
                Item = resultItems.GetNext();
            }
            /*
            foreach (object eMail in resultItems)
            {
                moveMail = eMail as Outlook.MailItem;
                try
                {
                    if (!(moveMail is null))
                    {
                        System.Diagnostics.Debug.WriteLine(moveMail.UnRead + " " + moveMail.ReceivedTime + " / " + moveMail.LastModificationTime + " - " + (string)moveMail.SenderEmailAddress + " " +  (string)moveMail.Subject);
                        //if (!(moveMail.ReceivedTime is null))
                        //{
                        if (moveMail.ReceivedTime > (DateTime.Now.AddDays(-2)))
                        {
                            if (!(moveMail.Subject is null))
                            {
                                if (moveMail.SenderEmailAddress.StartsWith("/O=EISENHOWER MEDICAL CENTER", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!(moveMail.Categories is null))
                                    {
                                        System.Diagnostics.Debug.WriteLine(moveMail.Categories);
                                    }
                                    if (moveMail.Categories != "Human")
                                    {
                                        moveMail.Categories = "Human";
                                        moveMail.Save();
                                    }
                                    //string titleSubject = (string)moveMail.Subject;
                                }
                            }
                        }
                        else
                        {
                            //return;
                        }
                        //}
                    }
                }
                catch (Exception ex)
                {
                    return;
                    MessageBox.Show(ex.Message);
                    if (ex.Message.StartsWith("Out of memory or system resources", StringComparison.OrdinalIgnoreCase))
                    {
                        Application.Quit();
                    }
                }
            }
            */
        }


        private void ProcessMailItem(Outlook.MailItem Item)
        {
            if (Item is Outlook._MailItem)
            {
                moveMail = Item as Outlook.MailItem;
                if (Humans.Contains(moveMail.SenderEmailAddress))
                {
                    if (moveMail.Categories != "Human")
                    {
                        moveMail.Categories = "Human";
                        moveMail.Save();
                    }
                    return;
                }

                if (NonHumans.Contains(moveMail.SenderEmailAddress))
                {
                    return;
                }

                Outlook.Recipient recipient = moveMail.Application.Session.CreateRecipient(moveMail.SenderEmailAddress);

                System.Diagnostics.Debug.WriteLine(moveMail.SenderEmailAddress + " " + (string) moveMail.Subject);
                if (recipient != null && recipient.Resolve() && recipient.AddressEntry != null)
                {
                    Outlook.ExchangeUser exUser = recipient.AddressEntry.GetExchangeUser();
                    if (exUser != null && !string.IsNullOrEmpty(exUser.Alias))
                    {
                        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
                        {
                            /*System.Diagnostics.Debug.WriteLine(exUser.Alias + " - " + exUser.Address);
                            if (exUser.Alias == "ssharpe")
                            {
                                System.Diagnostics.Debugger.Break();
                            }
                            */
                            UserPrincipal up = UserPrincipal.FindByIdentity(pc, exUser.Alias);
                            if (up != null)
                            {
                                DirectoryEntry directoryEntry = up.GetUnderlyingObject() as DirectoryEntry;
            System.Diagnostics.Debug.WriteLine(directoryEntry.Path);
                                if (directoryEntry.Properties.Contains("wWWHomePage"))
                                {
                                    //deliveryOffice = directoryEntry.Properties["wWWHomePage"].Value.ToString();
                                    //System.Diagnostics.Debug.WriteLine(moveMail.UnRead + " " + moveMail.ReceivedTime + " / " + moveMail.LastModificationTime + " - " + (string)moveMail.SenderEmailAddress + " " + (string)moveMail.Subject);
                                    if (moveMail.ReceivedTime > (DateTime.Now.AddDays(-2)))
                                    {
                                        if (!(moveMail.Subject is null))
                                        {
                                            if (moveMail.SenderEmailAddress.StartsWith("/O=EISENHOWER MEDICAL CENTER", StringComparison.OrdinalIgnoreCase))
                                            {
                                                Humans.Add(moveMail.SenderEmailAddress);

                                                if (moveMail.Categories != "Human")
                                                {
                                                    if (!(moveMail.Categories is null))
                                                    {
                                                        System.Diagnostics.Debug.WriteLine(moveMail.Categories);
                                                    }
                                                    moveMail.Categories = "Human";
                                                    moveMail.Save();
                                                }
                                                //string titleSubject = (string)moveMail.Subject;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    NonHumans.Add(moveMail.SenderEmailAddress);
                                    moveMail.Categories = "";
                                    moveMail.Save();
                                    System.Diagnostics.Debug.WriteLine("1");
                                }
                            }
                            else
                            {
                                NonHumans.Add(moveMail.SenderEmailAddress);
                                moveMail.Categories = "";
                                moveMail.Save();
                                System.Diagnostics.Debug.WriteLine("2");
                            }
                        }
                    }
                    else
                    {
                        NonHumans.Add(moveMail.SenderEmailAddress);
                        System.Diagnostics.Debug.WriteLine(moveMail.Subject);
                        moveMail.Categories = "";
                        moveMail.Save();
                        System.Diagnostics.Debug.WriteLine("3");
                    }
                }
                else
                {
                    NonHumans.Add(moveMail.SenderEmailAddress);
                    moveMail.Categories = "";
                    moveMail.Save();
                    System.Diagnostics.Debug.WriteLine("4");
                }
            }
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax