Exchange Me

So, imagine as part of your B2B project you have a partner that insisted on sending you XML files attached to emails. I know, stone age right? But you can't force them to evolve you have to deal with it.

Well, back in the day you'd end up fooling around with IMAPI, WebDAV or some third party component. Not any more! From 2007 onwards Microsoft have provided web services for working with Exchange Server. Which is great for interoperability - but even better, if you're working in .Net you don't have to worry about SOAP - or even creating a web reference - because they've given us the Microsoft Exchange Web Services Managed API.

The documentation is OK (a bit sparse in places), but when you get it working it's like a dream come true. Here's my spike for pulling attachments off emails in my Inbox:

ExchangeService service = new ExchangeService();
service.UseDefaultCredentials = true;
// using autodiscover I don't need to worry about my mailbox moving!
service.AutodiscoverUrl("myname@mydomain.com");

// get the most recent 50 emails in my inbox
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(50));

foreach (Item myItem in findResults.Items)
{
    EmailMessage message = myItem as EmailMessage;

    if (message != null)
    {
        Console.WriteLine(message.Subject);

        if (message.HasAttachments)
        {
            // bind to emails with attachments
            EmailMessage messageWithAttachment = EmailMessage.Bind(service, new ItemId(message.Id.ToString()), new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));

            foreach (FileAttachment attachment in messageWithAttachment.Attachments)
            {
                // load to a file location i.e. save
                attachment.Load(@"C:\temp\" + attachment.Name);

                Console.WriteLine(("Saved file: " + attachment.Name);
            }
        }
    }
}

Comments