使用 Aspose.Email for C++ 加载和保存电子邮件

Aspose.Email for C++ 提供灵活的选项来加载、保存和转换多种格式的电子邮件,包括 EML、MSG、MHTML 和 HTML。您还可以自定义加载和保存选项,以处理编码、附件和格式要求。

本文中的示例使用了以下头文件和名称空间:

#include <MailMessage.h>
#include <EmlLoadOptions.h>
#include <EmlxLoadOptions.h>
#include <HtmlLoadOptions.h>
#include <MhtmlLoadOptions.h>
#include <MsgLoadOptions.h>
#include <TnefLoadOptions.h>
#include <SaveOptions.h>
#include <EmlSaveOptions.h>
#include <MsgSaveOptions.h>
#include <MhtSaveOptions.h>
#include <HtmlSaveOptions.h>
#include <MailMessageSaveType.h>
#include <MhtFormatOptions.h>
#include <HtmlFormatOptions.h>
#include <MhtTemplateName.h>
#include <system/collections/specialized/string_dictionary.h>
#include <ResourceRenderingMode.h>
#include <FileCompatibilityMode.h>
#include <AttachmentCollection.h>
#include <Attachment.h>
#include <Mapi/MapiMessage.h>
#include <Mapi/MapiConversionOptions.h>
#include <Mapi/OutlookMessageFormat.h>
#include <Tools/FileFormat/FileFormatUtil.h>
#include <Tools/FileFormat/FileFormatInfo.h>
#include <Tools/FileFormat/FileFormatType.h>
#include <system/io/file.h>
#include <system/io/directory.h>
#include <system/io/file_info.h>
#include <system/text/encoding.h>
#include <system/object_ext.h>
#include <system/convert.h>
#include <system/timezone_info.h>
#include <system/timespan.h>

using namespace System;
using namespace Aspose::Email;
using namespace Aspose::Email::Mapi;
using namespace Aspose::Email::Tools;

使用自定义加载选项加载邮件

该 MailMessage 类加载 EML、EMLX、MSG、MHTML、HTML 和 TNEF 格式的消息。每种输入格式都有其自己的 LoadOptions,并且该对象被传递给 MailMessage::Load 以及文件名或流。基类为所有这些贡献了三个设置 - PreferredTextEncoding 用于没有声明字符集的文本, PreserveEmbeddedMessageFormat 用于作为消息附加的项目,以及 RemoveSignature - 同时每种格式都有其自己的:

| 类别 | 格式 | 附加设置 | | — | — | — | | EmlLoadOptions | EML | PreserveTnefAttachments | | EmlxLoadOptions | EMLX (Apple Mail) | - | | HtmlLoadOptions | HTML | PathToResources, ShouldAddPlainTextView | | MhtmlLoadOptions | MHTML | PreserveTnefAttachments | | MsgLoadOptions | Outlook MSG | KeepOriginalEmailAddresses, PreserveRtfContent, PreserveTnefAttachments, 超时 | | TnefLoadOptions | 原始 TNEF (winmail.dat) | - |

// EML
SharedPtr<EmlLoadOptions> emlOptions = MakeObject<EmlLoadOptions>();
emlOptions->set_PreferredTextEncoding(System::Text::Encoding::get_UTF8()); // encoding for subject and body
emlOptions->set_PreserveEmbeddedMessageFormat(true);                       // keep embedded items as they are
emlOptions->set_PreserveTnefAttachments(true);                             // keep winmail.dat parts
emlOptions->set_RemoveSignature(false);                                    // keep the S/MIME signature
SharedPtr<MailMessage> eml = MailMessage::Load(u"sample.eml", emlOptions);

// EMLX (Apple Mail)
SharedPtr<EmlxLoadOptions> emlxOptions = MakeObject<EmlxLoadOptions>();
emlxOptions->set_PreferredTextEncoding(System::Text::Encoding::get_UTF8());
emlxOptions->set_PreserveEmbeddedMessageFormat(true);
SharedPtr<MailMessage> emlx = MailMessage::Load(u"sample.emlx", emlxOptions);

// HTML
SharedPtr<HtmlLoadOptions> htmlOptions = MakeObject<HtmlLoadOptions>();
htmlOptions->set_PathToResources(u".");        // where the referenced images live
htmlOptions->set_ShouldAddPlainTextView(true); // add a text/plain alternative
SharedPtr<MailMessage> fromHtml = MailMessage::Load(u"body_content.html", htmlOptions);

// MHTML
SharedPtr<MhtmlLoadOptions> mhtmlOptions = MakeObject<MhtmlLoadOptions>();
mhtmlOptions->set_PreserveTnefAttachments(true);
SharedPtr<MailMessage> fromMhtml = MailMessage::Load(u"sample.mhtml", mhtmlOptions);

// MSG
SharedPtr<MsgLoadOptions> msgOptions = MakeObject<MsgLoadOptions>();
msgOptions->set_KeepOriginalEmailAddresses(true); // do not rewrite Exchange addresses
msgOptions->set_PreserveRtfContent(true);         // keep the RTF body
msgOptions->set_Timeout(5000);                    // formatting time limit, milliseconds
SharedPtr<MailMessage> fromMsg = MailMessage::Load(u"sample.msg", msgOptions);

// TNEF - a raw winmail.dat file, not a message that contains one
SharedPtr<TnefLoadOptions> tnefOptions = MakeObject<TnefLoadOptions>();
tnefOptions->set_PreferredTextEncoding(System::Text::Encoding::get_UTF8());
SharedPtr<MailMessage> fromTnef = MailMessage::Load(u"winmail.dat", tnefOptions);

Console::WriteLine(u"Subjects: " + eml->get_Subject() + u" | " + emlx->get_Subject() +
    u" | " + fromMsg->get_Subject() + u" | " + fromTnef->get_Subject());

保留嵌入消息的格式

作为消息附加的项目可以存储为 MSG 或 EML。使用 PreserveEmbeddedMessageFormat 附件保持在源文件中的格式,而不是被转换为:

SharedPtr<EmlLoadOptions> options = MakeObject<EmlLoadOptions>();
options->set_PreserveEmbeddedMessageFormat(true);

SharedPtr<MailMessage> mail = MailMessage::Load(u"tnefWithMsgInside.eml", options);

// the embedded item keeps the format it had in the source message
FileFormatType fileFormat = FileFormatUtil::DetectFileFormat(
    mail->get_Attachments()->idx_get(0)->get_ContentStream())->get_FileFormatType();

Console::WriteLine(u"Embedded message file format: " + ObjectExt::ToString(fileFormat));

已签名消息和文件格式检测

解析消息时会保留签名。 RemoveSignature 请求库将其删除,并且 FileFormatUtil::DetectFileFormat 在加载之前报告文件的实际类型——当扩展名不可靠时非常有用。

// a signature is kept by default
SharedPtr<MailMessage> signedMessage = MailMessage::Load(u"signed.eml");
Console::WriteLine(u"IsSigned: " + Convert::ToString(signedMessage->get_IsSigned()) +
    u", IsEncrypted: " + Convert::ToString(signedMessage->get_IsEncrypted()));

// RemoveSignature strips it while the message is parsed
SharedPtr<EmlLoadOptions> options = MakeObject<EmlLoadOptions>();
options->set_RemoveSignature(true);
SharedPtr<MailMessage> unsigned_ = MailMessage::Load(u"signed.eml", options);
Console::WriteLine(u"After RemoveSignature: " + Convert::ToString(unsigned_->get_IsSigned()));

// the format of a file can be detected before it is loaded
SharedPtr<FileFormatInfo> info = FileFormatUtil::DetectFileFormat(u"Message.msg");
Console::WriteLine(u"The message format is: " + ObjectExt::ToString(info->get_FileFormatType()));

以不同格式保存电子邮件

Aspose.Email for C++ 能够在 EML、MSG、MHTML 和 HTML 等格式之间转换消息。开发者可以使用 SaveOptions 类层次结构用于指定高级保存参数,包括编码、TNEF 附件和边界保留。

可用的保存选项包括:

  • EmlSaveOptions
  • MsgSaveOptions
  • MhtSaveOptions
  • HtmlSaveOptions

将邮件保存为 EML

MailMessage::Save 与 SaveOptions::get_DefaultEml 将消息写入 EML 文件。示例加载 EML 消息并以相同格式保存。

SharedPtr<MailMessage> mailMessage = MailMessage::Load(u"Attachments.eml");
mailMessage->Save(u"Attachments_copy.eml", SaveOptions::get_DefaultEml());

Console::WriteLine(u"Attachments in the copy: " + Convert::ToString(MailMessage::Load(u"Attachments_copy.eml")->get_Attachments()->get_Count()));

保留原始 EML 边界

MIME 边界用于分隔消息的各部分。当加载 EML 消息并再次保存为 EML 时,会保留源的边界,以便可以逐部分与原文件进行比较;不需要选项。自定义边界通过模板设置,如在 自定义 MIME 边界.

SharedPtr<MailMessage> mailMessage = MailMessage::Load(u"Attachments.eml");

SharedPtr<EmlSaveOptions> emlSaveOptions = MakeObject<EmlSaveOptions>(MailMessageSaveType::get_EmlFormat());
mailMessage->Save(u"PreservedBoundaries.eml", emlSaveOptions);

// the first boundary of the source file and of the saved file
auto firstBoundary = [](String path)
{
    String text = IO::File::ReadAllText(path);
    int32_t start = text.IndexOf(u"boundary=\"") + 10;
    return text.Substring(start, text.IndexOf(u'"', start) - start);
};
Console::WriteLine(u"Source: " + firstBoundary(u"Attachments.eml"));
Console::WriteLine(u"Saved:  " + firstBoundary(u"PreservedBoundaries.eml"));

在 EML 中保留 TNEF 附件

带有 TNEF 部分的消息(winmail.dat) 通常在保存时被重新写成普通 MIME。设置 FileCompatibilityMode::PreserveTnefAttachments 在 EmlSaveOptions 保持 TNEF 部分原样,因此依赖它的客户端——尤其是 Outlook——仍能找到其数据。有关 TNEF 消息的更多信息请参见 处理 TNEF 附件.

SharedPtr<MailMessage> mailMessage = MailMessage::Load(u"tnefEml1.eml");

SharedPtr<EmlSaveOptions> emlSaveOptions = MakeObject<EmlSaveOptions>(MailMessageSaveType::get_EmlFormat());
emlSaveOptions->set_FileCompatibilityMode(FileCompatibilityMode::PreserveTnefAttachments);
mailMessage->Save(u"PreservedTnef.eml", emlSaveOptions);

// the TNEF part is still there
SharedPtr<EmlLoadOptions> loadOptions = MakeObject<EmlLoadOptions>();
loadOptions->set_PreserveTnefAttachments(true);
for (SharedPtr<Attachment> attachment : MailMessage::Load(u"PreservedTnef.eml", loadOptions)->get_Attachments())
{
    Console::WriteLine(attachment->get_Name() + u" - TNEF: " + Convert::ToString(attachment->get_IsTnef()));
}

将 EML 转换为 MSG

将 EML 文件保存为 Outlook MSG 文件时使用 SaveOptions::get_DefaultMsgUnicode - 当前 Outlook 版本使用的 Unicode MSG 格式 - 或者使用 get_DefaultMsg 用于较旧的 ANSI 变体。

SharedPtr<MailMessage> eml = MailMessage::Load(u"Message.eml");
eml->Save(u"FromEml.msg", SaveOptions::get_DefaultMsgUnicode());

Console::WriteLine(u"Saved as MSG: " + MapiMessage::Load(u"FromEml.msg")->get_Subject());

保存为 MHTML

SaveOptions::get_DefaultMhtml 生成单个 MHTML 文件,浏览器即可显示,其中消息标题写在正文上方,图像已嵌入。

SharedPtr<MailMessage> eml = MailMessage::Load(u"Message.eml");
eml->Save(u"FromEml.mhtml", SaveOptions::get_DefaultMhtml());

使用自定义时区导出为 MHT

写入 MHTML 页面标题的日期会根据 TimeZoneOffset。将其设置为本地系统的偏移以显示本地时间,或设置为任意固定偏移; MhtFormatOptions::WriteHeader 确保写入带日期的标题。

SharedPtr<MailMessage> eml = MailMessage::Load(u"Message.eml");

// the offset of the local system ...
eml->set_TimeZoneOffset(TimeZoneInfo::get_Local()->GetUtcOffset(DateTime::get_Now()));

// ... or any fixed offset, here UTC-08:00
eml->set_TimeZoneOffset(TimeSpan(-8, 0, 0));

SharedPtr<MhtSaveOptions> options = MakeObject<MhtSaveOptions>();
options->set_MhtFormatOptions(MhtFormatOptions::WriteHeader);
eml->Save(u"CustomTimeZone.mhtml", options);

导出邮件为 EML

从其他格式加载的消息以相同方式导出为 EML。示例将 Outlook MSG 文件转换。

SharedPtr<MailMessage> msg = MailMessage::Load(u"Message.msg");
msg->Save(u"ExportedFromMsg.eml", SaveOptions::get_DefaultEml());

Console::WriteLine(u"Exported: " + MailMessage::Load(u"ExportedFromMsg.eml")->get_Subject());

自定义 MIME 边界

在加载 EML 文件并重新保存时会保留源消息的边界。若要改用自定义模式生成,请设置 BoundariesTemplate 在 EmlSaveOptions。支持两个占位符: {#} 用于边界编号并且 {guid} 为生成的 GUID。

SharedPtr<MailMessage> mailMessage = MailMessage::Load(u"Attachments.eml");

SharedPtr<EmlSaveOptions> emlSaveOptions = MakeObject<EmlSaveOptions>(MailMessageSaveType::get_EmlFormat());

// {#} is replaced with the boundary number, {guid} with a generated GUID
emlSaveOptions->set_BoundariesTemplate(u"boundary_{#}_{guid}");

mailMessage->Save(u"CustomBoundaries.eml", emlSaveOptions);

Console::WriteLine(IO::File::ReadAllText(u"CustomBoundaries.eml").Substring(0, 300));

当目标格式为 MHTML 时,使用 MhtSaveOptions::PreserveOriginalBoundaries.

保留原始日期并保存为模板

默认情况下,转换为 MSG 时会标记当前时间。 PreserveOriginalDates 则保持源消息的日期。Outlook 模板格式(.oft) 有其自带的预设选项集, SaveOptions::DefaultOft.

SharedPtr<MailMessage> eml = MailMessage::Load(u"Attachments.eml");

// keep the dates of the source message instead of stamping the current time
SharedPtr<MsgSaveOptions> msgSaveOptions = MakeObject<MsgSaveOptions>(MailMessageSaveType::get_OutlookMessageFormatUnicode());
msgSaveOptions->set_PreserveOriginalDates(true);
eml->Save(u"PreservedDates.msg", msgSaveOptions);

// an Outlook template (.oft) is written with the dedicated save type
eml->Save(u"AsTemplate.oft", SaveOptions::get_DefaultOft());

Console::WriteLine(u"msg: " + Convert::ToString(MakeObject<IO::FileInfo>(u"PreservedDates.msg")->get_Length()) +
    u" bytes, oft: " + Convert::ToString(MakeObject<IO::FileInfo>(u"AsTemplate.oft")->get_Length()) + u" bytes");

MHTML 输出选项

MhtSaveOptions 塑造 MHTML 输出。 MhtFormatOptions 是决定渲染内容的标志枚举: WriteHeader 将标题块写在正文上方, RenderCalendarEvent 添加会议的详细信息, RenderVCardInfo 联系人的那些, RenderTaskFields 任务的那些,以及 WriteComplete...EmailAddress 成员打印完整地址而不是显示名称。各个标题行通过模板格式化,这些模板由以下名称指定 MhtTemplateName.

SharedPtr<MailMessage> msg = MailMessage::Load(u"Meeting_with_Recurring_Occurrences.msg");

// render the calendar event together with the header block
SharedPtr<MhtSaveOptions> options = MakeObject<MhtSaveOptions>();
options->set_MhtFormatOptions(MhtFormatOptions::WriteHeader | MhtFormatOptions::RenderCalendarEvent);

// the header lines can be reformatted through their templates
options->get_FormatTemplates()->idx_set(MhtTemplateName::Start,
    u"<span class='headerLineTitle'>Start:</span><span class='headerLineText'>{0}</span><br/>");

msg->Save(u"MeetingWithEvent.mhtml", options);

// leave the inline images out of the output
SharedPtr<MhtSaveOptions> withoutImages = MakeObject<MhtSaveOptions>();
withoutImages->set_SkipInlineImages(true);
SharedPtr<MailMessage> eml = MailMessage::Load(u"EmailWithAttachEmbedded.eml");
eml->Save(u"NoInlineImages.mhtml", withoutImages);

// keep the MIME boundaries of the source message
SharedPtr<MhtSaveOptions> keepBoundaries = MakeObject<MhtSaveOptions>();
keepBoundaries->set_PreserveOriginalBoundaries(true);
eml->Save(u"OriginalBoundaries.mhtml", keepBoundaries);

调整输出的字体

库写入 MHTML 的 CSS 块可作为 CssStyles 字符串并且可以在保存前进行扩展:

SharedPtr<MailMessage> eml = MailMessage::Load(u"Attachments.eml");

SharedPtr<MhtSaveOptions> options = SaveOptions::get_DefaultMhtml();

// the CSS block that Aspose.Email writes into the MHTML can be extended
int32_t cssInsertPos = options->get_CssStyles().LastIndexOf(u"</style>");
options->set_CssStyles(options->get_CssStyles().Insert(cssInsertPos, u".PlainText{ font-family: sans-serif; }"));

eml->Save(u"CustomFont.mhtml", options);

控制资源写入 HTML 的方式

当消息导出为 HTML 时,默认情况下其内联图像会作为 base64 数据嵌入。 ResourceRenderingMode 更改该设置: SaveToFile 将每个资源写入 HTML 文件旁的文件夹,并将路径写入 src 属性, SubstituteFromFile 用您自己的图标替换资源,并且 None 将资源完全删除。 PathToHtmlFile 告诉库该文件夹所属位置,并且 UseRelativePathToResources 将相对路径写入标记。

SharedPtr<MailMessage> msg = MailMessage::Load(u"EmailWithAttachEmbedded.eml");

SharedPtr<HtmlSaveOptions> options = MakeObject<HtmlSaveOptions>();

// write the inline images next to the HTML file instead of embedding them as base64
options->set_ResourceRenderingMode(ResourceRenderingMode::SaveToFile);
options->set_PathToHtmlFile(u"HtmlExport.html");
options->set_UseRelativePathToResources(true);

// include the header block in the body
options->set_HtmlFormatOptions(HtmlFormatOptions::WriteHeader);

msg->Save(u"HtmlExport.html", options);

for (String f : IO::Directory::GetFiles(u".", u"HtmlExport*"))
{
    Console::WriteLine(IO::Path::GetFileName(f));
}

将 MailMessage 转换为 MapiMessage

PST 和 OLM 存储,以及 Outlook 本身,使用 MAPI 项目。 MapiMessage::FromMailMessage 执行转换,并且 MapiConversionOptions 控制其细节:

| 属性 | 含义 | | — | — | | Format | OutlookMessageFormat Unicode 或 Ascii. | | PreserveOriginalDates | 保持源消息的日期。 | | PreserveOriginalAddresses | 不将地址重写为 Exchange 形式。 | | PreserveEmbeddedMessageFormat | 保持附件消息的原始格式。 | | UseBodyCompression | 将 RTF 正文压缩存储。 | | RemoveSignature | 在转换期间删除 S/MIME 签名。 | | ForcedRtfBodyForAppointment | 对于约会始终写入 RTF 正文。 |

ASCII格式 和 UnicodeFormat 返回为两种 Outlook 格式准备好的选项集。

SharedPtr<MailMessage> eml = MailMessage::Load(u"Attachments.eml");

SharedPtr<MapiConversionOptions> options = MakeObject<MapiConversionOptions>();
options->set_Format(OutlookMessageFormat::Unicode);  // Unicode or Ascii
options->set_PreserveOriginalDates(true);            // keep the dates of the source message
options->set_PreserveOriginalAddresses(true);        // do not rewrite the addresses
options->set_PreserveEmbeddedMessageFormat(true);    // keep embedded items in their own format
options->set_UseBodyCompression(true);               // compress the RTF body

SharedPtr<MapiMessage> mapi = MapiMessage::FromMailMessage(eml, options);
mapi->Save(u"ConvertedWithOptions.msg");

// ready-made option sets for the two Outlook formats
SharedPtr<MapiMessage> unicode = MapiMessage::FromMailMessage(eml, MapiConversionOptions::get_UnicodeFormat());
SharedPtr<MapiMessage> ascii = MapiMessage::FromMailMessage(eml, MapiConversionOptions::get_ASCIIFormat());

Console::WriteLine(u"Unicode body: " + Convert::ToString(unicode->get_Body().get_Length()) +
    u", ASCII body: " + Convert::ToString(ascii->get_Body().get_Length()));