Code Snippet
private static void SetMessageProperty(object mapiObject, uint propertyTag, string text)
{
// Pointer to IUnknown Interface
IntPtr IUnknown = NULL;
// Pointer to IMessage Interface
IntPtr IMessage = NULL;
// Pointer to IMAPIProp Interface
IntPtr IMAPIProp = NULL;
// Structure that will hold the Property Value
SPropValue propValue;
// A pointer that points to the SPropValue structure
IntPtr ptrPropValue = NULL;
// if we have no MAPIObject everything is senseless...
if (mapiObject == null) return;
try
{
// We can pass NULL here as parameter, so we do it.
MAPIInitialize(NULL);
// retrive the IUnknon Interface from our MAPIObject comming from Outlook.
IUnknown = Marshal.GetIUnknownForObject(mapiObject);
// since HrGetOneProp needs a IMessage Interface, we must query our IUnknown interface for the IMessage interface.
// create a Guid that we pass to retreive the IMessage Interface.
Guid guidIMessage = new Guid(IID_IMessage);
// try to retrieve the IMessage interface, if we don't get it, everything else is sensless.
if (Marshal.QueryInterface(IUnknown, ref guidIMessage, out IMessage) != S_OK) return;
// create a Guid that we pass to retreive the IMAPIProp Interface.
Guid guidIMAPIProp = new Guid(IID_IMAPIProp);
// try to retrieve the IMAPIProp interface from IMessage Interface, everything else is sensless.
if (Marshal.QueryInterface(IMessage, ref guidIMAPIProp, out IMAPIProp) != S_OK) return;
// double check, if we wave no pointer, exit...
if (IMAPIProp == NULL) return;
// Alloc memory for the text and create a pointer to it
IntPtr ptrToValue = Marshal.StringToHGlobalAnsi(text);
// Create our structure with data
propValue = new SPropValue();
// Wich property should be set
propValue.ulPropTag = propertyTag;
propValue.dwAlignPad = 0;
propValue.Value = (long)ptrToValue;
ptrPropValue = Marshal.AllocHGlobal(Marshal.SizeOf(propValue));
Marshal.StructureToPtr(propValue, ptrPropValue, false);
// try to set the Property ( Property Tags can be found with Outlook Spy from Dmitry Streblechenko )
HrSetOneProp(IMAPIProp, ptrPropValue);
Marshal.FreeHGlobal(ptrPropValue);
Marshal.FreeHGlobal(ptrToValue);
}
catch (System.Exception ex)
{
}
finally
{
// Free used Memory structures
if (ptrPropValue != NULL) MAPIFreeBuffer(ptrPropValue);
// cleanup all references to COM Objects
if (IMAPIProp != NULL) Marshal.Release(IMAPIProp);
if (IMessage != NULL) Marshal.Release(IMessage);
if (IUnknown != NULL) Marshal.Release(IUnknown);
MAPIUninitialize();
}
}