Save attachments

You can save/export attachments from Email documents, Outlook data files, Archives and PDF documents with only a few lines of code using GroupDocs.Viewer for Java API.

Follow these steps to get and save (export) attachments:

  • Instantiate Viewer object for the file that contains attachment(s);
  • Call getAttachments() method which will return document attachments collection;
  • Iterate through attachments collection and save attachment by calling saveAttachment(…) method.

Following example demonstrates on how to get and save all attachments contained by a MSG file.

try (Viewer viewer = new Viewer("sample.msg")) {
    List<Attachment> attachments = viewer.getAttachments();

    for (Attachment attachment : attachments) {
        FileOutputStream fileStream = 
            new FileOutputStream(attachment.getFileName());

        viewer.saveAttachment(attachment, fileStream);
    }
}

After running the code above all the attachments will be saved to the current directory.

Provided code example is actual for all document types that support attachments - Email documents, Outlook data files, Archives and PDF documents.