Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Office Interop » Outlook Integration in C#

Outlook Integration in C#

This article describes how we can manipulate outlook from Visual Studio 2005.

Total page views :  108236
Total downloads :  2819
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
OutlookIntegrationEx.zip
 
Become a Sponsor

This article introduces a integrating the outlook from visual studio. We can do the manipulation with outlook with c# language. We can create contacts in outlook contacts, tasks in outlook tasks from visual studio. Microsoft provides the Com components libraries. To complete this task The Microsoft Outlook 11.0 Outlook Library reference should be added to our project from com components tab. When we add reference to our project the Microsft.Office.Core and Outlook assemblies will be added.

The outlook name space consists of all outlook classes like application, contact item, task item, appointment item, and Journal item. Every class deals with the folders in out look application. In this article we are going to create contact in default contact folder. In the same way we can create tasks, appointment etc in out look from visual studio with c# code.

A brief introduction to outlook.
           
.pst File

Microsoft Outlook (non-Exchange Server) uses files with the extension .pst to store your e-mail messages, calendar, contacts, and other information to your computer. These files mobilize you to restore data that is lost or damaged because of a hardware failure and move or transfer data to a different hard disk drive.

MapiFolders

Outlook uses MAPI folders to keep track of your e-mail messages, contacts, appointments, tasks, notes, and journal entries. Outlook keeps these files in one of two places, depending on the type of e-mail server you use. Your MAPI file is either in a personal storage folder (.pst) on your hard disk drive or in a mailbox located on the server, if you are using Outlook with Microsoft Exchange server.

For accessing those MAPI folders first we have to instantiate the Outlook Application object. We are referring the outlook name space couple of times .so, rename outlook name space rename like this.

using OutLook = Microsoft.Office.Interop.Outlook;

First we have to create outlook application interface object.

OutLook._Application outlookObj = new OutLook.Application();

As outlook uses mapi folders to keep contacts, we have to loop through all outlook folders and get the outlook contact folder.

OutLook.MAPIFolder fldContacts = (OutLook.MAPIFolder)outlookObj.Session.GetDefaultFolder(OutLook.OlDefaultFolders.olFolderContacts);

Then, we have to instantiate outlook contact item and add to the outlook contacts folder as below.

OutLook.ContactItem newContact = (OutLook.ContactItem)fldContacts.Items.Add(OutLook.OlItemType.olContactItem);

Get the properties of contact item as shown below.

newContact.FirstName = txtFirstName.Text.Trim().ToString();
newContact.LastName = txtLastName.Text.Trim().ToString();
newContact.Email1Address = txtEmail.Text.Trim().ToString();
newContact.Business2TelephoneNumber = txtPhone.Text.Trim().ToString();
newContact.BusinessAddress = txtAddress.Text.Trim().ToString();

In our example the contact properties are getting from text box values .so the text box values are assigning to the outlook contact item. These values we can get from database, excel sheet or Web service.

We can save this new contact item by invoking the save method on contact item object.

newContact.Save();

The contact item will be created in default contacts folder in outlook.

If we need to create a custom folder in default contacts folder of outlook application, we can follow below steps.
First we have to check whether the folder exists or not and if not create new folder as like this.

public bool CheckCustomFolderExisits()

{

    OutLook._Application outlookObj = new OutLook.Application();

    OutLook.MAPIFolder fldContacts = (OutLook.MAPIFolder)outlookObj.Session.GetDefaultFolder(OutLook.OlDefaultFolders.olFolderContacts);

    //VERIFYING THE CUSTOM SUB FOLDER IN CONTACTS FOLDER IN OUT LOOK.

    foreach (OutLook.MAPIFolder subFolder in fldContacts.Folders)

    {

        if (subFolder.Name == "CustomeFolderName")

        {

            CustomFolder= subFolder;

            return true;

        }

        else

            return false;

    }

    return false;

}

 

For verifying the existing folder we have to loop through the all folders in contacts folder

If not create folder in default contacts folder as below.

public void CreateCustomFolder()

{

    OutLook._Application outlookApp =

new OutLook.Application();

    OutLook.MAPIFolder cntctFolder =

 (OutLook.MAPIFolder)

outlookApp.Session.GetDefaultFolder(OutLook.OlDefaultFolders.olFolderContacts);

    //VERIFYING THE CUSTOM FOLDER IN OUT LOOK .

    foreach (OutLook.MAPIFolder subFolder in cntctFolder.Folders)

    {

        if (subFolder.Name == " CustomeFolderName ")

        {

            CustomFolder= subFolder;

        }

    }

    //IF  CUSTOM FOLDER DOES NOT EXIST CREATE A NEW FOLDER WITH NAME  CUSTOM FOLDER NAME.

    if (CustomFolder == null)

    {

        CustomFolder = contactsFolder.Folders.Add("CustomeFolderName ", Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderContacts);

    }

}

 

We can create contacts in this folder as u follow steps as same as in creating the contacts in default folder ,by passing our custom folder as the parameter . When we are creating the contact in default contacts folder it creates the contact item with unique entry id. We can cross verify the contacts by this entry id.

 

If  want to add custom properties to contact item the contact item has a list property  called  user properties where we can add custom properties to identify the contact.

 

In our code example, the grid shows the contacts in different folders in outlook application. The folders in our outlook application are displayed in a combo.

This code gets the contacts from contacts folder in outlook application.

foreach (Microsoft.Office.Interop.Outlook._ContactItem contactItem in fldContacts.Items)

{

    MyContact contact = new MyContact();

    contact.FirstName = (contactItem.FirstName == null) ? string.Empty :      

                                   contactItem.FirstName;

    contact.LastName = (contactItem.LastName == null) ? string.Empty :

                                  contactItem.LastName;

    contact.EmailAddress = contactItem.Email1Address;

    contact.Phone = contactItem.Business2TelephoneNumber;

    contact.Address = contactItem.BusinessAddress;

    contacts.Add(contact);

}

 

 

The code example allows creating a contact in default folder or custom folder by selecting the custom folder option. The custom Property added in example is 'myPetName'. We can add custom property to contact item like this.

Notice here, the user properties takes the outlookuserpropertytype as parameter.

newContact.UserProperties.Add("myPetName",OutLook.OlUserPropertyType.olText, true, OutLook.OlUserPropertyType.olText);

 

newContact.UserProperties["myPetName"].Value = txtProp1.Text.Trim().ToString();

When we check verify the contact with custom property if it exists it updates the old contact or it creates a new contact. 

Here in this method, it finds the existed contact with user property value.

private OutLook._ContactItem FindContactItem(MyContact contact, OutLook.MAPIFolder folder)

{

    object missing = System.Reflection.Missing.Value;

    foreach (OutLook._ContactItem contactItem in folder.Items)

    {

        OutLook.UserProperty userProperty = contactItem.UserProperties.Find("myPetName", missing);

        if (userProperty != null)

        {

            if (userProperty.Value.Equals(txtProp1.Text.Trim().ToString()))

               return contactItem;

        }

     }

     return null;

}

 

 

 

Outlook Security Access

 

When we are accessing the out look contacts the out look application will prompt for message as shown.

It is a safeguard Microsoft put in to help prevent viruses from mailing everyone in your contacts in outlook. We allow access for 1 minute or more than one minute if there are lots of contacts.

The sample attached can be downloaded and you can learn the how the code works.

Note: VS 2005 and Outlook is required to run this application.


Login to add your contents and source code to this article
 About the author
 
Sairam
Rambabu is software developer. He is interested in Microsoft Technologies.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
OutlookIntegrationEx.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Importing Outlook Contacts by Jyothi On November 6, 2006

Hi Ram,

we have developed a softphone application on windows using vs 2003. the application talks with outlook and all contacts from outlook will import in to softphone when outlook is taken as default database for contacts. in some machines the outlook fails to import contacts beyond 200. there is no error message or exception thrown. the outlook jst fails to import. could you please help me what could be the reason for failure.

 

And the machines where it fails is not any differnent from the normal machines in configuration.

 

Thanks & Regards,

Jyothi Gummadi 

Reply | Email | Delete | Modify | 
What if i want to suppress this prompt through code by faiyaz On February 21, 2007
When we are accessing the out look contacts the out look application will prompt to allow access for . What if i want to suppress this prompt through code
Reply | Email | Delete | Modify | 
reg supressing outlook security access by anand On September 24, 2007
Hi Rambabu, In the current project iam in,iam getting the outlook security access window which you have shown at the end of the article.I want to supress that window through code. can you pls guide me how we can supress.. Regards.. Anand swaroop
Reply | Email | Delete | Modify | 
How we can integrate outlook from web applications by inderjeet On March 3, 2008
How we can integrate outlook from web applications
Reply | Email | Delete | Modify | 
outlook 2007 by Jo On March 17, 2008
this code is not working with the libary from outlook 2007
Reply | Email | Delete | Modify | 
Integration Of outlook by sai On March 24, 2009
Hi, My requirement is Integration of outlook into my application. Inorder to start the integration, first we are adding the COM library references of outlook into my referencs. Actually my requirement is I dont know which version of outlook client has installed on his workstyation? For my programming purpose if I add outtlook 2007 Dll (outlook 12.0 library) then the client who has outlook 2003 (outlook 11.0 library) can't access my application.It will throw exceptions. How can I fix this problem? Can I add outlook references dynamically based on installed outlook version? How to solve this please help me? Regards ---------- Sai kumar bayyavarapu
Reply | Email | Delete | Modify | 
Works like a charm! by ogegoon On August 4, 2009
Great! This is exactly what I am looking for.... No need for me to read the MSDN :o)

I have upgraded your code to VS.net 2008 and replaced the COM references by the Microsoft.Office.Interop.Outlook delivered by MS (available in the .Net tab of the Add references window). It works like a charm !

O.
Reply | Email | Delete | Modify | 
How to suppres When we are accessing the out look contacts the out look application will prompt for message as shown. by hema On August 25, 2009
Hi ram,


          This article is very help to me. is there any possible to suppress the Outlook error message through code after when we add a contact. pls tell me.
Reply | Email | Delete | Modify | 
Access contacts in Windows service by Miha On October 22, 2009
Hi!

Very helpful article!

I have one question: It's possible to access outook contacts in windows service? It throws me exception: Cannot complete the operation. You are not connected. 
Exception is throw when I want to get outlook contact folder :
 OutLook.MAPIFolder fldContacts = (OutLook.MAPIFolder)outlookObj.Session.GetDefaultFolder(OutLook.OlDefaultFolders.olFolderContacts);



Any ideas?

Regards,
MM
Reply | Email | Delete | Modify | 
with out Microsoft.Office.Interop.Outlook.dll how we can do this? by Dinesh On December 15, 2009
with out Microsoft.Office.Interop.Outlook.dll how we can do this?
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.