Jaa


EWS - Csharp - List unread inbox messages using a restriction

// C# sample using Exchange Web Service Proxy classes to list unread messages in an inbox using a restriction.

 

 private void FindInFolder()
        {
 
            // TODO: Put this code into a winform and call from a button:
            // TODO: create 3 text boxes called txtRequest, txtResponse, txtItems
            // TODO: Set the properties for the three text boxes to multiline=true, Scrolling=Both and  Wrap=false.
            // TODO: Change the credentials below to match your server & mailbox

            //----------------- Setup basic credentials for test server ----
            //------------------
            //string sUserName = "administrator";     // TODO: Change
            //string sPassword = "MyPassword1";     // TODO: Change
            //string sDomain = "mydom";      // TODO: Change
            //string sAuthenticate = "Basic";    //"Windows, "Basic"    // TODO: Change
            //string sEWS_URL = "https://my2k7server.mydom.extest.microsoft.com/EWS/Services.wsdl";    // TODO:  Change
 
            //----------------- Setup windows credentials for live server ----
            //
            string sUserName = "";    // TODO: Change
            string sPassword = "";    // TODO: Change
            string sDomain = "";    // TODO: Change
            string sAuthenticate = "Windows";  //Windows, Basic    // TODO: Change
            string sEWS_URL = "https://myserver.microsoft.com/ews/exchange.asmx";    // TODO: Change
 

            // ------------------- Lets now bind to Exchange
            NetworkCredential nc = null;
            if (sAuthenticate == "Windows")
            {
                nc = System.Net.CredentialCache.DefaultNetworkCredentials;
            }
            else
            {
                nc = new NetworkCredential(sUserName, sPassword, sDomain);
            }

            ExchangeServiceBinding esb = new ExchangeServiceBinding();
            esb.Url = sEWS_URL;
            esb.Credentials = nc;

            //----------------------- main code ---------------
            FindItemType findItemRequest = new FindItemType();
            findItemRequest.Traversal = ItemQueryTraversalType.Shallow;

            // Define which item properties are returned in the response
            ItemResponseShapeType itemProperties = new ItemResponseShapeType();
            itemProperties.BaseShape = DefaultShapeNamesType.AllProperties; 
            findItemRequest.ItemShape = itemProperties;  // Add properties shape to request
 
            // Identify which folders to search to find items
            DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
            folderIDArray[0] = new DistinguishedFolderIdType();
            folderIDArray[0].Id = DistinguishedFolderIdNameType.inbox;

            // Add folders to request
            findItemRequest.ParentFolderIds = folderIDArray;
 
            //Create unread only restriction --------------------------
            RestrictionType restriction = new  RestrictionType();
            IsEqualToType isEqualTo = new  IsEqualToType();
            PathToUnindexedFieldType pathToFieldType = new  PathToUnindexedFieldType();
            pathToFieldType.FieldURI =  UnindexedFieldURIType.messageIsRead;

            FieldURIOrConstantType constantType = new  FieldURIOrConstantType();
            ConstantValueType constantValueType = new  ConstantValueType();
            constantValueType.Value = "0";
            constantType.Item = constantValueType;
            isEqualTo.Item = pathToFieldType;
            isEqualTo.FieldURIOrConstant = constantType;
            restriction.Item = isEqualTo; 
            findItemRequest.Restriction = restriction;
 
            // ------------- GetAccessibilityObjectById the stream
            using ( StreamWriter myreqWriter = new StreamWriter(  "c:\\findItemRequest.xml"))
            {
                XmlSerializer myReqSerializer = new XmlSerializer(typeof(FindItemType));

                myReqSerializer.Serialize(myreqWriter, findItemRequest);

            }
            txtRequest.Text = File.ReadAllText("c:\\findItemRequest.xml");

            // ------------- Send the request and get the response
            FindItemResponseType findItemResponse = esb.FindItem(findItemRequest);

            using (StreamWriter myrespWriter = new StreamWriter("c:\\findItemResponse.xml"))
            {
                XmlSerializer myRespSerializer = new XmlSerializer(typeof(FindItemResponseType));

                myRespSerializer.Serialize(myrespWriter, findItemResponse);
            }
            txtResponse.Text = File.ReadAllText("c:\\findItemResponse.xml");
       

            // ------------- read returned
            FindItemResponseMessageType folder = (FindItemResponseMessageType) findItemResponse.ResponseMessages.Items[0];
            ArrayOfRealItemsType folderContents = new ArrayOfRealItemsType();
            folderContents = (ArrayOfRealItemsType)folder.RootFolder.Item;
            ItemType[] items = folderContents.Items;
            string sText = "";
            foreach (ItemType curItem in items)
            {
                sText += "Subject: " +(curItem.Subject.Trim()) + "  ";
                sText += "DisplayTo: " + (curItem.DisplayTo.Trim()) + "  ";
                sText += "DateTimeReceived: " + (curItem.DateTimeReceived.TimeOfDay.ToString()) + " ";
                sText += "DateTimeReceived: " + (curItem.ItemClass.Trim()) + " ";
                sText += "\r\n" ;

                Console.WriteLine(curItem.Subject);
            }
            txtItems.Text = sText;

        }

Comments

  • Anonymous
    October 16, 2008
    I've put together a list of articles which cover common questions on Exchange Web Services (EWS). These

  • Anonymous
    November 03, 2008
    Hi Dan, first of all thanks for your great Blog about WebDav... it's really awesome! But can you give an example how a second restriction would be implemented? In this example you're only looking for unread messages, how should the implementation look like if you set a second restriction for a additional field like for example sender? Here an example of what I mean: Looking for all unread Messages where sender is info@example.com I've followed your usefull links but couldn't find an answer how to combine multiple restrictions in one request... thx and greetings from germany, Sebastian

  • Anonymous
    March 03, 2009
    Sebastian, You can find a sample here with multiple restrictions http://blogs.msdn.com/vikas/archive/2007/07/27/howto-getfolder-finditem-restriction-getitem.aspx You can extend this sample with as many restrictions as you like

  • Anonymous
    May 06, 2009
    When i run above code i see error 401. Please help

  • Anonymous
    May 18, 2009
    A 401 is unauthorized - not enough permissions.  Please look at the section on 401 errors in the paper on my very first blog posting - WebDAV 101.

  • Anonymous
    September 05, 2010
    Hi Daniel, can you explain me the best way to retrieve an email received in reply to a specific email? Thank you

  • Anonymous
    September 07, 2010
    You could try the conversation index, and if  there is no conversation index, then use conversation topic. Reference:  msdn.microsoft.com/.../cc765583.aspx  

  • Anonymous
    November 29, 2010
    Hi, thats a very useful little program for me but what do i have to change if i want to see the unread items of another mailbox on which i have access rights? And is it possible to get the unread items of the subfolders of inbox, too? Thank you in Advance!

  • Anonymous
    May 01, 2012
    Thanks for this useful code, I need to list only unread mails  from gmail in web application using pop3 client how can i achieve thisplease help me.. Thanks in Advance.....

  • Anonymous
    November 20, 2012
    Hi, We are getting this exception when accessing the EWS. org.xml.sax.SAXException: Processing instructions are not allowed within SOAP messages at org.apache.axis.SOAPPart.getEnvelope can anyone give some clue about the issue? Thank