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 - 각 형식마다 자체적인 항목을 추가합니다:
| Class | Format | Additional settings | | — | — | — | | 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());
winmail.dat 파일. 단순히 해당 첨부 파일만을 포함하는 일반 메시지는 자체 형식 옵션으로 로드되며, 다음과 같이 표시됩니다 TNEF 첨부 파일 작업.
임베디드 메시지 형식 보존
메시지로 첨부된 항목은 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 첨부 파일 및 경계 보존 등을 포함한 고급 저장 매개변수를 지정합니다.
사용 가능한 저장 옵션은 다음과 같습니다:
EmlSaveOptionsMsgSaveOptionsMhtSaveOptionsHtmlSaveOptions
이메일을 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 on 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()));
}
Convert EML to 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 on 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에 리소스를 기록하는 방식을 제어
When a message is exported to HTML, its inline images are embedded as base64 data by default. 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 두 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()));