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 ファイル名またはストリームと共に。基底クラスはすべてに対して3つの設定を提供します - PreferredTextEncoding 宣言された文字セットのないテキスト用、 PreserveEmbeddedMessageFormat メッセージとして添付された項目用、そして RemoveSignature - 各フォーマットはそれぞれ以下を追加します:

| クラス | フォーマット | 追加設定 | | — | — | — | | EmlLoadOptions | EML | PreserveTnefAttachments | | EmlxLoadOptions | EMLX (Apple Mail) | - | | HtmlLoadOptions | HTML | PathToResources, ShouldAddPlainTextView | | MhtmlLoadOptions | MHTML | PreserveTnefAttachments | | MsgLoadOptions | Outlook MSG | KeepOriginalEmailAddresses, PreserveRtfContent, PreserveTnefAttachments, タイムアウト | | TnefLoadOptions | raw 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 部分をそのまま保持するため、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。2 つのプレースホルダーがサポートされています: {#} 境界番号用に、そして {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本文を書き込む |

ASCIIFormat および UnicodeFormat 2つの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()));