BOOKS i'm reading |
Automate Microsoft Outlook from C++Contents
Accessing the Outlook COM interfaces from C++ (Part 1)The first step to automate Outlook is to define an interface. Here is the one I have come with:
// Forward declaration class COutlookStubImpl; class CRecipient { public: explicit CRecipient(LPCTSTR email, LPCTSTR firstName = NULL, LPCTSTR lastName = NULL); std::string Format() const; private: std::string m_email; std::string m_firstName; std::string m_lastName; }; class COutlookStub { public: enum StubMethod { COM }; COutlookStub( StubMethod eMethod = COM ); ~COutlookStub(); bool Init(); void SetDeleteAfterSubmit( bool val ) { m_bDeleteAfterSubmit = val; } bool Send(LPCTSTR Subject, LPCTSTR To, LPCTSTR Body); bool Send(LPCTSTR Subject, const CRecipient &recipient, LPCTSTR Body) { return Send(Subject,recipient.Format().c_str(),Body); } private: /* * This class is using the envellope/letter pattern to really * encapsulate the method by which it contacts Outlook. */ COutlookStubImpl *m_pOutlookStubImpl; bool m_bDeleteAfterSubmit; }; First, the defined interface is very simple and could easilly be extended. For the purpose of this article, defining a
// Check first if a connection to Outlook is possible. if( dlg.m_OutlookStub.Init() ) { INT_PTR nResponse = dlg.DoModal(); } else { MessageBox(NULL,_T("Connecting to Outlook 2003 has failed"), _T("Outlook Automation with C++"),MB_OK|MB_ICONERROR); } The next step is to create an struct InitOle { InitOle() { m_bMustUninitialize = OLI_SUCCEEDED(::CoInitialize(NULL)); } ~InitOle() { if(m_bMustUninitialize) ::CoUninitialize(); } private: bool m_bMustUninitialize; } _init_InitOle_;
/* * The Microsoft Office 11 Object type library is required as it is referenced by the * Outlook type library. */ #import "libid:2DF8D04C-5BFA-101B-BDE5-00AA0044DE52" rename("EOF","EOFile") // This statement is needed otherwise the generated header file for msout.olb will not // compile. using namespace Office; /* * Please consult the Outlook Type library from Tools/OLE/COM object viewer * to know its exact location as it might vary from one computer to the other. * * Note, it is important to place the import statement first as there is a conflict with * a macro named CopyFile defined in winbase.h */ #import "libid:00062FFF-0000-0000-C000-000000000046" rename("EOF","EOFile") It tells to compiler to fetch the specified COM type libraries and to generate C++ header files that can be used from our program. The libid keyword specify to the compiler to search in the registry to find the location of the type library. You can directly specify the path but by doing so, it makes the code source much less portable since the type libraries location can vary from one system to the other. I found this tip in an article from Heath Stewart. |