Freigeben über


EWS: Obtaining Mail Item from List

In troubleshooting an issue for a customer, I ran into a problem: I could obtain the data from the MAPI store (via EWS) but I was unable to figure out how to cast from the list of items obtained to an actual message to action against.

For example, here's where I was attempting to obtain the items from the MAPI container:          

Console.WriteLine("Connecting to EWS endpoint...");
ExchangeService ExService = newExchangeService(ExchangeVersion.Exchange2007_SP1);
ExService.Credentials = new WebCredentials(targetMBX, passWord);
ExService.AutodiscoverUrl(targetMBX, RedirectionUrlValidationCallback); 

// Obtain the message to reply to.
ItemView iv = new ItemView(3);
FindItemsResults<Item> zeitem = ExService.FindItems(WellKnownFolderName.Inbox, iv);

As you can see, we're calling FindItems and returning it as a collection of Items. I thought a cast would have to occur, to convert the Item back into an EmailMessage. Instead, as one would be happy to find out as I was, the Item is an encapsulation of the EmailMessage and we can 'extract' it via an array call:

var item = zeitem.Items[0];

From this, we can further action against the mail items via EWS:

if (item is EmailMessage)
{
      Console.WriteLine("Working with the first item found.");

// Reply to the message
ResponseMessage responseMessage = message.CreateReply(replyToAll);
string myReply = "This is a test of the EWS responseMessage method[s].";
responseMessage.BodyPrefix = myReply;
      var messageToSend = responseMessage.Save();

// Send and save a copy of the replied email message in the default Sent Items folder.
messageToSend.SendAndSaveCopy();
}

Using the EWS API, one can do many powerful and important administrative tasks in Exchange. You can read more about it, here.