Friday, 17 February 2012

Java Client Exchange Web Services - EWS

Following snippets explains you to write Java Clients that consumes Microsoft Exchange Web Services.

From Exchange Server 2010 Microsoft stopped WEBDAV support on exchange server.  Java Clients using WEBDAV needs to migrate to consume EWS to fetch mail, compose, send  emails ..etc 

Read five email items from inbox

package demo;

import java.net.URI;

import microsoft.exchange.webservices.data.ExchangeCredentials;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.FindItemsResults;
import microsoft.exchange.webservices.data.Item;
import microsoft.exchange.webservices.data.ItemView;
import microsoft.exchange.webservices.data.WebCredentials;
import microsoft.exchange.webservices.data.WellKnownFolderName;

public class EWSDemo {
 public static void main(String[] args) throws Exception {
  ExchangeService service = new ExchangeService();
  // Provide Crendentials
  ExchangeCredentials credentials = new WebCredentials("username", "password");
  service.setCredentials(credentials);

  // Set Exchange WebSevice URL
  service.setUrl(new URI("https://myexchangehost/EWS/exchange.asmx"));

  // Get five items from mail box
  ItemView view = new ItemView(5);

  // Search Inbox
  FindItemsResults findResults = service.findItems(WellKnownFolderName.Inbox, view);

  // iterate thru items
  for (Item item : findResults.getItems()) {
   System.out.println(item.getSubject());
  }

 }
} 
Reading Body 

 
item.getBody()
 Reading body using the method item.getBody() it yields to exception
 
Exception in thread "main" microsoft.exchange.webservices.data.ServiceObjectPropertyException: You must load or assign this property before you can read its value.
To overcome it first the body needs to be loaded.
item.load();
Reading Non default mail box
Some time it is possible for single user to have multiple mail boxes. Following snippet shows you to access non default mail box for eg sysadmin@abc.com
Mailbox mb = new Mailbox();
mb.setAddress("syadmin@abc.com");
FolderId folderId = new FolderId(WellKnownFolderName.Inbox, mb);
  
// Search Inbox syadmin@abc.com
FindItemsResults findResults = service.findItems( folderId, view);
Reading UnRead Emails
  // Get five items from mail box
  ItemView view = new ItemView(5);
  
  //Set Filter to Read UnRead emails
  SearchFilter itemFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true);
  // Search Inbox
  FindItemsResults findResults = service.findItems(WellKnownFolderName.Inbox,itemFilter,view);

  // iterate thru items
  for (Item item : findResults.getItems()) {
     System.out.println(item.getSubject());
  }

Marking mail as read
// iterate thru items
  for (Item item : findResults.getItems()) {
   //Type cast it to EmailMessage
   EmailMessage em = (EmailMessage) item;
   em.setIsRead(true);
   em.update(ConflictResolutionMode.AlwaysOverwrite);
   System.out.println(em.getSubject());
  }
Reading mail Headers and body
// iterate thru items
  for (Item item : findResults.getItems()) {
   item.load();
   String subject=item.getSubject();
   //Read Body
   String body = MessageBody.getStringFromMessageBody(item.getBody());
   System.out.println(subject);
   System.out.println(body);
   //Reading Header
   InternetMessageHeaderCollection headers = item.getInternetMessageHeaders();
   for(InternetMessageHeader header:headers){
    System.out.println("Header Name: "+header.getName()+" Header Value: "+header.getValue() );
   }
  }

21 comments:

  1. Where did you get microsoft.exchange.webservices.data.xxx code from?

    That's not what's generated from the wsdl.

    Thanks

    Bob

    ReplyDelete
  2. For old versions of Exchange (2000-2003-2007) good alternative is WebDAV library for Exchange http://www.independentsoft.de/jwebdav/index.html

    ReplyDelete
  3. any idea how to import webdav library to netbeans ?

    ReplyDelete
  4. Its Really a good post. It helped me a lot

    ReplyDelete
  5. Here are some of the other Items I want to add for this post. This would help others ....

    ReplyDelete
  6. To Find the Mail Box Folders Size
    =====================================

    public static void findInboxSize2(ExchangeService service) throws Exception
    {
    ExtendedPropertyDefinition extendedProperty
    = new ExtendedPropertyDefinition(0xe08, MapiPropertyType.Long);

    PropertySet propertySet = new PropertySet(BasePropertySet.FirstClassProperties,extendedProperty);

    FindFoldersResults folders=null;
    FolderView view = new FolderView(Integer.MAX_VALUE);
    int pagesize = 50;
    do {
    folders = service.findFolders(WellKnownFolderName.MsgFolderRoot,
    new FolderView(pagesize, view.getOffset(), OffsetBasePoint.Beginning));

    for(Folder folder : folders)
    {
    folder.load(propertySet);

    ExtendedPropertyCollection extCollection = folder.getExtendedPropertiesForService();
    for (Iterator it = extCollection.iterator(); it.hasNext(); ) {
    ExtendedProperty extProp = it.next();
    Object value = extProp.getValue();
    System.out.println(folder.getDisplayName()+" : " + value);
    }

    }
    int i = view.getOffset();
    }while(folders.isMoreAvailable());
    }

    ReplyDelete
  7. TO Send Mail using Exchange Web Services (EWS)
    ================================================

    public static void sendEmail(ExchangeService service, String to, String subject, String body)
    throws Exception
    {
    EmailMessage email = new EmailMessage(service);
    email.getToRecipients().add(to);
    email.setSubject(subject);
    email.setBody(new MessageBody(body));
    email.send();
    }

    ReplyDelete
    Replies
    1. Thanks praveen its working for me.

      Delete
    2. Hi Praveen,
      Can u tell me how to send email on multiple recipient.

      Delete
  8. Hi,
    its very helpfull for me thanks alot

    ReplyDelete
  9. Hi,

    Great post!
    How can I listen to INBOX folder and get an incomming mail with attachmens(more than 2).
    I also need to filter the mails according to conditions, i.e - if the subject contain certain string, or an out of office reply mail.

    Appriciate your help here.

    Thanks
    Joe

    ReplyDelete
  10. Hi,

    How can i attach inline attachments by using the EWS Managed API.
    Actually i want a logo on my form,

    Appriciate your help here.

    ReplyDelete
  11. Hi,
    I can't mark unread message as read.
    Get connection failed exception.
    Please, help.!

    ReplyDelete
  12. What about load all distribution groups from exchange server??

    ReplyDelete
  13. hello guys ...
    i have created a account on outlook.com
    and now I am trying to read the Inbox as shown below.

    But it is not working for me.
    My code gets stuck at the line: service.autodiscoverUrl(EMAIL_ID);

    Can someone point me to the solution.
    Is this EWS suppose to work with Outlook.com?

    ----------------------------------------------------------------------------------------------------------
    ExchangeService service = new ExchangeService();
    ExchangeCredentials credentials = new WebCredentials(EMAIL_ID, EMAIL_PWD);
    service.setCredentials(credentials);
    try {
    System.out.println("111111111111111");
    service.autodiscoverUrl(EMAIL_ID);
    System.out.println("222222222222222");
    ItemView view = new ItemView(10);
    FindItemsResults findResults;

    findResults = service.findItems(WellKnownFolderName.Inbox, view);

    for(Item item : findResults.getItems())
    {
    item.load();
    System.out.println(item.getSubject());
    }

    } catch (Exception e) {
    e.printStackTrace();
    }

    ReplyDelete
  14. Hi,i want to get email any body tell me what i do for this.i am new in android .i cannot know how i start .

    ReplyDelete
  15. Hello , I want to know if I can use this code to connect Exchange server 2013.
    Thanks in advance!

    ReplyDelete
    Replies
    1. I think you ca specify on the Exchange constructor the latest available version and it will work with 2013

      Like:
      new ExchangeService(ExchangeVersion.Exchange2010_SP2)

      Delete
  16. Unser Unternehmen bietet beste Qualität und Web-Entwicklung Dienstleistungen in Deutschland. Wir bieten derzeit Web und mobile Anwendung Entwicklungsdienstleistungen .http://www.accuratesolutionsltd.com/web-entwicklung/

    ReplyDelete
  17. Hi i am always getting connection timed out error what will be the issue.

    ReplyDelete
  18. Can some one tell code how to download email attachments on HD using Java EWS api

    ReplyDelete