简体   繁体   English

使用 Exchange 下载附件 Web 服务 Java API?

[英]Download attachments using Exchange Web Services Java API?

I am writing a Java application to download emails using Exchange Web Services.我正在编写一个 Java 应用程序来使用 Exchange Web 服务下载电子邮件。 I am using Microsoft's ewsjava API for doing this.我正在使用 Microsoft 的 ewsjava API 来执行此操作。

I am able to fetch email headers.我能够获取 email 标头。 But, I am not able to download email attachments using this API.但是,我无法使用此 API 下载 email 附件。 Below is the code snippet.下面是代码片段。

FolderId folderId = new FolderId(WellKnownFolderName.Inbox, "mailbox@example.com");
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 . item.getHasAttachments()返回true ,但attachmentsCol.getCount()0

You need to load property Attachments before you can use them in your code.您需要先加载属性Attachments ,然后才能在代码中使用它们。 You set it for ItemView object that you pass to FindItems method.您为传递给 FindItems 方法的ItemView object 设置它。

Or you can first find items and then call service.LoadPropertiesForItems and pass findIesults and PropertySet object with added EmailMessageSchema.Attachments或者您可以先查找项目,然后调用service.LoadPropertiesForItems并通过findIesultsPropertySet object 添加EmailMessageSchema.Attachments

FolderId folderId = new FolderId(WellKnownFolderName.Inbox, "mailbox@example.com"); 
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());
      } 
   } 
} 

Honestly as painful as it is, I'd use the PROXY version instead of the Managed API.老实说,虽然很痛苦,但我会使用代理版本而不是托管 API。 It's a pity, but the managed version for java seems riddled with bugs.很遗憾,但 java 的托管版本似乎充满了错误。

before checking for item.getHasAttachments(), you should do item.load().在检查 item.getHasAttachments() 之前,您应该执行 item.load()。 Otherwise there is a chance your code will not load the attachment and attachmentsCol.getCount() will be 0. Working code with Exchange Server 2010:否则,您的代码可能不会加载附件,并且 attachmentsCol.getCount() 将为 0。Exchange Server 2010 的工作代码:

ItemView view = new ItemView(Integer.MAX_VALUE);
view.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Descending);  
FindItemsResults < Item > results = service.findItems(WellKnownFolderName.Inbox, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true), view);
Iterator<Item> itr = results.iterator();
while(itr.hasNext()) {
    Item item = itr.next();
    item.load();
    ItemId itemId = item.getId();
    EmailMessage email = EmailMessage.bind(service, itemId);
    if (item.getHasAttachments()) { 
        System.err.println(item.getAttachments());
        AttachmentCollection attachmentsCol = item.getAttachments(); 
        for (int i = 0; i < attachmentsCol.getCount(); i++) {
            FileAttachment attachment=(FileAttachment)attachmentsCol.getPropertyAtIndex(i);
            attachment.load("C:\\TEMP\\" +attachment.getName());
        }
    }
}

Little late for the answer, but here is what I have.答案有点晚了,但这就是我所拥有的。

HashMap<String, HashMap<String, String>> attachments = new HashMap<String, HashMap<String, String>>();    

if (emailMessage.getHasAttachments() || emailMessage.getAttachments().getItems().size() > 0) {

            //get all the attachments
            AttachmentCollection attachmentsCol = emailMessage.getAttachments();

            log.info("File Count: " +attachmentsCol.getCount());

            //loop over the attachments
            for (int i = 0; i < attachmentsCol.getCount(); i++) {
                Attachment attachment = attachmentsCol.getPropertyAtIndex(i);
                //log.debug("Starting to process attachment "+ attachment.getName());

                   //FileAttachment - Represents a file that is attached to an email item
                    if (attachment instanceof FileAttachment || attachment.getIsInline()) {

                        attachments.putAll(extractFileAttachments(attachment, properties));

                    } else if (attachment instanceof ItemAttachment) { //ItemAttachment - Represents an Exchange item that is attached to another Exchange item.

                        attachments.putAll(extractItemAttachments(service, attachment, properties, appendedBody));
                    }
                }
            }
        } else {
            log.debug("Email message does not have any attachments.");
        }


//Extract File Attachments
try {
        FileAttachment fileAttachment = (FileAttachment) attachment;
        // if we don't call this, the Content property may be null.
        fileAttachment.load();

        //extract the attachment content, it's not base64 encoded.
        attachmentContent = fileAttachment.getContent();

        if (attachmentContent != null && attachmentContent.length > 0) {

            //check the size
            int attachmentSize = attachmentContent.length;

            //check if the attachment is valid
            ValidateEmail.validateAttachment(fileAttachment, properties,
                    emailIdentifier, attachmentSize);

            fileAttachments.put(UtilConstants.ATTACHMENT_SIZE, String.valueOf(attachmentSize));

            //get attachment name
            String fileName = fileAttachment.getName();
            fileAttachments.put(UtilConstants.ATTACHMENT_NAME, fileName);

            String mimeType = fileAttachment.getContentType();
            fileAttachments.put(UtilConstants.ATTACHMENT_MIME_TYPE, mimeType);

            log.info("File Name: " + fileName + "  File Size: " + attachmentSize);


            if (attachmentContent != null && attachmentContent.length > 0) {
                //convert the content to base64 encoded string and add to the collection.
                String base64Encoded = UtilFunctions.encodeToBase64(attachmentContent);
                fileAttachments.put(UtilConstants.ATTACHMENT_CONTENT, base64Encoded);
            }



//Extract Item Attachment
try {
        ItemAttachment itemAttachment = (ItemAttachment) attachment;

        PropertySet propertySet = new PropertySet(
                BasePropertySet.FirstClassProperties, ItemSchema.Attachments, 
                ItemSchema.Body, ItemSchema.Id, ItemSchema.DateTimeReceived,
                EmailMessageSchema.DateTimeReceived, EmailMessageSchema.Body);

        itemAttachment.load();
        propertySet.setRequestedBodyType(BodyType.Text);

        Item item = itemAttachment.getItem();

        eBody = appendItemBody(item, appendedBody.get(UtilConstants.BODY_CONTENT));

        appendedBody.put(UtilConstants.BODY_CONTENT, eBody);

        /*
         * We need to check if Item attachment has further more
         * attachments like .msg attachment, which is an outlook email
         * as attachment. Yes, we can attach an email chain as
         * attachment and that email chain can have multiple
         * attachments.
         */
        AttachmentCollection childAttachments = item.getAttachments();
        //check if not empty collection. move on
        if (childAttachments != null && !childAttachments.getItems().isEmpty() && childAttachments.getCount() > 0) {

            for (Attachment childAttachment : childAttachments) {

                if (childAttachment instanceof FileAttachment) {

                    itemAttachments.putAll(extractFileAttachments(childAttachment, properties, emailIdentifier));

                } else if (childAttachment instanceof ItemAttachment) {

                    itemAttachments = extractItemAttachments(service, childAttachment, properties, appendedBody, emailIdentifier);
                }
            }
        }
    } catch (Exception e) {
        throw new Exception("Exception while extracting Item Attachments: " + e.getMessage());
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 通过使用Exchange Web Services Api 2.0和Java在Exchange Server中添加约会 - Add an appointment in Exchange Server by using Exchange Web Services Api 2.0 and Java Exchange Web服务Java APi + RESTful推送通知侦听器 - Exchange Web Services Java APi + RESTful Push Notifications Listener Exchange Web服务(EWS)Java Api:401未经授权 - Exchange Web-Services (EWS) Java Api : 401 Unauthorized Exchange Web服务(EWS)或JavaMail Api连接到Outlook Exchange Server-Java - Exchange Web Services (EWS) or JavaMail Api to connect to Outlook Exchange Server - Java 使用 Java Mail 下载附件 - Download attachments using Java Mail 使用JAVAX API下载电子邮件附件 - Download email attachments using JAVAX api 使用Java从Microsoft Mail Exchange服务器读取带有附件的邮件 - Read mails with attachments from Microsoft mail Exchange server using Java 如何通过Java Web Service客户端连接Exchange Web Services? - How to connect Exchange Web Services via java web service client? 如何使用JAVA Rest API从Rally工作项下载附件? - How can I download attachments from a Rally workitem using JAVA Rest API? 使用Java Jackrabbit Web DAV客户端从Exchange Server 2003下载电子邮件附件 - Download email attachment from exchange server 2003 using java jackrabbit web dav client
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM