Wednesday, December 9, 2015

Accessing mail from Outlook through C# .NET

This example shows how to get the mails from outlook through C# code.

The following demonstrates how to retrieve data from items within an Outlook folder (called "IN" under the Inbox folder) using .NET.First add a reference to the Outlook COM object your project:


  1. In VS.NET right click on References and choose Add Reference.
  2. Select the COM tab
  3. Choose "Microsoft Outlook 15.0 Object Library" (this is for MS Office 2013 ) and click Select.
  4. Click OK.
            using Microsoft.Office.Interop.Outlook;

            Microsoft.Office.Interop.Outlook.Application app = null;
            Microsoft.Office.Interop.Outlook._NameSpace namespce = null;            
            Microsoft.Office.Interop.Outlook.MailItem item = null;
            Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
            Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;
     
              try
            {
                app = new Microsoft.Office.Interop.Outlook.Application();
                namespce = app.GetNamespace("MAPI");
                namespce.Logon(null, null, false, false);

                inboxFolder = namespce.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
                subFolder = inboxFolder.Folders["IN"]; 
                Console.WriteLine("Folder Name: {0}, EntryId: {1}", subFolder.Name, subFolder.EntryID);
                Console.WriteLine("Num Items: {0}", subFolder.Items.Count.ToString());

                foreach (Folder folder in inboxFolder.Folders)
                {
                    
                    if (folder.Name == "IN")
                    {
                        Console.WriteLine(folder.Name);
                        for (int i = 1; i <= folder.Items.Count; i++)
                        {
                            item = (Microsoft.Office.Interop.Outlook.MailItem)folder.Items[i];                                  
                            Console.WriteLine("Subject: {0}", item.Subject);                            
                        }
                    }
                }
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                namespce = null;
                app = null;
                inboxFolder = null;
            }

No comments:

Post a Comment