Extract Message Attachments using Aspose.Email and Apache POI HSMF
Contents
[
Hide
]
Aspose.Email - Extract Message Attachments
To save attachments from existing messages:
- Create an instance of the MailMessage class.
- Load the existing email message using the MailMessage class load() method, specifying the correct MessageFormat.
- Create an instance of the AttachmentCollection class and fill it with attachments from the MaiMessage instance using the getAttachments() method.
- Iterate over the AttachmentCollection collection.
- Create an instance of the Attachment class and fill it with indexed value from the AttachmentCollection using the get() method.
- 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
For more details, visit Manage Attachments in Email Message.