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;
                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” ;

            txtItems.Text = sText;


Comments (10)

  1. I’ve put together a list of articles which cover common questions on Exchange Web Services (EWS). These

  2. ichbinweg says:

    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,


  3. Vikas - MSFT says:


    You can find a sample here with multiple restrictions


    You can extend this sample with as many restrictions as you like

  4. linhphan says:

    When i run above code i see error 401. Please help

  5. Webdav101 says:

    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.

  6. Gigi says:

    Hi Daniel,

    can you explain me the best way to retrieve an email received in reply to a specific email?

    Thank you

  7. Webdav101 says:

    You could try the conversation index, and if  there is no conversation index, then use conversation topic.

    Reference:  msdn.microsoft.com/…/cc765583.aspx  

  8. snd says:

    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!

  9. Ajit Kumar Das says:

    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…..

  10. DJ says:


    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?


Skip to main content