c++ 应用程序获取outlook联系人的详细步骤及代码
时间: 2023-11-22 09:52:44 浏览: 177
获取Outlook联系人的详细步骤及代码如下:
1. 引入Outlook头文件
```c++
#include <afxwin.h>
#include <afxdisp.h>
#include <atlbase.h>
#include <atlcom.h>
#include <atlctl.h>
#include <oleauto.h>
#include <msoutl.h>
```
2. 定义COleException异常类
```c++
class COleException : public CException
{
public:
COleException(HRESULT hr);
virtual ~COleException() throw();
// Attributes
public:
HRESULT m_hr;
// Implementation
public:
virtual BOOL GetErrorMessage(LPTSTR lpszError, UINT nMaxError,
PUINT pnHelpContext = NULL);
};
```
3. 实现COleException异常类
```c++
COleException::COleException(HRESULT hr) : m_hr(hr)
{
}
COleException::~COleException() throw()
{
}
BOOL COleException::GetErrorMessage(LPTSTR lpszError, UINT nMaxError,
PUINT pnHelpContext)
{
CString str;
str.Format(_T("0x%08x"), m_hr);
lstrcpyn(lpszError, str, nMaxError);
return TRUE;
}
```
4. 定义COutlookContacts类
```c++
class COutlookContacts
{
public:
COutlookContacts();
virtual ~COutlookContacts();
// Operations
public:
BOOL CreateDispatch(LPCTSTR lpszProgID);
void CloseDispatch();
COleException m_exception;
_Application m_app;
_NameSpace m_session;
_Items m_items;
_MailItem m_mailItem;
// Implementation
protected:
void ThrowException(HRESULT hr);
};
```
5. 实现COutlookContacts类
```c++
COutlookContacts::COutlookContacts()
{
}
COutlookContacts::~COutlookContacts()
{
CloseDispatch();
}
BOOL COutlookContacts::CreateDispatch(LPCTSTR lpszProgID)
{
COleException e;
if (!m_app.CreateDispatch(lpszProgID, &e))
{
ThrowException(e.m_hr);
return FALSE;
}
m_session.AttachDispatch(m_app.GetNamespace(_T("MAPI")));
try
{
m_session.Logon(_T(""), _T(""), TRUE, TRUE);
m_items.AttachDispatch(m_session.GetDefaultFolder(olFolderContacts)->GetItems(), TRUE);
}
catch (COleException* pEx)
{
ThrowException(pEx->m_hr);
pEx->Delete();
return FALSE;
}
return TRUE;
}
void COutlookContacts::CloseDispatch()
{
m_items.ReleaseDispatch();
m_session.ReleaseDispatch();
m_app.ReleaseDispatch();
}
void COutlookContacts::ThrowException(HRESULT hr)
{
m_exception.m_hr = hr;
THROW(m_exception);
}
```
6. 使用COutlookContacts类获取联系人信息
```c++
COutlookContacts outlook;
if (outlook.CreateDispatch(_T("Outlook.Application")))
{
int count = outlook.m_items.GetCount();
for (int i = 1; i <= count; i++)
{
_ContactItem contactItem = outlook.m_items.GetItem(COleVariant((short)i));
CString name = contactItem.GetFullName();
CString email = contactItem.GetEmail1Address();
// Do something with the name and email
}
outlook.CloseDispatch();
}
else
{
AfxMessageBox(_T("Failed to create Outlook session."));
}
```
注意:需要在项目属性中的“C/C++” -> “预处理器” -> “预处理器定义”中添加“_ATL_APARTMENT_THREADED”宏定义。另外,需要在程序运行时保证Outlook已经启动。
阅读全文