Article ID: 168903
Article Last Modified on 8/18/2005
// BEGIN CODE
#include <windows.h>
#define USES_IID_IMAPITable
#define USES_IID_IMessage
#define USES_IID_IMAPIStatus
#define INITGUID
#include <initguid.h>
#include <ole2.h>
#include <mapiguid.h>
#include <mapiutil.h>
#include <mapitags.h>
#define USES_OID_OLE2_STORAGE
#define INITOID
#include <mapioid.h>
LPSTORAGE pstg = NULL;
LPUNKNOWN lpUnknown = NULL;
LPATTACH pAtt = NULL;
ULONG ulAttNum;
HRESULT hRes;
OPENFILENAME ofn;
TCHAR szFile[MAX_PATH];
OLECHAR pszFile[MAX_PATH];
enum {METHOD,RENDERING,NUM_ATT_PROPS};
SPropValue spvAttach[NUM_ATT_PROPS];
ZeroMemory((LPVOID) &ofn, sizeof ofn);
// Set up structure to retrieve filename
lstrcpy(szFile,"*.*");
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hWnd;
ofn.lpstrFilter = "All files\0*.*\0";
ofn.lpstrFile = szFile;
ofn.nMaxFile = MAX_PATH;
ofn.lpstrTitle = "Attach File";
ofn.Flags = OFN_NONETWORKBUTTON | OFN_FILEMUSTEXIST |
OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST;
// Prompt user for file name
if (GetOpenFileName(&ofn))
{
// Create an attachment on the message
if (FAILED(hRes = pMsg->CreateAttach(
NULL, (ULONG)0, &ulAttNum, &pAtt)))
goto Quit;
spvAttach[METHOD].ulPropTag = PR_ATTACH_METHOD;
spvAttach[METHOD].Value.l = ATTACH_OLE;
spvAttach[RENDERING].ulPropTag = PR_RENDERING_POSITION;
spvAttach[RENDERING].Value.l = 0;
// Save the properties we have set on the attachment
if (FAILED(hRes = pAtt -> SetProps(
NUM_ATT_PROPS,
(LPSPropValue)&spvAttach,
NULL)))
goto Quit;
// PR_ATTACH_DATA_OBJ will contain the OLE object
if (FAILED(hRes = pAtt->OpenProperty(
PR_ATTACH_DATA_OBJ,
(LPIID)&IID_IStorage, 0,
MAPI_CREATE | MAPI_MODIFY,
(LPUNKNOWN *)&pstg)))
goto Quit;
// We must convert the file name to a Wide Character string
// for use in the OleCreateFromFile function
MultiByteToWideChar(CP_ACP, 0, ofn.lpstrFile, -1, pszFile, 512);
// Create an embedded object in the IStorage object from the
// contents of the specified file
if (FAILED(hRes = OleCreateFromFile(
CLSID_NULL, pszFile, IID_IOleObject,
OLERENDER_NONE, NULL, NULL, pstg,
(LPVOID FAR*)&lpUnknown)))
goto Quit;
// Call the Commit Method of the IStorage Object
if (FAILED(hRes = pstg->Commit(STGC_DEFAULT)))
goto Quit;
// Save the changes to the Attachment
pAtt -> SaveChanges(0);
Quit:
if (pAtt)
pAtt -> Release();
if (lpUnknown)
lpUnknown -> Release();
if (pstg)
pstg -> Release();
return hRes;
// END CODE
Keywords: kbhowto kbmsg kbcode KB168903