加载和保存消息

加载和保存电子邮件消息

检测文件格式

Aspose.Email API 提供检测提供的邮件文件格式的功能。该 DetectFileFormat 方法的 FileFormatUtil 可以使用该类来实现此功能。以下类和方法可用于检测已加载的文件格式。

以下代码片段展示了如何检测文件格式。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// The path to the resource directory.
String dataDir = "data/";

// Detect the file format
FileFormatInfo info = FileFormatUtil.detectFileFormat(dataDir + "Message.msg");

// Get the detected load format
System.out.println("The message format is: " + info.getFileFormatType());

检测 RFC 消息文件

邮件服务器和归档工具经常将包含 MIME 内容但不是标准 EML 或 MHT 文件的消息存储为文件,例如使用 .trn 扩展名。这类文件被识别为 RFC 消息: detectFileFormat 返回 FileFormatType.RfcMessage 为它们提供值。这使您能够识别这些文件并将其作为电子邮件处理,而不是将其视为未知格式而跳过。

FileFormatInfo info = FileFormatUtil.detectFileFormat("message.trn");

if (info.getFileFormatType() == FileFormatType.RfcMessage) {
    // The file contains MIME content, so it can be loaded as an email message
    MailMessage message = MailMessage.load("message.trn");
    System.out.println("Body: " + message.getBody());
}

加载电子邮件消息

要使用特定加载选项加载消息,Aspose.Email 提供了 LoadOptions 可按如下方式使用的类:

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
// Loading with default options
// Load from EML
MailMessage eml = MailMessage.load("test.eml", new EmlLoadOptions());

// Load from HTML
MailMessage html = MailMessage.load("test.html", new HtmlLoadOptions());

// Load from MHTML
MailMessage mhtml = MailMessage.load("test.mhtml", new MhtmlLoadOptions());

// Load from MSG
MailMessage msg = MailMessage.load("test.msg", new MsgLoadOptions());

// Load from the TNEF format
MailMessage tnef = MailMessage.load("winmail.dat", new TnefLoadOptions());

// Loading with custom options
EmlLoadOptions emlOptions = new EmlLoadOptions();
emlOptions.setPreserveTnefAttachments(true);
MailMessage emlMailMessage = MailMessage.load("test.eml", emlOptions);

HtmlLoadOptions htmlOptions = new HtmlLoadOptions();
htmlOptions.shouldAddPlainTextView(true);
MailMessage htmlMailMessage = MailMessage.load("test.html", htmlOptions);

从 EML 加载

本节介绍如何使用该方式将 EML 文件加载到 MailMessage 对象中。 EmlLoadOptions 类。该类提供选项来自定义 EML 文件的加载方式,例如保留嵌入消息格式或控制 TNEF 附件的加载行为。

  1. 初始化 EmlLoadOptions 实例。
  2. 根据需要配置加载选项。
  3. 使用 MailMessage.load() 使用指定选项加载 EML 文件的方法。
// Initialize EmlLoadOptions
EmlLoadOptions loadOptions = new EmlLoadOptions();

// Configure the load options
loadOptions.setPreferredTextEncoding(StandardCharsets.UTF_8);  // preferred encoding for the message
loadOptions.setPreserveEmbeddedMessageFormat(true);            // preserve the format of embedded messages
loadOptions.setPreserveTnefAttachments(true);                  // control TNEF attachment loading
loadOptions.setRemoveSignature(false);                         // do not remove the signature

// Load the EML file
MailMessage eml = MailMessage.load("file.eml", loadOptions);

EmlLoadOptions 的属性

  • PreferredTextEncoding - 设置消息主题和正文的首选编码。默认是 null.
  • PreserveEmbeddedMessageFormat - 指示加载时是否保留嵌入消息的格式。默认值为 false.
  • PreserveTnefAttachments - 控制 TNEF 附件加载行为。默认是 false.
  • RemoveSignature - 指定加载时是否应移除签名。默认值为 false.

加载带签名/不带签名的消息

默认情况下加载 EML 文件时支持保留签名。要移除签名,请设置 setRemoveSignature(true):

EmlLoadOptions loadOptions = new EmlLoadOptions();
loadOptions.setRemoveSignature(true);

MailMessage msg = MailMessage.load("signed.eml", loadOptions);

从 EMLX 加载

该 EmlxLoadOptions 类提供类似于 EmlLoadOptions 的选项,允许控制编码、签名移除和嵌入消息格式。

// Instantiate EmlxLoadOptions
EmlxLoadOptions loadOptions = new EmlxLoadOptions();

loadOptions.setPreferredTextEncoding(StandardCharsets.UTF_8);
loadOptions.setPreserveEmbeddedMessageFormat(true);
loadOptions.setRemoveSignature(true);

// Load the EMLX file
MailMessage emlx = MailMessage.load("file.emlx", loadOptions);

EmlxLoadOptions 的属性

  • PreferredTextEncoding - 设置消息主题和正文的首选编码。默认是 null.
  • PreserveEmbeddedMessageFormat - 指示是否在加载时保留嵌入式消息的格式。默认是 false.
  • RemoveSignature - 指定在加载时是否移除签名。默认是 false.

从 HTML 加载

该 HtmlLoadOptions 类专门用于处理 HTML 内容,提供管理资源和添加纯文本视图的选项。

// Initialize HtmlLoadOptions
HtmlLoadOptions loadOptions = new HtmlLoadOptions();

loadOptions.setPathToResources("resources/");                 // directory containing the resource files
loadOptions.setPreferredTextEncoding(StandardCharsets.UTF_8);
loadOptions.shouldAddPlainTextView(true);                     // add a plain text view of the body

// Load the HTML file
MailMessage html = MailMessage.load("file.html", loadOptions);

HtmlLoadOptions 的属性

  • PathToResources - 定义资源文件(例如图像)所在目录的路径。
  • PreferredTextEncoding - 设置消息主题和正文的首选编码。默认是 null.
  • PreserveEmbeddedMessageFormat - 决定是否保留嵌入式消息的格式。默认是 false.
  • shouldAddPlainTextView(boolean) - 指定是否在消息正文中添加纯文本视图。默认是 false。请注意访问器名称:它不是 setShouldAddPlainTextView.

从 MHTML 加载

该 MhtmlLoadOptions 类提供管理编码、保留嵌入式消息格式以及处理 TNEF 附件的选项。

// Create MhtmlLoadOptions
MhtmlLoadOptions loadOptions = new MhtmlLoadOptions();

loadOptions.setPreferredTextEncoding(StandardCharsets.UTF_8);
loadOptions.setPreserveEmbeddedMessageFormat(true);
loadOptions.setPreserveTnefAttachments(true);
loadOptions.setRemoveSignature(false);

// Load the MHTML file
MailMessage mhtml = MailMessage.load("file.mht", loadOptions);

MhtmlLoadOptions 的属性

  • MessageFormat - 表示邮件消息格式,可为 EML、MSG 或 MHTML。默认是 EML。该属性在 Java 中为只读。
  • PreferredTextEncoding - 设置消息主题和正文的首选编码。默认是 null.
  • PreserveEmbeddedMessageFormat - 决定是否保留嵌入式消息的格式。默认是 false.
  • PreserveTnefAttachments - 控制 TNEF 附件加载行为。默认是 false.
  • RemoveSignature - 指定在加载时是否移除签名。默认是 false.

从 MSG 加载

该 MsgLoadOptions 类提供多种属性以处理 MSG 文件的加载方式,包括保留 RTF 内容或管理 TNEF 附件的选项。

// Create MsgLoadOptions
MsgLoadOptions loadOptions = new MsgLoadOptions();

loadOptions.setKeepOriginalEmailAddresses(true);              // preserve the original email addresses
loadOptions.setPreferredTextEncoding(StandardCharsets.UTF_8);
loadOptions.setPreserveRtfContent(true);                      // keep the RTF content in the message
loadOptions.setPreserveTnefAttachments(true);
loadOptions.setRemoveSignature(false);
loadOptions.setTimeout(5000);                                 // limit the loading time to 5 seconds

// Load the MSG file
MailMessage msg = MailMessage.load("file.msg", loadOptions);

MsgLoadOptions 的属性

  • KeepOriginalEmailAddresses - 指示是否保留原始电子邮件地址。默认是 false.
  • PreferredTextEncoding - 定义消息主题和正文的首选编码。默认是 null.
  • PreserveEmbeddedMessageFormat - 决定是否保留嵌入式消息的格式。默认是 false.
  • PreserveRtfContent - 指定是否在 MailMessage。默认是 false.
  • PreserveTnefAttachments - 管理 TNEF 附件加载行为。默认是 false.
  • RemoveSignature - 决定在加载时是否移除签名。默认是 false.
  • Timeout - 在转换期间限制格式化时间(毫秒),默认是 3000 毫秒。
  • TimeoutReachedHandler - 超时到期时触发的处理程序。

从 TNEF 加载

该 TnefLoadOptions 类提供在加载 TNEF 格式的 EML 文件时管理编码和移除签名的选项。

// Instantiate TnefLoadOptions
TnefLoadOptions loadOptions = new TnefLoadOptions();

loadOptions.setPreferredTextEncoding(StandardCharsets.UTF_8);
loadOptions.setPreserveEmbeddedMessageFormat(true);
loadOptions.setRemoveSignature(true);

// Load the TNEF file
MailMessage tnef = MailMessage.load("file.eml", loadOptions);

TnefLoadOptions 的属性

  • MessageFormat - 表示邮件消息格式,如 EML、MSG 或 MHTML。默认是 EML。该属性在 Java 中为只读。
  • PreferredTextEncoding - 设置消息主题和正文的首选编码。默认是 null.
  • PreserveEmbeddedMessageFormat - 指示是否在加载时保留嵌入式消息的格式。默认是 false.
  • RemoveSignature - 指定在加载时是否移除签名。默认是 false.

在加载期间保留嵌入的消息格式

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

EmlLoadOptions options = new EmlLoadOptions();
options.setPreserveEmbeddedMessageFormat(true);

MailMessage mail = MailMessage.load(dataDir + "tnefWithMsgInside.eml", options);

int fileFormat = FileFormatUtil.detectFileFormat(
        mail.getAttachments().get_Item(0).getContentStream()).getFileFormatType();

System.out.println("Embedded message file format: " + fileFormat);

保存并转换电子邮件消息

Aspose.Email 让将任何消息类型转换为其他格式变得轻松。为演示此功能,本文的代码从磁盘加载三种类型的消息并将它们保存为其他格式。基类 SaveOptions 以及这些类 EmlSaveOptions, MsgSaveOptions, MhtSaveOptions, HtmlSaveOptions 用于保存时的额外设置 MailMessage 可用于将消息保存为其他格式。本文展示了如何使用这些类将示例电子邮件保存为:

  • EML 格式。
  • Outlook MSG。
  • MHTML 格式。
  • HTML 格式。

加载并保存电子邮件消息

以下代码片段演示如何加载 EML 消息并以相同格式保存到磁盘。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

MailMessage msg = MailMessage.load(dataDir + "test.eml", new EmlLoadOptions());

// Save the email message to disk by using the SaveOptions
msg.save(dataDir + "LoadAndSaveFileAsEML_out.eml", SaveOptions.getDefaultEml());

原始消息的边界

当 EML 消息被加载后再次保存为 EML 时,默认会保留源消息的边界,因此无需配置即可保持它们。库的早期版本提供了一个 EmlSaveOptions.PreserveOriginalBoundaries 属性。该属性已被移除,默认行为是保留原始边界。

自定义 MIME 边界

如果需要边界遵循特定模式,请使用 BoundariesTemplate 属性的 EmlSaveOptions 类。它定义用于为保存的消息生成 MIME 边界的模板。默认值为 null,这意味着边界由库生成。模板支持两个通配符:

  • {#} - 边界编号。
  • {guid} - 生成的 GUID。

下面的代码片段演示了如何加载 EML 并以自定义 MIME 边界保存为 EML。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

MailMessage eml = MailMessage.load(dataDir + "test.eml");

// Save as EML with a custom boundary template
EmlSaveOptions emlSaveOptions = new EmlSaveOptions(MailMessageSaveType.getEmlFormat());
emlSaveOptions.setBoundariesTemplate("boundary_{#}_{guid}");

eml.save(dataDir + "CustomBoundaries_out.eml", emlSaveOptions);

保存为 EML,保留 TNEF 附件

以下代码片段展示了如何保存为 EML,同时保留 TNEF 附件。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

MailMessage eml = MailMessage.load(dataDir + "TnefAttachments.eml");

// Save as EML with the TNEF attachments preserved
EmlSaveOptions emlSaveOptions = new EmlSaveOptions(MailMessageSaveType.getEmlFormat());
emlSaveOptions.setFileCompatibilityMode(FileCompatibilityMode.PreserveTnefAttachments);

eml.save(dataDir + "PreserveTNEFAttachment_out.eml", emlSaveOptions);

将 EML 保存为 MSG

下面的代码片段展示了如何加载 EML 消息并使用 SaveOptions.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

// Initialize and load an existing EML file
MailMessage eml = MailMessage.load(dataDir + "test.eml");

// Save the email message to disk in Unicode format
eml.save(dataDir + "LoadingEMLSavingToMSG_out.msg", SaveOptions.getDefaultMsgUnicode());

将 EML 保存为保留日期的 MSG

该 MsgSaveOptions 类允许您将源消息保存为 Outlook 消息文件(MSG),并保留日期。下面的代码片段展示了如何保存带有原始日期的 MSG 消息。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

MailMessage eml = MailMessage.load(dataDir + "test.eml");

// Save as MSG with the original dates preserved
MsgSaveOptions msgSaveOptions = new MsgSaveOptions(MailMessageSaveType.getOutlookMessageFormatUnicode());
msgSaveOptions.setPreserveOriginalDates(true);

eml.save(dataDir + "SavingAsMSGWithPreservedDates_out.msg", msgSaveOptions);

将 EML 保存为 MHTML

可以使用不同的 MHTML 选项来获得期望的结果。以下代码片段展示了如何将 EML 消息加载到 MailMessage 并将其转换为带有 UTC 系统消息日期的 MHTML。

String dataDir = "data/";

// Set options for MHTML output
MhtSaveOptions saveOptions = SaveOptions.getDefaultMhtml();

// Save the message date as a UTC date
saveOptions.setPreserveOriginalDate(false);

// Initialize and load an existing EML file
try (MailMessage mailMessage = MailMessage.load(dataDir + "Message.eml")) {
    mailMessage.save(dataDir + "Message_out.mhtml", saveOptions);
}

从 EML 保存时全局格式化 MHT 头

使用 Aspose.Email,您可以为 MHT 头使用全局格式选项。全局选项为所有 MhtSaveOptions 实例。此功能旨在避免为每个实例设置格式 MhtSaveOptions.

使用以下方法的 GlobalFormattingOptions 类和下面的代码示例用于设置 MHT 头的格式:

// The formatting is set once and applies to every MhtSaveOptions instance created afterwards
GlobalFormattingOptions.setPageHeaderFormat("<div><h1>{0}</h1></div>");
GlobalFormattingOptions.setHeaderFormat("<div>{0}: {1}</div>");
GlobalFormattingOptions.setBeforeHeadersFormat("<div style='font-family:Arial'>");
GlobalFormattingOptions.setAfterHeadersFormat("</div>");

// saveOptions1 and saveOptions2 have the same MHT header formatting
MhtSaveOptions saveOptions1 = new MhtSaveOptions();
MhtSaveOptions saveOptions2 = new MhtSaveOptions();

使用可选设置将 EML 转换为 MHTML

该 MhtSaveOptions 该类提供将电子邮件消息保存为 MHTML 格式的额外选项。枚举 MhtFormatOptions 使得可以将额外的电子邮件信息写入输出 MHTML。可以写入以下附加字段:

  • WriteHeader - 将电子邮件头写入输出文件。
  • WriteOutlineAttachments - 将大纲附件写入输出文件。
  • WriteCompleteEmailAddress - 将完整的电子邮件地址写入输出文件。
  • NoEncodeCharacters - 不应使用字符的传输编码。
  • HideExtraPrintHeader - 隐藏输出文件顶部的额外打印头。
  • WriteCompleteToEmailAddress - 将收件人的完整电子邮件地址写入输出文件。
  • WriteCompleteFromEmailAddress - 将发送者的完整电子邮件地址写入输出文件。
  • WriteCompleteCcEmailAddress - 将所有抄送收件人的完整电子邮件地址写入输出文件。
  • WriteCompleteBccEmailAddress - 将所有密送收件人的完整电子邮件地址写入输出文件。
  • RenderCalendarEvent - 将日历事件的文本写入输出文件。
  • SkipByteOrderMarkInBody - 跳过消息正文中的字节顺序标记(BOM)字节。
  • RenderVCardInfo - 将 VCard 替代视图中的文本写入输出文件。
  • DisplayAsOutlook - 显示 From 标头。
  • RenderTaskFields - 将特定任务字段写入输出文件。
  • 无 - 未指定任何设置。

以下代码片段展示了如何使用可选设置将 EML 文件转换为 MHTML。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

MailMessage eml = MailMessage.load(dataDir + "test.eml");

// Save as MHT with a header
MhtSaveOptions mhtSaveOptions = new MhtSaveOptions();
mhtSaveOptions.setMhtFormatOptions(MhtFormatOptions.WriteHeader | MhtFormatOptions.HideExtraPrintHeader);

eml.save(dataDir + "ConvertingToMHTMLWithOptionalSettings_out.mht", mhtSaveOptions);

在转换为 MHTML 时渲染日历事件

该 MhtFormatOptions.RenderCalendarEvent 选项将日历事件呈现到输出的 MHTML。下面的代码片段展示了在转换为 MHTML 时如何呈现日历事件。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

MailMessage msg = MailMessage.load(dataDir + "Meeting with Recurring Occurrences.msg");

MhtSaveOptions options = new MhtSaveOptions();
options.setMhtFormatOptions(MhtFormatOptions.WriteHeader | MhtFormatOptions.RenderCalendarEvent);

// Format the output details if required - optional.
// set_Item overrides a template, and adds it when it is not in the collection yet.
options.getFormatTemplates().set_Item(MhtTemplateName.START,
        "<span class='headerLineTitle'>Start:</span><span class='headerLineText'>{0}</span><br/>");
options.getFormatTemplates().set_Item(MhtTemplateName.END,
        "<span class='headerLineTitle'>End:</span><span class='headerLineText'>{0}</span><br/>");
options.getFormatTemplates().set_Item(MhtTemplateName.RECURRENCE,
        "<span class='headerLineTitle'>Recurrence:</span><span class='headerLineText'>{0}</span><br/>");
options.getFormatTemplates().set_Item(MhtTemplateName.RECURRENCE_PATTERN,
        "<span class='headerLineTitle'>RecurrencePattern:</span><span class='headerLineText'>{0}</span><br/>");
options.getFormatTemplates().set_Item(MhtTemplateName.ORGANIZER,
        "<span class='headerLineTitle'>Organizer:</span><span class='headerLineText'>{0}</span><br/>");
options.getFormatTemplates().set_Item(MhtTemplateName.REQUIRED_ATTENDEES,
        "<span class='headerLineTitle'>RequiredAttendees:</span><span class='headerLineText'>{0}</span><br/>");

msg.save(dataDir + "Meeting with Recurring Occurrences_out.mhtml", options);

导出电子邮件为 MHT(无内嵌图像)

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

MailMessage eml = MailMessage.load(dataDir + "Message.msg", new MsgLoadOptions());

MhtSaveOptions mhtSaveOptions = new MhtSaveOptions();
mhtSaveOptions.setSkipInlineImages(true);

eml.save(dataDir + "EmlToMhtmlWithoutInlineImages_out.mht", mhtSaveOptions);

使用自定义时区导出电子邮件为 MHT

该 MailMessage class 提供了 setTimeZoneOffset 方法在导出为 MHT 时设置自定义时区。下面的代码片段展示了如何使用自定义时区将电子邮件导出为 MHT。

String dataDir = "data/";

MailMessage msg = MailMessage.load(dataDir + "Message.msg", new MsgLoadOptions());
msg.setDate(new Date());

// Set the time zone offset in milliseconds
msg.setTimeZoneOffset(5 * 60 * 60 * 1000);

MhtSaveOptions mhtOptions = new MhtSaveOptions();
mhtOptions.setMhtFormatOptions(MhtFormatOptions.WriteHeader);

msg.save(dataDir + "ExportToMHTWithCustomTimezone_out.mhtml", mhtOptions);

导出电子邮件为 EML

以下代码片段展示了如何将电子邮件导出为 EML。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

MailMessage eml = MailMessage.load(dataDir + "Message.msg", new MsgLoadOptions());

eml.save(dataDir + "testEml_out.eml", SaveOptions.getDefaultEml());

将电子邮件保存为 HTML

该 HtmlSaveOptions 类允许您将消息正文导出为 HTML。以下代码片段展示了如何将消息保存为 HTML。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

MailMessage msg = MailMessage.load(dataDir + "Message.msg");
msg.save(dataDir + "SavingMessageAsHTML_out1.html", SaveOptions.getDefaultHtml());

// or

MailMessage eml = MailMessage.load(dataDir + "test.eml");

HtmlSaveOptions options = SaveOptions.getDefaultHtml();
options.setHtmlFormatOptions(HtmlFormatOptions.WriteHeader | HtmlFormatOptions.WriteCompleteEmailAddress);

eml.save(dataDir + "SavingMessageAsHTML_out2.html", options);

使用相对路径保存电子邮件为 HTML

在将电子邮件导出为 HTML 格式时,可以选择使用相对路径保存电子邮件资源。此功能在输出 HTML 文件中链接资源的方式上提供了更大的灵活性,使得在不同系统之间共享和显示已保存的电子邮件更加方便。该 HtmlSaveOptions.UseRelativePathToResources 属性提供了使用相对路径保存资源的能力。默认属性值为 false(资源使用绝对路径保存)。设置为 true 时,资源使用相对路径保存。使用相对路径的 HTML 文件更具可移植性,无论托管环境的文件结构如何,都能正确查看。您可以根据需求在绝对路径和相对路径之间选择。您可以使用 ResourceHtmlRenderingHandler 事件。

使用默认相对路径保存资源

String dataDir = "data/";

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

HtmlSaveOptions htmlSaveOptions = new HtmlSaveOptions();
htmlSaveOptions.setResourceRenderingMode(ResourceRenderingMode.SaveToFile);
htmlSaveOptions.setUseRelativePathToResources(true);

msg.save(dataDir + "target.html", htmlSaveOptions);

在这种情况下,资源保存在 [html file name].files 文件夹中,路径与 .html 文件相同,HTML 通过相对路径引用资源。

使用绝对路径保存资源

String dataDir = "data/";

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

HtmlSaveOptions htmlSaveOptions = new HtmlSaveOptions();
htmlSaveOptions.setResourceRenderingMode(ResourceRenderingMode.SaveToFile);
htmlSaveOptions.setUseRelativePathToResources(false);

msg.save(dataDir + "target.html", htmlSaveOptions);

如第一种情况,资源保存在 [html file name].files 默认情况下使用文件夹,但 HTML 使用绝对路径引用资源。

使用 ResourceHtmlRenderingHandler 事件的自定义相对路径

String dataDir = "data/";

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

HtmlSaveOptions htmlSaveOptions = new HtmlSaveOptions();
htmlSaveOptions.setResourceRenderingMode(ResourceRenderingMode.SaveToFile);
htmlSaveOptions.setUseRelativePathToResources(true);

htmlSaveOptions.setResourceHtmlRenderingHandler(new ResourceHtmlRenderingHandler() {
    @Override
    public void invoke(Object sender, ResourceHtmlRenderingEventArgs args) {
        if (sender instanceof AttachmentBase) {
            AttachmentBase attachment = (AttachmentBase) sender;
            // UseRelativePathToResources is true, so assign a relative path to PathToResourceFile
            args.setPathToResourceFile("images/" + attachment.getContentType().getName());
        }
    }
});

msg.save(dataDir + "A Day in the Park.html", htmlSaveOptions);

通过使用 ResourceHtmlRenderingHandler 事件,您可以为资源设置自定义的相对或绝对路径。在使用 ResourceHtmlRenderingHandler 事件处理程序,分配相对路径给 PathToResourceFile 属性时 UseRelativePathToResources 设置为 true 时使用相对路径,设置为 false 时使用绝对路径,以确保正确引用。

在将消息转换为 HTML 时保留自定义图标

有时消息包含内联附件,这些附件在邮件正文中显示为图标图像。此类消息在转换为 HTML 时可能会出现问题,因为图标图像会丢失。这是因为附件图标并未直接保存在邮件中。

Aspose.Email 让您在将邮件转换为 HTML 时自定义附件的图标。该 ResourceHtmlRenderingHandler 事件用于在将电子邮件保存为 HTML 文件时自定义资源文件(如附件)的呈现方式。在下面的代码示例中,事件处理程序根据附件的内容类型动态设置资源文件(图标)的路径。这使得可以根据文件类型在 HTML 输出中自定义资源的呈现。

String dataDir = "data/";

HtmlSaveOptions options = new HtmlSaveOptions();

options.setResourceHtmlRenderingHandler(new ResourceHtmlRenderingHandler() {
    @Override
    public void invoke(Object sender, ResourceHtmlRenderingEventArgs e) {
        AttachmentBase attachment = (AttachmentBase) sender;
        String name = attachment.getContentType().getName();

        e.setCaption(name);

        if (name.endsWith(".pdf")) {
            e.setPathToResourceFile("pdf_icon.png");
        } else if (name.endsWith(".docx")) {
            e.setPathToResourceFile("word_icon.jpg");
        } else if (name.endsWith(".jpg")) {
            e.setPathToResourceFile("jpeg_icon.png");
        } else {
            e.setPathToResourceFile("not_found_icon.png");
        }
    }
});

options.setResourceRenderingMode(ResourceRenderingMode.SubstituteFromFile);

MailMessage mailMessage = MailMessage.load(dataDir + "message.msg");
mailMessage.save(dataDir + "message.html", options);

在将 EML 保存为 HTML 时设置时间和时区

Aspose.Email 用户可以在中设置时间和时区显示格式 HtmlSaveOptions。该 HeadersFormattingOptions 类允许您在将 MailMessage 保存为 MHTML 或 HTML 格式时指定标题格式选项。以下常量的 HtmlFormatOptions 类指定要在输出文件中显示的字段:

以下代码示例展示了在将 EML 保存为 HTML 时如何设置时间和时区:

String dataDir = "data/";

MailMessage msg = MailMessage.load(dataDir + "Message.eml");

HtmlSaveOptions options = new HtmlSaveOptions();
options.setHtmlFormatOptions(HtmlFormatOptions.WriteHeader);
options.getFormatTemplates().set_Item(MhtTemplateName.DATE_TIME, "MM d yyyy HH:mm tt");

msg.save(dataDir + "Message_out.html", options);

以不嵌入资源的方式保存为 HTML

默认情况下,消息的资源会作为数据 URI 嵌入输出 HTML。设置 ResourceRenderingMode 到 ResourceRenderingMode.SaveToFile 将它们写为 HTML 旁边的独立文件。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

MailMessage eml = MailMessage.load(dataDir + "EmailWithAttandEmbedded.eml");

HtmlSaveOptions options = new HtmlSaveOptions();

// Write the resources next to the HTML file instead of embedding them into it
options.setResourceRenderingMode(ResourceRenderingMode.SaveToFile);
options.setUseRelativePathToResources(true);

eml.save(dataDir + "EmailWithAttandEmbedded_out.html", options);

将消息保存为 Outlook 模板(.oft)文件

Outlook 模板是一种 MAPI 级别的格式,因此消息会被转换为 MapiMessage 先写入,然后再写入 saveAsTemplate的文件。以下代码片段演示如何将消息保存为 Outlook 模板(.oft)文件。

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-Java
String dataDir = "data/";

MailMessage eml = new MailMessage("test@from.to", "test@to.to", "template subject", "Template body");

// An Outlook template is a MAPI-level format, so convert the message first
MapiMessage msg = MapiMessage.fromMailMessage(eml);
msg.saveAsTemplate(dataDir + "EmlAsOft_out.oft");