This website completely moved to new platform. For latest content, visit www.programmingposts.com

Search this Site

24 Jan 2014

Reading emails from MS Outlook using C#.Net

In this article we will see a example for extracting / reading the emails from MS Outlook using C#.Net.
We will see a sample application, which read mail from outlook and display its contents in our application.
The screenshot of sample application is shown below


Before starting the coding, you have to add the reference



The version of Reference may change depending on version of MS Office you are using. Another important thing is, after adding reference Microsoft.Office.Interop.Outlook , right click on Reference , goto properties of reference and set Embed Interop Types -> True . This avoids Runtime COM Exceptions.

Now Add NameSpace using Microsoft.Office.Interop.Outlook; and start coding.

The c# code for the button click Read Mail is given below

private void btnReadMail_Click(object sender, EventArgs e)
        {
            try
            {
                try
                {
                    ItemNo = Convert.ToInt32(txtItemNo.Text);
                }
                catch (FormatException ex2)
                {
                    // MessageBox.Show();
                    MessageBox.Show(ex2.Message + "\nEnter Valid Number greater than zero", "Outlook Reader", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // Check whether there is an running Outlook process
                if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
                {
                    // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
                    myApp = System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application;
                }

                else
                {
                    //if not, creating a new application instance
                    myApp = new Microsoft.Office.Interop.Outlook.Application();
                }

                mapiNameSpace = myApp.GetNamespace("MAPI");
                //selecting Inbox folder
                myInbox = mapiNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
                mapiNameSpace.SendAndReceive(false); //performs SendRecieve Operation without showing ProgrssDialog

                if (myInbox.Items.Count > 0 && ItemNo <= myInbox.Items.Count) //if checking mailcount starts
                {
                    string subject = string.Empty;
                    string attachments = string.Empty;
                    string body = string.Empty;
                    string senderName = string.Empty;
                    string senderEmail = string.Empty;
                    string recepients = string.Empty;
                    string creationdate = string.Empty;

                    bool isMailItem = true;
                    Microsoft.Office.Interop.Outlook.MailItem MyOutlookItem = null;


                    try
                    {
                        //if the item is not a mail Item Application will throw COM exception
                        MyOutlookItem = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[ItemNo]);
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.Message + "\nThere Item " + ItemNo + " is not a Mail Item", "Outlook Reader", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        isMailItem = false;
                    }


                    if (isMailItem)
                    {
                        // Retrieving the Subject
                        if (MyOutlookItem.Subject != null)
                        {
                            subject = MyOutlookItem.Subject;
                            //while working with database, trying to use the values in sql query,
                           //replace ' with " or some symbol, to avoid sql exceptions
                            subject = subject.Replace('\'', '\"');
                        }

                        //Retrieving the Attachment Name
                        if (MyOutlookItem.Attachments.Count > 0)
                        {
                            lblAttachCount.Text = MyOutlookItem.Attachments.Count.ToString();
                            for (int j = 1; j <= MyOutlookItem.Attachments.Count; j++)
                            {
                                attachments += MyOutlookItem.Attachments[j].FileName + "; ";
                            }
                        }
                        else
                        {
                            lblAttachCount.Text = MyOutlookItem.Attachments.Count.ToString();
                            attachments = "No Attachments found";
                        }

                        if (MyOutlookItem.Recipients.Count > 0)
                        {
                            lblReciCount.Text = MyOutlookItem.Recipients.Count.ToString();
                            for (int j = 1; j <= MyOutlookItem.Recipients.Count; j++)
                            {
                                recepients += MyOutlookItem.Recipients[j].Name + "< " + MyOutlookItem.Recipients[j].Address + " >; ";
                            }
                        }


                        attachments = attachments.Replace('\'', '\"');

                        // retrieving the Body
                        body = MyOutlookItem.Body;
                        body = body.Replace('\'', '\"');

                        // Sender Name
                        senderName = MyOutlookItem.SenderName;
                        senderName = senderName.Replace('\'', '\"');


                        // Sender Email
                        senderEmail = MyOutlookItem.SenderEmailAddress;
                        senderEmail = senderEmail.Replace('\'', '\"');

                        // Creation date
                        creationdate = MyOutlookItem.CreationTime.ToString();

                        ////////////////////////////////////////////////////////
                        txtCreateDate.Text = creationdate;
                        txtSenderEmail.Text = senderEmail;
                        txtSenderName.Text = senderName;
                        txtRecipients.Text = recepients;
                        txtSubject.Text = subject;
                        txtAttachments.Text = attachments;
                        txtBody.Text = body;

                        myApp = null;
                    }

                }
                else if (ItemNo > myInbox.Items.Count) //else checking mailcount
                {
                    MessageBox.Show("There are only " + myInbox.Items.Count + " items in your Inbox.", "Outlook Reader", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("There are no items in your Inbox.", "Outlook Reader", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (System.Exception ex4)
            {
                MessageBox.Show(ex4.Message, "Outlook Reader:Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }



The Outlook not only contains mail Items but also may contain Report Item,Meeting Item,Note Items etc,. Hence if you are trying to Cast a Non -MailItem as MailItem, application will throw a run-time COM Exception.The following line of code given below is kept in try catch, to check if the item is MailItem or not.

 //if the item is not a mail Item Application will throw COM exception
 MyOutlookItem = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[ItemNo]);


Suppose, If you are trying to cast the NoteItem as MailItem, it will throw a Run-time COM Exception like, 

Unable to cast COM object of type System_ComObject to InterfaceType "Microsoft.Office.Interop.Outlook.MailItem" . This operation failed because the QueryInterface Call on the Com Component for the Interface with ID'{00063034-0000-0000-C000-00000000046} failed due to the following error.  No such interface supported (Exception from HRESULT: 0x80004002)

(E_NONINTERFACE)

Download the source code from the link below.

Download Source Code