6

I have tried to get the contacts of Outlook contacts into C#, but it is not working. I have used the Microsoft Outlook 12.0 Object Library. I want to show the data in richtextbox or gridview.

The code is pasted below. Please let me know what I should do there.

    private void getContacts_Click(object sender, EventArgs e)
    {
        // Obtain an instance of the Outlook application
        Outlook.Application app = new Outlook.ApplicationClass();

        // Access the MAPI namespace
        Outlook.NameSpace ns = app.GetNamespace("MAPI");

        // Get the user's default contacts folder
        Outlook.MAPIFolder contacts =
        ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);

        // Iterate through each contact
        for (int i = 1; i < contacts.Items.Count + 1; i++)
        {
            // Get a contact
            Outlook.ContactItem contact =
            (Outlook.ContactItem)contacts.Items[i];
            richTextBox1.Text += contact.FullName + " (" +
            contact.BusinessTelephoneNumber + ")" + Environment.NewLine;
            Application.DoEvents();
        }
    }
}
Jamal
  • 763
  • 7
  • 22
  • 32
user2420211
  • 280
  • 1
  • 3
  • 11
  • Can you provide more detail about the 'not working' part? – Gayot Fow Jun 02 '13 at 15:58
  • as the button event takes place! it doesnot do anything at all! although it should show the contacts of outlook in gridview! – user2420211 Jun 02 '13 at 16:31
  • 1
    AH! If nothing at all is happening, you need to wire the 'Click' event of the button to your handler. You can do that in the Xaml. – Gayot Fow Jun 02 '13 at 16:40
  • 1
    Breakpoints are your best friends. Set break point before the for loop and step over the loop - see if you have some actual contacts or not. Let us know what you see. Also, `Application.DoEvents()` is very bad for health - please don't use it - delete that line of code. – YK1 Jun 02 '13 at 18:54

4 Answers4

7

This works for me. It gets all the contacts from outlook and shows it in datagridview.

  Microsoft.Office.Interop.Outlook.Items OutlookItems;
  Microsoft.Office.Interop.Outlook.Application outlookObj = new Microsoft.Office.Interop.Outlook.Application();
  MAPIFolder Folder_Contacts;
  Folder_Contacts = (MAPIFolder)outlookObj.Session.GetDefaultFolder(OlDefaultFolders.olFolderContacts);
  OutlookItems = Folder_Contacts.Items;
  MessageBox.Show("Wykryto kontaktów: " + OutlookItems.Count.ToString());

  for (int i = 0; i < OutlookItems.Count; i++)
  {
    Microsoft.Office.Interop.Outlook.ContactItem contact = (Microsoft.Office.Interop.Outlook.ContactItem)OutlookItems[i+1];
    sNazwa = contact.FullName;
    sFirma = contact.CompanyName;
    sAdress = contact.BusinessAddressStreet;
    sMiejscowosc = contact.BusinessAddressPostalCode + " " + contact.BusinessAddressCity;
    sEmail = contact.Email1Address;
    dataGridView1.Rows.Add(sNazwa, sFirma, sAdress, sMiejscowosc, sEmail);

  }
Łukasz Motyczka
  • 1,169
  • 2
  • 13
  • 35
3

I have tried the below-mentioned code to fetch the data from Outlook to C# desktop application in gridview. I have the above-mentioned API for that and got the email address of Outlook that is configured on your system! The code is pasted below.

The used API works fine with outlook 2007 and 2003, but for outlook 2010, it's suggested to use the other API.

public partial class Form1: Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        fetchOutlookContacts();
    }

    public void fetchOutlookContacts()
    {
        Microsoft.Office.Interop.Outlook.Items OutlookItems;
        Microsoft.Office.Interop.Outlook.Application outlookObj;
        MAPIFolder Folder_Contacts;

        outlookObj = new Microsoft.Office.Interop.Outlook.Application();
        Folder_Contacts = (MAPIFolder)outlookObj.Session.GetDefaultFolder(OlDefaultFolders.olFolderContacts);
        OutlookItems = Folder_Contacts.Items;

        DataTable dt = new DataTable();
        dt.Columns.Add("Email Address");

        for (int i = 0; i < OutlookItems.Count; i++)
        {
            Microsoft.Office.Interop.Outlook.ContactItem contact = (Microsoft.Office.Interop.Outlook.ContactItem)OutlookItems[i + 1];
            dt.Rows.Add(new object[] { contact.Email1Address });

        }
        dataGridView1.DataSource = dt;
        dataGridView1.Show();

    }
}
Muhammad Usman Bashir
  • 1,441
  • 2
  • 14
  • 43
user2420211
  • 280
  • 1
  • 3
  • 11
  • I tried your code, it is working but when I tried in a pc that didnt have outlook it doesnt work. what is the issue? I mean it asked for setup outlook app. – Amir May 31 '19 at 16:19
  • 1
    @Amir yes you have to setup Outlook in order to work. Microsoft.Office.Interop references Outlook com objects on your machine. You should use another approach if installing it is not an option. Microsoft Exchange Web services could be another solution. – Samidjo May 14 '20 at 21:49
2

This code is working fine in my C#-Solution.

using Outlook =Microsoft.Office.Interop.Outlook;

private void kontaktImport_Click(object sender, RoutedEventArgs e)
        {
            Outlook.Application app = new Outlook.Application();
            Outlook.NameSpace NameSpace = app.GetNamespace("MAPI");
            Outlook.MAPIFolder ContactsFolder = NameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
            Outlook.Items ContactItems = ContactsFolder.Items;
            try
            {
                foreach (Outlook.ContactItem item in ContactItems)
                {
                    String output = "";
                    output = item.FirstName + "\n";
                    output += item.LastName;
                    TestTextBox.Text = output;
                }
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                TestTextBox.Text = ex.ToString();
            }
        }         
1

Well there is a solution with Microsoft Interop but that creates issue with systems where Microsoft office is not installed. So i solved it with Microsoft exchange service. For now i have tried it in Asp.Net mvc and it works fine. So this is how you can get contacts in Asp.Net

public void GetContact()
    {
        
        string ewsUrl = "https://outlook.office365.com/EWS/Exchange.asmx";
        string userName = "outlookusername";
        string password = "outlookpassword";

        ExchangeService servicex = new ExchangeService();
        servicex.Url = new Uri(ewsUrl);
        servicex.UseDefaultCredentials = true;
        servicex.Credentials = new WebCredentials(userName, password);
        ContactsFolder contactsfolder = ContactsFolder.Bind(servicex, WellKnownFolderName.Contacts);
        int numItems = contactsfolder.TotalCount < 50 ? contactsfolder.TotalCount : 50;
        if (numItems == 0)
            AddContact();
        numItems = contactsfolder.TotalCount < 50 ? contactsfolder.TotalCount : 50;
        // Instantiate the item view with the number of items to retrieve from the Contacts folder.
        ItemView view = new ItemView(numItems);

        // To keep the request smaller, request only the display name property.
        view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName);

        // Retrieve the items in the Contacts folder that have the properties that you selected.
        FindItemsResults<Item> contactItems = servicex.FindItems(WellKnownFolderName.Contacts, view);

        // Display the list of contacts. 
        foreach (Item item in contactItems)
        {
            if (item is Contact)
            {
                Contact contact = item as Contact;
                Console.WriteLine(contact.DisplayName);
            }
        }
    }`

you just have to replace outlook username password there and this will give you contacts. In case there are no contacts i have called Add Contact method for adding one.For more reference you can have a look at this article i found Microsoft Outlook Add contact and get contact Asp.Net MVC using Microsoft Exchange Service

Shubham
  • 443
  • 2
  • 10