Tuesday, July 22, 2014

Exchange Server: EWS Managed API complex Filters

How to Add complex search filters to the search filter collection


I do not see Microsoft provided detailed enough documents for this,  I figured it out so i would like to share  here:




// mailbox_to_monitor is the param for the 
var mailbox_to_monitor = string.IsNullOrEmpty(ConfigurationManager.AppSettings["mailboxToMonitor"]) ? targetFilePath : ConfigurationManager.AppSettings["mailboxToMonitor"];

            
//The 1st filter tries to filter based on the mail body 
SearchFilter sf1 = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, DateTime.Now.AddDays(daysToRetrieve * -1)), new SearchFilter.ContainsSubstring(ItemSchema.Body, mailbox_to_monitor));

//The 2st filter tries to filter based on the mail sender
                SearchFilter sf2 = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, DateTime.Now.AddDays(daysToRetrieve * -1)), new SearchFilter.ContainsSubstring(EmailMessageSchema.Sender, mailbox_to_monitor));

////////////////////////////////////// // logical OR with filter 1 and filter 2
//This is the line to do the trick
                SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, sf1, sf2);


FindItemsResults<Item> findResults = service.FindItems(
                new FolderId(WellKnownFolderName.Inbox, new Mailbox(mailbox)),
                sf,
                new ItemView(200));


                var mailResults = findResults.OrderBy(t => t.DateTimeSent);


//Loop through the items and do whatever is required.
                string data = string.Empty;
                var emailMsgs = new List<string>();
                var hrefList = new List<string>();
                foreach (var i in mailResults)
                {

                    i.Load();
                    var msgBody = i.Body;
                    var msgText = msgBody.Text;

                    if (msgText.Contains("Value_You_Try_To_Look_At")) emailMsgs.Add(msgText.Trim());

                    data = String.Format("{0}{1} On: {2} – Subject: {3}", data, Environment.NewLine, i.DateTimeReceived.ToString(), i.Subject);


                }






No comments:

Post a Comment