File SDK - Process email .msg files (C++)

The File SDK supports labeling operations for .msg files in the same manner as any other file type, except that the SDK needs the application to enable the MSG feature flag. This quickstart shows how to set this flag.

As discussed previously, instantiating mip::FileEngine requires the mip::FileEngineSettings settings object. The application uses FileEngineSettings to pass custom settings for a particular instance. The CustomSettings property of mip::FileEngineSettings sets the enable_msg_file_type flag to enable processing of .msg files.

Prerequisites

If you haven't already, be sure to complete the following prerequisites before continuing:

Prerequisite implementation steps

  1. Open the Visual Studio solution you created in the previous "Quickstart: Client application initialization (C++)" article.

  2. Create a PowerShell script to generate access tokens, as explained in Quickstart: List sensitivity labels (C++).

  3. Implement an observer class to monitor mip::FileHandler, as explained in Quickstart: Set/get sensitivity labels (C++).

Set enable_msg_file_type and use File SDK to label .msg file

Add the following file engine construction code to set the enable_msg_file_type flag and use the file engine to label a .msg file.

  1. In Solution Explorer, open the .cpp file in your project that contains the implementation of the main() method. It defaults to the same name as the project containing it, which you specified during project creation.

  2. Add the following #include and using directives after the corresponding existing directives, at the top of the file:

    #include "filehandler_observer.h" 
    #include "mip/file/file_handler.h" 
    #include <iostream>    
    using mip::FileHandler;   
    using std::endl;
    
  3. Remove the implementation of the main() function from the previous quickstart. Inside the main() body, insert the following code. In the following code block, the file engine creation sets the enable_msg_file_type flag. mip::FileHandler objects created by using the file engine can then process a .msg file.

int main()
{
    // Construct/initialize objects required by the application's profile object
    ApplicationInfo appInfo { "<application-id>",                    // ApplicationInfo object (App ID, name, version)
                              "<application-name>", 
                              "1.0" 
    };

    std::shared_ptr<mip::MipConfiguration> mipConfiguration = std::make_shared<mip::MipConfiguration>(appInfo,
				                                                                                       "mip_data",
                                                                                        			   mip::LogLevel::Trace,
                                                                                                       false,
                                                                                                       mip::CacheStorageType::OnDisk);

    std::shared_ptr<mip::MipContext> mMipContext = mip::MipContext::Create(mipConfiguration);

    auto profileObserver = make_shared<ProfileObserver>();                      // Observer object
    auto authDelegateImpl = make_shared<AuthDelegateImpl>("<application-id>");  // Authentication delegate object (App ID)
    auto consentDelegateImpl = make_shared<ConsentDelegateImpl>();              // Consent delegate object

    // Construct/initialize profile object
    FileProfile::Settings profileSettings(mMipContext, mip::CacheStorageType::OnDisk,
        consentDelegateImpl, profileObserver);

    // Set up promise/future connection for async profile operations; load profile asynchronously
    auto profilePromise = make_shared<promise<shared_ptr<FileProfile>>>();
    auto profileFuture = profilePromise->get_future();
    try
    {
        mip::FileProfile::LoadAsync(profileSettings, profilePromise);
    }
    catch (const std::exception& e)
    {
        std::cout << "An exception occurred. Are the Settings and ApplicationInfo objects populated correctly?\n\n"<< e.what() << "'\n";
        system("pause");
        return 1;
    }

    auto profile = profileFuture.get();

    // Construct/initialize engine object
    FileEngine::Settings engineSettings(
                            mip::Identity("<engine-account>"),      // Engine identity (account used for authentication)
                            authDelegateImpl,                       // Token acquisition implementation
                            "<engine-state>",                       // User-defined engine state
                            "en-US");                               // Locale (default = en-US)

    //Set enable_msg_file_type flag as true
    std::vector<std::pair<string, string>> customSettings;
    customSettings.emplace_back(mip::GetCustomSettingEnableMsgFileType(), "true");
    engineSettings.SetCustomSettings(customSettings);

    // Set up promise/future connection for async engine operations; add engine to profile asynchronously
    auto enginePromise = make_shared<promise<shared_ptr<FileEngine>>>();
    auto engineFuture = enginePromise->get_future();
    profile->AddEngineAsync(engineSettings, enginePromise);
    std::shared_ptr<FileEngine> engine;

    try
    {
        engine = engineFuture.get();
    }
    catch (const std::exception& e)
    {
        cout << "An exception occurred... is the access token incorrect/expired?\n\n"<< e.what() << "'\n";
        system("pause");
        return 1;
    }

    //Set file paths
    string inputFilePath = "<input-file-path>"; //.msg file to be labeled
    string actualFilePath = inputFilePath;
    string outputFilePath = "<output-file-path>"; //labeled .msg file
    string actualOutputFilePath = outputFilePath;

    //Create a file handler for original file
    auto handlerPromise = std::make_shared<std::promise<std::shared_ptr<FileHandler>>>();
    auto handlerFuture = handlerPromise->get_future();

    engine->CreateFileHandlerAsync(inputFilePath,
                                    actualFilePath,
                                    true,
                                    std::make_shared<FileHandlerObserver>(),
                                    handlerPromise);

    auto fileHandler = handlerFuture.get();

    //List labels available to the user    

    // Use mip::FileEngine to list all labels
    auto labels = engine->ListSensitivityLabels();

    // Iterate through each label, first listing details
    for (const auto& label : labels) {
        cout << label->GetName() << " : " << label->GetId() << endl;

        // get all children for mip::Label and list details
        for (const auto& child : label->GetChildren()) {
            cout << "->  " << child->GetName() << " : " << child->GetId() << endl;
        }
    }

    string labelId = "<labelId-id>"; //set a label ID to use

    // Labeling requires a mip::LabelingOptions object. 
    // Review API ref for more details. The sample implies that the file was labeled manually by a user.
    mip::LabelingOptions labelingOptions(mip::AssignmentMethod::PRIVILEGED);

    // Resolve the label ID to a mip::Label, then apply it.
    auto label = engine->GetLabelById(labelId);
    fileHandler->SetLabel(label, labelingOptions, mip::ProtectionSettings());

    // Commit changes, save as outputFilePath
    auto commitPromise = std::make_shared<std::promise<bool>>();
    auto commitFuture = commitPromise->get_future();

    if(fileHandler->IsModified())
    {
        fileHandler->CommitAsync(outputFilePath, commitPromise);
    }
    
    if (commitFuture.get()) {
        cout << "\n Label applied to file: " << outputFilePath << endl;
    }
    else {
        cout << "Failed to label: " + outputFilePath << endl;
        return 1;
    }

    // Create a new handler to read the label
    auto msgHandlerPromise = std::make_shared<std::promise<std::shared_ptr<FileHandler>>>();
    auto msgHandlerFuture = msgHandlerPromise->get_future();

    engine->CreateFileHandlerAsync(inputFilePath,
                                    actualFilePath,
                                    true,
                                    std::make_shared<FileHandlerObserver>(),
                                    msgHandlerPromise);

    auto msgFileHandler = msgHandlerFuture.get();

    cout << "Original file: " << inputFilePath << endl;
    cout << "Labeled file: " << outputFilePath << endl;
    cout << "Label applied to file : " 
            << msgFileHandler->GetLabel()->GetLabel()->GetName() 
            << endl;
    
    // Application shutdown. Null out profile, engine, handler.
    // Application may crash at shutdown if resources aren't properly released.
    msgFileHandler = nullptr;
    fileHandler = nullptr;
    engine = nullptr;
    profile = nullptr;
    mMipContext->ShutDown();
    mMipContext = nullptr;

    return 0;
}

For more information about file operations, see File Handler concepts.

  1. Replace the placeholder values in the source code with the following values:

    Placeholder Value
    <application-id> The application ID as registered with the Microsoft Entra tenant, for example: 00001111-aaaa-2222-bbbb-3333cccc4444.
    <engine-account> The account used for the engine identity, for example: user@tenant.onmicrosoft.com.
    <engine-state> User-defined application state, for example: My engine state.
    <input-file-path> The full path to a test input message file, for example: c:\\Test\\message.msg.
    <output-file-path> The full path to the output file, which is a labeled copy of the input file, for example: c:\\Test\\message_labeled.msg.
    <label-id> The label ID retrieved by using ListSensitivityLabels, for example: 667466bf-a01b-4b0a-8bbf-a79a3d96f720.

Build and test the application

Use F6 (Build Solution) to build your client application. If you don't have build errors, use F5 (Start debugging) to run your application.