65.9K
CodeProject is changing. Read more.
Home

Using Collaboration Data Objects (CDO) to check for new Exchange email

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.28/5 (14 votes)

Feb 19, 2004

Public Domain
viewsIcon

108612

downloadIcon

3028

Using Collaboration Data Objects (CDO) to check for new Exchange email

Introduction

This application connects to the Exchange server and checks for unread mail in your inbox. Outlook does this already, but this feature doesn't work well with SpamBayes. I decided I'd write my own in C# using the CDO Library

We use the Microsoft CDO 1.21 Library in our project to connect to Exchange, open the inbox and filter on unread messages as follows

// New session
oSession = new MAPI.Session();
// Will use vEmpty for Empty parameter
Object vEmpty = Missing.Value;
// Logon
oSession.Logon(vEmpty,vEmpty,false,false,vEmpty,vEmpty,vEmpty);
// Get Inbox.
oFolder = (MAPI.Folder)oSession.Inbox;
// Get Messages collection.
MAPI.Messages oMsgs = (MAPI.Messages)oFolder.Messages;
// Get the collection's MessageFilter object
MAPI.MessageFilter oFilter = (MAPI.MessageFilter)oMsgs.Filter;
oFilter.Unread = true; 
// Get messages count.
Object oCount = oMsgs.Count;
// Log off session.
if (oSession != null)
    oSession.Logoff(); 

Launching Outlook I also use some calls from user32.dll to bring outlook up when the system tray icon is double clicked. This code is from an article written by Marc Clifton on this website.

[DllImport("user32.dll")] private static extern
  bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")] private static extern
  bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")] private static extern
  bool IsIconic(IntPtr hWnd);
private const int SW_RESTORE = 9;
// look for outlook already running
Process[] processes = Process.GetProcessesByName("Outlook");
if (processes.Length == 0)
{
    // start new outlook process
    Process proc = new Process();
    proc.StartInfo.FileName = "Outlook";
    proc.Start();}
else
{
    // pull up the existing outlook window
    IntPtr hWnd=processes[0].MainWindowHandle;
    if (IsIconic(hWnd))
    {
      ShowWindowAsync(hWnd, SW_RESTORE);
    }
    SetForegroundWindow(hWnd);
} 

Conclusion

My only problem with the code is how much memory it hogs, but I think that's a .NET thing.