Connecting to Outlook and Establishing a MAPI Session

Before sending and reading email, it is necessary to obtain connections both to Outlook and to the MAPI subsystem. To connect to Outlook, instantiate an object of Outlook’s Application class, as shown here:

Dim OutlookApplication As Outlook.Application
Set OutlookApplication = New Outlook.Application

The act of instantiating the Application object causes Outlook to load and run, if it’s not running already. However, when Outlook is executed in this way, it does not appear in a window, nor is there a button for it in the task bar; instead, it runs as a hidden application.

The next order of business is to establish a MAPI session. The Application object doesn’t have a method for doing this. Rather, it’s necessary to obtain a NameSpace object from the Application object. This can be done in either of two ways. One way is to call the Application object’s GetNamespace method, like this:

' OutlookApplication previously Dim'ed and Set.
Dim OutlookNameSpace As Outlook.NameSpace
Set OutlookNameSpace = Outlook.Application.GetNamespace("MAPI")

The argument to the GetNamespace method must always be the string "MAPI“. The other way to get a NameSpace object from the Application object is to read the contents of the Application object’s Session property, like this:

' OutlookApplication previously Dim'ed and Set.
Dim OutlookNameSpace As Outlook.NameSpace
Set OutlookNameSpace = Outlook.Application.Session

The NameSpace object is roughly analogous ...

Get CDO & MAPI Programming with Visual Basic: now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.