加载、查看和解析 MSG 文件
Contents
[
Hide
]
本主题解释如何加载 Microsoft Outlook 消息文件 (*.msg)。 MapiMessage 类用于加载 MSG 文件,并提供多种静态加载函数以应对不同场景。以下代码片段展示如何从文件或流中加载 MSG 文件。
加载 MSG 文件
以下代码片段展示如何加载 MSG 文件。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the File directory.
String dataDir = RunExamples.getDataDir_Outlook();
// Create an instance of MapiMessage from file
MapiMessage msg = MapiMessage.fromFile(dataDir + "message.msg");
// Get subject
System.out.println("Subject:" + msg.getSubject());
// Get from address
System.out.println("From:" + msg.getSenderEmailAddress());
// Get body
System.out.println("Body" + msg.getBody());
// Get recipients information
System.out.println("Recipient: " + msg.getRecipients());
// Get attachments
for (MapiAttachment att : msg.getAttachments())
{
System.out.println("Attachment Name: " + att.getFileName());
System.out.println("Attachment Display Name: " + att.getDisplayName());
}
以下代码示例展示如何使用 MailMessage 加载 MSG 格式的消息。
MailMessage eml = MailMessage.load("message.msg");
需要注意的是,生成的消息会转换为 EML 格式,包括嵌入的消息附件。如果想保留原始消息的一些特定 MSG 格式属性,请不要使用此加载方法。
要保留嵌入消息附件的原始格式,请使用 MsgLoadOptions.PreserveEmbeddedMessageFormat 属性。
MsgLoadOptions msgLoadOptions = new MsgLoadOptions();
msgLoadOptions.setPreserveEmbeddedMessageFormat(true);
MailMessage msg = MailMessage.load(stream, msgLoadOptions);
从流加载
以下代码片段展示如何从流中加载文件。
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Create an instance of MapiMessage from file
try (FileInputStream stream = new FileInputStream(dataDir + "message.msg"))
{
// Create an instance of MapiMessage from file
MapiMessage msg = MapiMessage.fromStream(stream);
// Get subject
System.out.println("Subject:" + msg.getSubject());
// Get from address
System.out.println("From:" + msg.getSenderEmailAddress());
// Get body
System.out.println("Body" + msg.getBody());
}
将 EML 转换为 MSG 并保留嵌入的 EML 格式
EML 文件可以加载到 MapiMessage 类,通过实例化一个 MailMessage 对象并将其传递给 MapiMessage.fromMailMessage 方法。如果 EML 文件包含嵌入的 EML 文件,请使用 MapiConversionOptions.setPreserveEmbeddedMessageFormat 以保留嵌入 EML 文件的格式。下面的代码片段展示如何将 EML 文件加载到 MapiMessage 同时保留嵌入的 EML 文件的格式。
Try it out!
使用免费在线转换电子邮件和消息归档 Aspose.Email 转换应用.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = RunExamples.getDataDir_Email();
MailMessage eml = MailMessage.load(dataDir + "sample.eml", new EmlLoadOptions());
MapiConversionOptions options = MapiConversionOptions.getUnicodeFormat();
//Preserve Embedded Message Format
options.setPreserveEmbeddedMessageFormat(true);
//Convert EML to MSG with Options
MapiMessage msg = MapiMessage.fromMailMessage(eml, options);