Exchange Web Services (EWS) programming with Exchange Server 2010 in C#

I have an application to sniff email notification from Exchange Server and automatically insert data record to SQL database. Because recently our IT department upgraded MS Exchange Server to 2010 and Exchange Server 2010 does not support WebDAV any more, my robust WebDAV program is dead 🙁

To revive my application, I have to migrant WebDAV to EWS, because WebDAV has been replaced by Exchange Web Services (EWS). EWS is relatively new, and there is no too much information I can use. Here to share my EWS programming experience.

private void ReceiveEmail(object sender, EventArgs e)
{
    ExchangeServiceBinding esb = new ExchangeServiceBinding();
    esb.Credentials = new NetworkCredential(username, password, domain);
    ServicePointManager.ServerCertificateValidationCallback =
      delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
      {
          // trust any certificate
          return true;
      };

    esb.Url = @"https://exchangeserver/EWS/Exchange.asmx";

    FindItemType findRequest = new FindItemType();
    findRequest.ItemShape = new ItemResponseShapeType();
    findRequest.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;

    DistinguishedFolderIdType inbox = new DistinguishedFolderIdType();
    inbox.Id = DistinguishedFolderIdNameType.inbox;
    findRequest.ParentFolderIds = new []{inbox};
    findRequest.Traversal = ItemQueryTraversalType.Shallow;


    findRequest.ItemShape.BodyType = BodyTypeResponseType.Text;
    findRequest.ItemShape.BodyTypeSpecified = true;

    FindItemResponseType response = esb.FindItem(findRequest);
    FindItemResponseMessageType responseMessage =
      response.ResponseMessages.Items[0]
          as FindItemResponseMessageType;
    ArrayOfRealItemsType items = responseMessage.RootFolder.Item as ArrayOfRealItemsType;


    foreach (MessageType item in items.Items)
    {
         MessageType msg = (MessageType) item;
         string emailBody = GetMessageBody(esb, msg);
         //delete email
         this.DeleteMessage(esb,msg);
    }
}

private string GetMessageBody(ExchangeServiceBinding binding, MessageType message)
{
    string messageBody = string.Empty;
    MessageType temp = null;

    // Call GetItem on each ItemId to retrieve the
    // item’s Body property and any AttachmentIds.
    //
    // Form the GetItem request.
    GetItemType getItemRequest = new GetItemType();

    getItemRequest.ItemShape = new ItemResponseShapeType();
    // AllProperties on a GetItem request WILL return
    // the message body.
    getItemRequest.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;

    getItemRequest.ItemIds = new ItemIdType[1];
    getItemRequest.ItemIds[0] = (BaseItemIdType)message.ItemId;

    // Here is the call to exchange.
    GetItemResponseType getItemResponse = binding.GetItem(getItemRequest);

    // We only passed in one ItemId to the GetItem
    // request. Therefore, we can assume that
    // we got at most one Item back.
    ItemInfoResponseMessageType getItemResponseMessage =
        getItemResponse.ResponseMessages.Items[0]
        as ItemInfoResponseMessageType;

    if (getItemResponseMessage != null)
    {
        if (getItemResponseMessage.ResponseClass ==
            ResponseClassType.Success
            && getItemResponseMessage.Items.Items != null
            && getItemResponseMessage.Items.Items.Length > 0)
            {
                temp = (MessageType)getItemResponseMessage.Items.Items[0];

                if (temp.Body != null)
                    messageBody = temp.Body.Value;
            }
    }
    return messageBody;
}

private void DeleteMessage(ExchangeServiceBinding binding, MessageType message)
{
    // Call DeleteItem on each ItemId to delete the message
    // Form the DeleteItem request.
    DeleteItemType delItemRequest = new DeleteItemType();

    delItemRequest.ItemIds = new ItemIdType[1];
    delItemRequest.ItemIds[0] = (BaseItemIdType)message.ItemId;
    
    // Here is the call to exchange.
    DeleteItemResponseType delItemResponse = binding.DeleteItem(delItemRequest);
}