Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
18 Feb 2004 1  
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here