טעינה ושמירה של הודעות אימייל באמצעות Aspose.Email ל‑C++
Aspose.Email ל‑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 | 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 ל‑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"));
שימור קבצים מצורפים בפורמט TNEF ב‑EML
הודעה שהגיעה עם חלק 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()));
}
Convert EML to MSG
קובץ EML הופך לקובץ Outlook MSG כאשר נשמר עם SaveOptions::get_DefaultMsgUnicode - פורמט MSG ב-Unicode המשמש גרסאות Outlook נוכחיות - או עם 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);
התאמת הגופנים של הפלט
חלק ה-CSS שהספרייה כותבת לתוך ה-MHTML זמין כ- 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, תמונות inline משובצות כנתוני 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 מחזירה קבוצות אפשרויות מוכנות לשני פורמטי 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()));