Click here to Skip to main content
15,886,798 members
Articles / Programming Languages / C#

Outlook Address Collector

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
15 Jul 2011CPOL3 min read 28K   804   10  
Extracts recipients from an email using Outlook
using System;
using System.Windows.Forms;
using System.IO;
using System.DirectoryServices;
using System.Management;


namespace OutlookAddressCollector
{
    public partial class Form1 : Form
    {

        //global variables NOT ELEGANT!!!!!!
        Microsoft.Office.Interop.Outlook.Application myApp ;
        Microsoft.Office.Interop.Outlook.NameSpace mapiNameSpace;
        Microsoft.Office.Interop.Outlook.MAPIFolder myInbox;
        int st;
            
        public Form1()
        {
            InitializeComponent();
        }


        // Gets users email address, when recipient is a member of an Active Directory (i.e in a company)
        private static string getLDAPvalue(string ldapserver, string legacyexchangedn, string ldapuser, string ldappasword)
        {
            string strLDAPPath = "";
            string x = "";
            DirectoryEntry objSearchRoot;
            try
            {


                strLDAPPath = "LDAP://" + ldapserver;

                if (ldapuser == "")
                {
                    objSearchRoot = new DirectoryEntry(strLDAPPath);
                }
                else
                {
                    objSearchRoot = new DirectoryEntry(strLDAPPath, ldapuser, ldappasword, AuthenticationTypes.ReadonlyServer);
                }

                DirectorySearcher objDirectorySearcher = new DirectorySearcher(objSearchRoot);
                objDirectorySearcher.Filter = "(&(objectClass=person)(legacyexchangedn=" + legacyexchangedn + "))";
                objDirectorySearcher.PropertiesToLoad.Add("mail");

                SearchResult objSearchResult;
                objSearchResult = objDirectorySearcher.FindOne();
                if (!(objSearchResult == null))
                {
                    ResultPropertyValueCollection objValueCollection;
                    objValueCollection = objSearchResult.Properties["mail"];

                    foreach (object objPropertyValue in objValueCollection)
                    {
                        x = x + objPropertyValue.ToString();
                    }

                }
                else
                {
                    x = "No hits";
                }
                objDirectorySearcher.CacheResults = false;
                objDirectorySearcher.Dispose();
            }
            catch (Exception ex)
            {
                x = "";
                MessageBox.Show(ex.Message);
            }
            return x;
        }


        //Refresh datagrid
        private void Refresh(int start)
        {

            try
            {
                if (myInbox.Items.Count == 0)
                {
                    throw new System.Exception("There are no emails in your Inbox.");
                }

                int db = 10;

                if (start - 10 < 0) db = start;

                if (start > myInbox.Items.Count) start = myInbox.Items.Count;



                dataGridView1.Rows.Clear();

                int x = 0;

                for (int i = start; i > start - db; i--)
                {


                    x = dataGridView1.Rows.Add();

                    dataGridView1.Rows[x].Cells[0].Value = i.ToString();
                    dataGridView1.Rows[x].Cells[1].Value = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[i]).SenderName;
                    dataGridView1.Rows[x].Cells[2].Value = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[i]).Subject;
                    dataGridView1.Rows[x].Cells[3].Value = String.Format("{0:yyyy.MM.dd HH:mm:ss}", ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[i]).ReceivedTime);

                    x++;
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }


        private void button2_Click(object sender, EventArgs e)
        {
            Refresh(st);
        }

        // Gets computers domain
        private string getdomain()
        {
            string domain = "";

            SelectQuery query = new SelectQuery("Win32_ComputerSystem");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

            foreach (ManagementObject mo in searcher.Get())
            {
                if ((bool)mo["partofdomain"] == true)
                    domain = String.Format("{0}", mo["domain"]);
            }

            return domain;
        }



        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
          
            textBox2.Text = getdomain();
            myApp = new Microsoft.Office.Interop.Outlook.ApplicationClass();
            mapiNameSpace = myApp.GetNamespace("MAPI");
            myInbox = mapiNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
            st = myInbox.Items.Count;
            Refresh(st);
            dataGridView1_CellClick(sender, null);
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            st = st - 10;
            if (st < 10) st = 10;
            Refresh(st);
            dataGridView1_CellClick(sender, null);

        }

        public void button4_Click(object sender, EventArgs e)
        {
            st = st + 10;
            if (st > myInbox.Items.Count) st = myInbox.Items.Count;
            Refresh(st);
            dataGridView1_CellClick(sender, null);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            st = myInbox.Items.Count;
            Refresh(st);
            dataGridView1_CellClick(sender, null);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            st = 10;
            Refresh(st);
            dataGridView1_CellClick(sender, null);
        }




        //Saves attachments
        private void button1_Click(object sender, EventArgs e)
        {
            int rownum = dataGridView1.CurrentCell.RowIndex;
            int index = Convert.ToInt32(dataGridView1.Rows[rownum].Cells[0].Value);

            try
            {
                if (((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[1]).Attachments.Count == 0)
                {
                    throw new System.Exception("There aren't any attachment");

                }
                string foldername = "";
                DialogResult result = this.folderBrowserDialog1.ShowDialog();
                if (result == DialogResult.OK)
                {
                    foldername = this.folderBrowserDialog1.SelectedPath;
                }

                if (foldername == "")
                {
                    throw new System.Exception("Folder name is empty");
                }

                foreach (Microsoft.Office.Interop.Outlook.Attachment item in ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[1]).Attachments)
                {

                    string filename = Path.Combine(foldername, item.FileName);

                    item.SaveAsFile(filename);

                }



            }
            catch (System.Exception ex)
            {

                MessageBox.Show(ex.Message);
            }


        }



        // When You click on a datagrid cell.
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {

            int rownum = dataGridView1.CurrentCell.RowIndex;
            int index = Convert.ToInt32(dataGridView1.Rows[rownum].Cells[0].Value);

            string sendermail = "";

            textBox1.Text = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[index]).Subject;


            richTextBox1.Text = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[index]).Body;
            textBox3.Text = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[index]).SenderName;
            sendermail = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[index]).SenderEmailAddress;

            if (sendermail.Contains("CN="))
            {
                textBox4.Text = getLDAPvalue(textBox2.Text, sendermail, textBox8.Text, textBox9.Text);
            }
            else
            {
                textBox4.Text = sendermail;
            }



            textBox5.Text = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[index]).To;
            textBox6.Text = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[index]).CC;
            Microsoft.Office.Interop.Outlook.Recipients recipients = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[index]).Recipients;

            textBox7.Text = "";
            foreach (Microsoft.Office.Interop.Outlook.Recipient item in recipients)
            {
                if (item.Address.Contains("CN="))
                {
                    textBox7.Text = textBox7.Text +getLDAPvalue(textBox2.Text, item.Address, textBox8.Text, textBox9.Text) + Environment.NewLine;
                }
                else
                {
                    textBox7.Text = textBox7.Text + item.Address + Environment.NewLine;
                }
            }

        }
    }

}


By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Hungary Hungary
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions