Manage Attachments in Outlook MSG Files

Aspose.Email for C++ provides a rich API for accessing, saving, removing, and embedding attachments when working with Microsoft Outlook MSG files. Attachments are handled through the MapiMessage class, using its Attachments property, which exposes a MapiAttachmentCollection.

Save Attachments from an MSG File

To extract and save attachments from an MSG file:

  1. Load the message using MapiMessage::Load.
  2. Iterate through the MapiAttachmentCollection.
  3. Save each attachment using the MapiAttachment::Save() method.
// 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());
    }
}

Remove Attachments

Aspose.Email for C++ offers two ways to remove attachments from MSG files:

It takes the path of the message file as a parameter. It is implemented as a public static method, so you don’t need to instantiate the object. This static helper method removes all attachments from a message file.

The following code snippet shows how to use this method.

It works faster because it removes attachments without fully parsing the MSG file.

Add MSG Attachments

MSG files can contain other MSG files either as standard or embedded attachments. Use the overloaded Add methods in MapiAttachmentCollection to embed Outlook messages.

The following code sample demonstrates how to create a new MAPI message with specified sender, recipient, subject, and body, then attach an existing MSG file as an embedded message, and finally save the resulting message with the embedded attachment to a new MSG file.

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");