In the last two posts (
Part 1,
Part 2) I've been going over some of the API calls to the Exchange Web Services, and so far we have retrieved an Item, but not any of the attachments held therein... So, lets go get that attachment!
We have an ItemType, which lets us know we have attachments, and now will even let us pull some basic properties but not to save... so, how do we save?
What we're (well, *I'm*) going to do is get the Item, then if it has attachments, save the attachments to my temp directory, so first lets get the Items:
static void GetItem( ExchangeServiceBinding esb, BaseItemIdType itemId )
{
// Form the FindItem request
GetItemType request = new GetItemType();
request.ItemIds = new BaseItemIdType[] {itemId};
request.ItemShape = new ItemResponseShapeType();
request.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
GetItemResponseType response = esb.GetItem( request );
foreach ( ItemInfoResponseMessageType responseMessage in response.ResponseMessages.Items )
{
if( responseMessage.ResponseClass != ResponseClassType.Success )
continue;
foreach ( ItemType item in responseMessage.Items.Items )
{
if(item.HasAttachments && item.Attachments != null)
foreach( AttachmentType attachment in item.Attachments )
{
Console.WriteLine( "\t" + attachment.Name );
}
}
}
}
So, given the ItemId we create a GetItemRequest and then call the 'GetItem' method, this gives us a list of Items with that ID (though in our case - we hope there is only 1)... In this code, I then just go through the attachments in the Item (if there are any) and write out the name...
The next step is to actually *Get* the attachment (as at the moment, we only have the name, id etc)... sooo....
static void GetAttachment( ExchangeServiceBinding esb, RequestAttachmentIdType attachmentId )
{
GetAttachmentType request = new GetAttachmentType();
request.AttachmentIds = new RequestAttachmentIdType[] { attachmentId };
GetAttachmentResponseType response = esb.GetAttachment( request );
foreach( AttachmentInfoResponseMessageType responseMessage in response.ResponseMessages.Items)
{
if( responseMessage.ResponseClass != ResponseClassType.Success )
return;
foreach ( FileAttachmentType attachment in responseMessage.Attachments )
using( BinaryWriter binWriter = new BinaryWriter( File.Open( @"C:\Temp\" + attachment.Name, FileMode.Create ) ) )
binWriter.Write( attachment.Content );
}
}
and with a quick modification of the 'foreach( AttachmentType attachment in item.Attachments) GetItem method to read:
foreach( AttachmentType attachment in item.Attachments )
{
Console.WriteLine( "\t" + attachment.Name );
GetAttachment( esb, attachment.AttachmentId );
}
We're saving all our attachments to the hard drive! Huzzah!
What's important to note in all these posts... The code isn't finalised (i.e. I haven't really added error checking etc) this is more my 'test' code for connecting, and whilst it works in my case, it may not in yours!