使用 Aspose.Email 和 Apache POI HSMF 提取邮件附件

Aspose.Email - 提取邮件附件

从现有邮件中保存附件:

  1. 创建 MailMessage 类的实例。
  2. 使用 MailMessage 类的 load() 方法加载现有电子邮件,并指定正确的 MessageFormat。
  3. 创建 AttachmentCollection 类的实例,并使用 getAttachments() 方法从 MaiMessage 实例中填充附件。
  4. 遍历 AttachmentCollection 集合。
  5. 创建 Attachment 类的实例,并使用 get() 方法从 AttachmentCollection 中获取索引值填充。
  6. 使用 Attachment 类的 save() 方法将附件保存到磁盘。

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 - 提取邮件附件

可以使用 AttachmentChunks 类访问 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();

				}

			}

		}

	}

}

下载运行代码

下载示例代码