Monday, August 4, 2014

using the exchange web service API from c#

This week I had been looking at the exchange web service API and how we can inspect Emails within Exchange.


If you need to read emails from an inbox then you can very easily and quickly by using the exchange web service API which you can download from here.


I was looking for a way to check unread messages and download its attachment then mark email as read.


In the following example lets assume we will have emails


Create a reference in your project to Microsoft.Exchange.WebServices.dll which you will be able to found in C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll


The following code demonstrates how to achieve this:


using Microsoft.Exchange.WebServices.Data;


 
 
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
                service.Credentials = new WebCredentials("Email Username""Email Password""domain name");
                service.Url = new Uri("https://contoso.com.au/ews/exchange.asmx");
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
                Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
 

                // The search filter to get unread email.
                SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                ItemView view = new ItemView(1000);
 
 
                // Fire the query for the unread items.
                // This method call results in a FindItem call to EWS.
                FindItemsResults<Item> unreadMessages = service.FindItems(WellKnownFolderName.Inbox, sf, view);
 
                 foreach (EmailMessage message in unreadMessages)
                {
                    message.Load();
                    Console.Out.WriteLine("*********************  Processing email " + message.Subject + " *********************");
                    foreach (FileAttachment attachment in message.Attachments)
                    {
                        if (attachment is FileAttachment)
                        {
 
                            FileAttachment fileAttachment = attachment as FileAttachment;
                            fileAttachment.Load("c:\\attachements\\" + fileAttachment.Name);
 
                        }
                    }
 
                    message.IsRead = true;
                    message.Update(ConflictResolutionMode.AlwaysOverwrite);
                }

No comments: