จัดการไฟล์แนบในไฟล์ Outlook MSG
Aspose.Email for C++ มี API ที่ครอบคลุมสำหรับการเข้าถึง, บันทึก, ลบ, และฝังไฟล์แนบเมื่อทำงานกับไฟล์ Microsoft Outlook MSG. ไฟล์แนบถูกจัดการผ่าน MapiMessage คลาส, ด้วยการใช้ Attachments คุณสมบัติ, ซึ่งให้การเข้าถึง MapiAttachmentCollection.
บันทึกไฟล์แนบจากไฟล์ MSG
เพื่อดึงและบันทึกไฟล์แนบจากไฟล์ MSG:
- โหลดข้อความโดยใช้ MapiMessage::Load.
- วนซ้ำผ่าน MapiAttachmentCollection.
- บันทึกไฟล์แนบแต่ละไฟล์โดยใช้ MapiAttachment::Save() เมธอด.
// Create an instance of MapiMessage from file
System::SharedPtr<MapiMessage> message = MapiMessage::Load(fileName);
// Iterate through the attachments collection
{
auto attachment_enumerator = (message->get_Attachments())->GetEnumerator();
decltype(attachment_enumerator->get_Current()) attachment;
while (attachment_enumerator->MoveNext() && (attachment = attachment_enumerator->get_Current(), true))
{
// Save the individual attachment
attachment->Save(dataDir + attachment->get_FileName());
}
}
ลบไฟล์แนบ
Aspose.Email for C++ มีสองวิธีในการลบไฟล์แนบจากไฟล์ MSG:
- เรียกใช้ RemoveAttachments() เมธอด
มันรับพาธของไฟล์ข้อความเป็นพารามิเตอร์. ถูกทำเป็นเมธอดสาธารณะแบบ static, ดังนั้นคุณไม่ต้องสร้างอินสแตนซ์ของอ็อบเจ็กต์. เมธอดช่วยเหลือแบบ static นี้จะลบไฟล์แนบทั้งหมดจากไฟล์ข้อความ.
โค้ดส่วนนี้แสดงวิธีใช้เมธอดนี้.
- เรียกใช้ DestoryAttachment() เมธอด
มันทำงานเร็วขึ้นเพราะลบไฟล์แนบโดยไม่ต้องพาร์เซไฟล์ MSG อย่างเต็มที่.
เพิ่มไฟล์แนบ MSG
ไฟล์ MSG สามารถบรรจุไฟล์ MSG อื่นในรูปแบบไฟล์แนบมาตรฐานหรือฝัง. ใช้ฟังก์ชัน overload Add เมธอดใน MapiAttachmentCollection เพื่อฝังข้อความ Outlook.
ตัวอย่างโค้ดต่อไปนี้แสดงวิธีสร้างข้อความ MAPI ใหม่โดยกำหนดผู้ส่ง, ผู้รับ, เรื่อง, และเนื้อหา, จากนั้นแนบไฟล์ MSG ที่มีอยู่เป็นข้อความฝัง, และสุดท้ายบันทึกข้อความที่ได้พร้อมไฟล์แนบฝังเป็นไฟล์ MSG ใหม่.
System::SharedPtr<MapiMessage> message = System::MakeObject<MapiMessage>(L"from@test.com", L"to@test.com", L"Subj", L"This is a message body");
System::SharedPtr<MapiMessage> attachMsg = MapiMessage::Load(L"Message.msg");
message->get_Attachments()->Add(L"Weekly report.msg", attachMsg);
message->Save(dataDir + L"WithEmbeddedMsg_out.msg");