Extract Message Attachments using Aspose.Email and Apache POI HSMF

Aspose.Email - Extract Message Attachments

To save attachments from existing messages:

  1. Create an instance of the MailMessage class.
  2. Load the existing email message using the MailMessage class load() method, specifying the correct MessageFormat.
  3. Create an instance of the AttachmentCollection class and fill it with attachments from the MaiMessage instance using the getAttachments() method.
  4. Iterate over the AttachmentCollection collection.
  5. Create an instance of the Attachment class and fill it with indexed value from the AttachmentCollection using the get() method.
  6. Save the attachment to disk using the Attachment class save() method.

Java

 MailMessage message = MailMessage.load(dataDir + "message.msg");

System.out.println("Extracting attachments....");

for (int i = 0; i < message.getAttachments().size(); i++)

{

    Attachment att = (Attachment) message.getAttachments().get_Item(i);

    System.out.println("Attachment Name: " + att.getName());

    String attFileName = att.getName().replace(".eml", "").replace(":", " ").replace("\\", " ").replace("/", " ").replace("?", "");

    // Save the attachment to disk

    att.save(dataDir + attFileName);

}

Apache POI HSMF - Extract Message Attachments

AttachmentChunks class can be used to access attachments of MAPIMessage.

Java

 MAPIMessage msg = new MAPIMessage(dataDir + "message.msg");

AttachmentChunks[] attachments = msg.getAttachmentFiles();

if (attachments.length > 0)

{

	File d = new File(dataDir + "attachments");

	if (d.exists() || d.mkdir())

	{

		for (AttachmentChunks attachment : attachments)

		{

			String fileName = attachment.attachFileName.toString();

			if (attachment.attachLongFileName != null)

			{

				fileName = attachment.attachLongFileName.toString();

			}

			File f = new File(d, fileName);

			OutputStream fileOut = null;

			try

			{

				fileOut = new FileOutputStream(f);

				fileOut.write(attachment.attachData.getValue());

			}

			finally

			{

				if (fileOut != null)

				{

					fileOut.close();

				}

			}

		}

	}

}

Download Running Code

Download Sample Code