Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / MFC

Save Message to MSG Compound File

4.67/5 (8 votes)
20 Aug 2023CPOL 26.9K  
How to save a message to an MSG Compound file.

This tip contains code that demonstrates how to save a message to a compound document that is readable by any client that supports the .msg file format.

#include "ConverterSession.h[^]":

C++
HRESULT SaveOutlookMessage(CMAPIMessage& pMapiMessage, BSTR bstrFilename)
{
   CString strFilePath = CString(bstrFilename);
   char lpszFileName[0x100] = { 0 };
   strcpy_s(lpszFileName, 0x100, CW2A(strFilePath));
 
   LPSTREAM pStream = NULL;
   IConverterSession* pConverterSession = NULL;
   HRESULT hr = S_OK;
 
   hr = CoCreateInstance(CLSID_IConverterSession, NULL,
      CLSCTX_INPROC_SERVER, IID_IConverterSession, (void**)&pConverterSession);
   if (SUCCEEDED(hr))
   {
      hr = pConverterSession->SetEncoding(IET_QP);
      if (SUCCEEDED(hr))
      {
         hr = pConverterSession->SetSaveFormat(SAVE_RFC1521);
         if (SUCCEEDED(hr))
         {
            hr = OpenStreamOnFile(MAPIAllocateBuffer, MAPIFreeBuffer,
               STGM_CREATE | STGM_READWRITE, (LPTSTR)lpszFileName, NULL, &pStream);
            if (SUCCEEDED(hr))
            {
               hr = pConverterSession->MAPIToMIMEStm(pMapiMessage.Message(), 
                  pStream, 0);
               if (SUCCEEDED(hr))
               {
                  hr = pStream->Commit(0);
                  if (SUCCEEDED(hr))
                  {
                     OutputDebugString(_T("All done right\n"));
                  }
               }
            }
         }
      }
   }
 
   if (pStream != NULL)
   {
      pStream->Release();
      pStream = NULL;
   }
 
   if (pConverterSession != NULL)
   {
      pConverterSession->Release();
      pConverterSession = NULL;
   }
 
   return hr;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)