Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download attachments using Exchange Web Services Java API?

I am writing a Java application to download emails using Exchange Web Services. I am using Microsoft's ewsjava API for doing this.

I am able to fetch email headers. But, I am not able to download email attachments using this API. Below is the code snippet.

FolderId folderId = new FolderId(WellKnownFolderName.Inbox, "[email protected]");
findResults = service.findItems(folderId, view);
for(Item item : findResults.getItems()) {
   if (item.getHasAttachments()) {
      AttachmentCollection attachmentsCol = item.getAttachments();
      System.out.println(attachmentsCol.getCount()); // This is printing zero all the time. My message has one attachment.
      for (int i = 0; i < attachmentsCol.getCount(); i++) {
         FileAttachment attachment = (FileAttachment)attachmentsCol.getPropertyAtIndex(i);
         String name = attachment.getFileName();
         int size = attachment.getContent().length;
      }
   }
}

item.getHasAttachments() is returning true, but attachmentsCol.getCount() is 0.

like image 258
NareshPS Avatar asked Jul 05 '11 16:07

NareshPS


3 Answers

You need to load property Attachments before you can use them in your code. You set it for ItemView object that you pass to FindItems method.

Or you can first find items and then call service.LoadPropertiesForItems and pass findIesults and PropertySet object with added EmailMessageSchema.Attachments

like image 61
grapkulec Avatar answered Nov 02 '22 12:11

grapkulec


FolderId folderId = new FolderId(WellKnownFolderName.Inbox, "[email protected]"); 
findResults = service.findItems(folderId, view); 
service.loadPropertiesForItems(findResults, new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.Attachments));

for(Item item : findResults.getItems()) { 
   if (item.getHasAttachments()) { 
      AttachmentCollection attachmentsCol = item.getAttachments(); 
      System.out.println(attachmentsCol.getCount());
      for (int i = 0; i < attachmentsCol.getCount(); i++) { 
         FileAttachment attachment = (FileAttachment)attachmentsCol.getPropertyAtIndex(i); 
         attachment.load(attachment.getName());
      } 
   } 
} 
like image 4
Yury Avatar answered Nov 02 '22 10:11

Yury


Honestly as painful as it is, I'd use the PROXY version instead of the Managed API. It's a pity, but the managed version for java seems riddled with bugs.

like image 1
MJB Avatar answered Nov 02 '22 12:11

MJB