Programming Outlook with C#


Microsoft Office provides a powerful component model to automate from another program. Using this object model, you can access Mail Items, Calendar Items, Journal Entries, and any other item that Outlook normally exposes. Using COM Interop you can automate Outlook from a .NET application. In this article we'll look at different approaches to working with Outlook folders, and walk through creating items in Outlook with C#.

Article Contents

 

System Requirements and Assumptions
The Outlook Object Model
Creating the Interop Assemblies
Starting a Session
Working with Folders
Outlook Items
Creating an Email
Creating a Contact
Conclusion

 

System Requirements and Assumptions

You will need the following software to use the code in this article.

  • Windows 2000 or XP
  • Office 2000
  • .Net Framework SDK

Im going to assume that you have a fair grasp of C#.

The Outlook Object Model

The Outlook object model provides a few key objects described in the table below.

Application Object This is the root object
Namespace Object This object controls Sessions, Folders, and Items among other things
Explorer Object The window displaying a folder
Inspector Class The window displaying an item

 

Creating the Interop Assemblies

In Visual Studio .NET you can just click add reference, then browse to the libraries you want to import. Specifically MSOUTL9.OLB for Outlook. If youre using the SDK then you will do this from the command line using the Type Library Import Tool tblimp.exe.

To use the Type Library Importer from the command line. Create a new directory in a location of your choosing called OfficeSample. From the command prompt change to the C:\Program Files\Microsoft.NET\FrameworkSDK\bin directory and then type: tlbimp "C:\Program Files\Microsoft Office\Office\msoutl9.olb" /out:"C:\Office Sample\msoutl9.dll"

This will create an interop dll for Outlook.

Starting a Session

The first step we need to take to automate Outlook is to create an Outlook session. To do this you need to create a reference to the Outlook Interop assembly, and select the profile you wish to work with.

msoutl9.Application objOutlook = new msoutl9.ApplicationClass();
msoutl9.NameSpace objNS = objOutlook.GetNamespace("MAPI");
objNS.Logon ("exchtest","net",false,true);

 

msoutl9.Application objOutlook = new msoutl9.ApplicationClass();

 

This line creates the Outlook object, next you need to call getNamespace, the only parameter you can pass to it is MAPI.

msoutl9.NameSpace objNS = objOutlook.GetNamespace("MAPI");

 

Finally, we call the logon Method. This will open the profile we want to work with.

objNS.Logon ("exchtest","net",false,true);

 

The Following table describes the arguments of the logon method.

Name DataType   Description
Profile string This is the name of the profile you want to log into. Leaving it blank uses the default profile.
Password string The password for the profile, leaving it blank uses the default profiles password.
ShowDialog Boolean Determines whether the Outlook profile dialog will be displayed
NewSession Boolean Determines if a new session will be created or an existing one used

 

You can also bypass the logon method, and the current profile and session will be used. However, you can not have multiple sessions in Outlook.

Working with Folders

Outlook stores everything in folders, and each folder can be set to hold only a certain kind of data. They can be accessed through the GetDefaultFolders Method of the Namespace object. There are several types of folder listed below with there constant values.

Folder Name Constant
Calendar OlDefaultFolders.olFolderCalendar
Contacts OlDefaultFolders.olFolderContacts
Deleted Items OlDefaultFolders.olFolderDeletedItems
Drafts OlDefaultFolders.olFolderDrafts
Inbox OlDefaultFolders.olFolderInbox
Journal OlDefaultFolders.olFolderJournal
Notes OlDefaultFolders.olFolderNotes
Outbox OlDefaultFolders.olFolderOutbox
Sent Items OlDefaultFolders.olFolderSentItems
Tasks OlDefaultFolders.olFolderTasks

 

To get to the Inbox Folder the code would be.

msoutl9.Explorer objExplorer = objOutlook.Explorers.Add(objFolder.GetDefaultFolder(OlDefaultFolders.olFolderInbox), OlFolderDisplayMode.olFolderDisplayNormal);
objExplorer.Activate();

 

We can also navigate folders using the index value of the Folders Collection.

for (int i=1; i <= objFolders.Count; i++)
{
Console.WriteLine(objFolders.Item(i).Name);
}

 

Or you could use foreach, this comes in handy for user created folders, and exchange public folders. Here is an example of a simple search function using foreach that will return true if a folder exists, and false otherwise.

public bool FindFolder(string strFolderName)
{
     msoutl9.MAPIFolder objFolder;
     foreach (objfolder in objNS.Folders)
     {
          if (objfolder.Name == strFolderName)
          {
               return true;
           }
     }
     return false;
}

 

Outlook Items

Outlook offers several different types of items that correlate to the default Outlook folders. As with the description of folders above, following is a table containing Outlook Item names, and their constants.

Item Constant
Appointment OlItemType.olAppointmentItem
Contact OlItemType.olContactItem
Distribution List OlItemType.olDistributionListItem
Journal Item OlItemType.olJournalItem
Mail OlItemType.olMailItem
Note OlItemType.olNoteItem
Post OlItemType.olPostItem
Task OlItemType.olTaskItem

 

You can create Items using the CreateItem method of the Application Object, or by using the Add method of the of the Items Collection of a given folder.

Using the CreateItem method the code would look like the following.

msoutl9.MailItem objMail = (msoutl9.MailItem) objOutlook.CreateItem(OlItemType.olMailItem);
 

 

Or using the Add method it would look like this.

msoutl9.MailItem objMail;
ObjInbox.Items.Add(objMail);

 

I'll use CreateItem for the remainder of the article.

Creating an Email

The most common task in Outlook is creating an email. You can automate this task from a .NET application easily. You can also automate the process of adding attachments. Here's an excerpt of the sample code.

msoutl9.MailItem objMail = (msoutl9.MailItem) objOutlook.CreateItem(OlItemType.olMailItem);
objMail.To = "user@localhost";
objMail.Subject = "new email";
objMail.Body = "I am your new email message";

 

You can either save the email to your drafts folder using the save method.

objMail.Save();

 

Or you can put it directly in the Outbox using the Send method.

objMail.Send();

 

If you want to save the email to a user created folder, create a reference to the folder you wish to work with, and use the Add method.

Creating a Contact

Just like in the email example above, we create a new Outlook item. This time it as a Contact.

msoutl9.ContactItem objContact = (msoutl9.ContactItem)
objOutlook.CreateItem(OlItemType.olContactItem);

 

Then we fill in the Contact information.

objContact.FirstName = "Joe";
objContact.LastName = "Smith";
objContact.MailingAddressStreet = "123 Some St.";
objContact.MailingAddressCity = "Anytown";
objContact.MailingAddressState = "CA";
objContact.MailingAddressPostalCode = "12345";
objContact.MailingAddressCountry = "USA";
objContact.CompanyName = "Acme Inc.";
objContact.Email1Address = "user@localhost.com";
objContact.Email1AddressType = "SMTP";
< /FONT >

 

And finally we save the information to our contacts folder.

objContact.Save();

 

Conclusion

Aside from those discussed in this article, there are many other properties and methods that are exposed by the object availble through the Outlook programming model some of which you will find in the articles example code.  C# and COM interop allow us as developers to work with Outlook and many other existing programs in familiar ways. For more information of programming with the Outlook object model, see the documentation on http://msdn.microsoft.com/  

posted @ 2008-08-22 10:12  kin2321  阅读(749)  评论(0编辑  收藏  举报