Extract/Export Email Addresses from Outlook

sknake 0 Tallied Votes 329 Views Share

I wanted to export a list of all email addresses I had corresponded with and was unable to find a free product to compile the list so I came up with this. You could take it a step further and scrape additional email addresses from the message body.

As far as calling the code:

void button1_Click(object sender, EventArgs e)
    {
      ThreadPool.QueueUserWorkItem(s => DoWork());
    }

    void DoWork()
    {
      OutlookEmailAddressExtractor extractor = new OutlookEmailAddressExtractor();
      string[] emails = extractor
         .GetAllAddress()
         .Where(addr => !string.IsNullOrEmpty(addr) && addr.Contains("@") && !addr.Contains(",") && !addr.Contains("="))
         .Distinct(StringComparer.OrdinalIgnoreCase)
         .OrderBy(s => s)
         .ToArray();

      string csv = string.Join(", ", emails);
      //save the csv list...

      string lst = string.Join(Environment.NewLine, emails);
      //save the list...

      Debugger.Break();
    }
kvprajapati commented: :) +15
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Outlook;

namespace WindowsFormsApplication3
{
  sealed class OutlookEmailAddressExtractor
  {
    Application m_application;
    NameSpace m_namespace;

    public OutlookEmailAddressExtractor()
    {
      m_application = new Application();
      m_namespace = m_application.GetNamespace("MAPI");
    }

    public IEnumerable<string> GetAllAddress()
    {
      //If you want to filter:
      //foreach (Store store in GetStores().Where(s => s.DisplayName == "Mailbox" || s.DisplayName == "Mailbox2"))

      foreach (Store store in GetStores())
      {
        foreach (Folder folder in GetFolders(store))
        {
          foreach (MailItem item in GetMailItems(folder))
          {
            foreach (string s in YieldRecipients(item.Recipients))
              yield return s;
            foreach (string s in YieldRecipients(item.ReplyRecipients))
              yield return s;
            if (!string.IsNullOrEmpty(item.SenderEmailAddress))
              yield return item.SenderEmailAddress;
          }
        }
      }
    }

    IEnumerable<string> YieldRecipients(Recipients recipients)
    {
      foreach (Recipient recip in recipients)
      {
        if (!string.IsNullOrEmpty(recip.Address))
        {
          yield return recip.Address;
        }

        string addr2 = null;
        try
        {
          if ((recip.AddressEntry != null) && (!string.IsNullOrEmpty(recip.AddressEntry.Address)))
          {
            addr2 = recip.AddressEntry.Address;
          }
        }
        catch (COMException ex)
        {
          Debug.WriteLine("COM Exception: " + ex.Message);
        }

        if (!string.IsNullOrEmpty(addr2))
          yield return addr2;
      }
    }

    IEnumerable<Folder> GetFolders(Store store)
    {
      Debug.WriteLine("Processing store: " + store.DisplayName);
      MAPIFolder rootFolder;

      try
      {
        rootFolder = store.GetRootFolder();
      }
      catch
      {
        yield break;
      }

      foreach (Folder folder in rootFolder.Folders)
      {
        foreach (Folder yieldFolder in GetFolders(folder))
        {
          yield return yieldFolder;
        }
      }
    }

    IEnumerable<Folder> GetFolders(Folder folder)
    {
      Debug.WriteLine("Folder: " + folder.Name);
      yield return folder;
      Debug.Indent();
      try
      {
        foreach (Folder childFolder in folder.Folders)
        {
          foreach (Folder yieldFolder in GetFolders(childFolder))
          {
            yield return yieldFolder;
          }
        }
      }
      finally
      {
        Debug.Unindent();
      }
    }

    IEnumerable<MailItem> GetMailItems(Folder folder)
    {
      foreach (object o in folder.Items)
      {
        MailItem mi;
        if ((mi = o as MailItem) != null)
          yield return mi;
      }
    }

    IEnumerable<Store> GetStores()
    {
      foreach (Store store in m_namespace.Stores)
      {
        yield return store;
      }
    }
  }
}
Rajwin.aravind 0 Newbie Poster
1  Option Strict Off
  2  Imports Microsoft.Office.Core
  3  Imports Outlook
  4  Imports System
  5  Imports System.IO
  6  Imports System.Text
  7  
  8  Public Class Form1
  9      Inherits System.Windows.Forms.Form
 10  
 11      Const conBasePath As String = "C:\TEMPOUTLOOK\"
 12  
 13  #Region " Windows Form Designer generated code "
 14  
 15      Public Sub New()
 16          MyBase.New()
 17  
 18          'This call is required by the Windows Form Designer.
 19          InitializeComponent()
 20  
 21          'Add any initialization after the InitializeComponent() call
 22  
 23      End Sub
 24  
 25      'Form overrides dispose to clean up the component list.
 26      Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
 27          If disposing Then
 28              If Not (components Is Nothing) Then
 29                  components.Dispose()
 30              End If
 31          End If
 32          MyBase.Dispose(disposing)
 33      End Sub
 34  
 35      'Required by the Windows Form Designer
 36      Private components As System.ComponentModel.IContainer
 37  
 38      'NOTE: The following procedure is required by the Windows Form Designer
 39      'It can be modified using the Windows Form Designer.  
 40      'Do not modify it using the code editor.
 41      Friend WithEvents btnRead As System.Windows.Forms.Button
 42      Friend WithEvents btnReadFile As System.Windows.Forms.Button
 43      <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
 44          Me.btnRead = New System.Windows.Forms.Button
 45          Me.btnReadFile = New System.Windows.Forms.Button
 46          Me.SuspendLayout()
 47          '
 48          'btnRead
 49          '
 50          Me.btnRead.Font = New System.Drawing.Font("Bookman Old Style", 11.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
 51          Me.btnRead.Location = New System.Drawing.Point(8, 8)
 52          Me.btnRead.Name = "btnRead"
 53          Me.btnRead.Size = New System.Drawing.Size(392, 48)
 54          Me.btnRead.TabIndex = 0
 55          Me.btnRead.Text = "Read Mails From Outlook And Save Locally"
 56          '
 57          'btnReadFile
 58          '
 59          Me.btnReadFile.Font = New System.Drawing.Font("Bookman Old Style", 11.25!)
 60          Me.btnReadFile.Location = New System.Drawing.Point(8, 64)
 61          Me.btnReadFile.Name = "btnReadFile"
 62          Me.btnReadFile.Size = New System.Drawing.Size(392, 48)
 63          Me.btnReadFile.TabIndex = 1
 64          Me.btnReadFile.Text = "Read Locally Saved Mails"
 65          '
 66          'Form1
 67          '
 68          Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
 69          Me.ClientSize = New System.Drawing.Size(416, 118)
 70          Me.Controls.Add(Me.btnReadFile)
 71          Me.Controls.Add(Me.btnRead)
 72          Me.Name = "Form1"
 73          Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
 74          Me.Text = "Read Outlook Data"
 75          Me.ResumeLayout(False)
 76  
 77      End Sub
 78  
 79  #End Region
 80  
 81      Private Sub btnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRead.Click
 82  
 83          'CHECKING FOLDER IS AVAILABLE OR NOT.
 84          'IF NOT CREATE IT ELSE DELETE AND CREATE AGAIN
 85          IsFolderAvailable()
 86  
 87          'METHOD FOR SAVING ALL MAIL ITEMS IN TO FOLDER.
 88          SaveAllMAPIFolderItems()
 89  
 90      End Sub
 91  
 92  #Region " METHOD FOR READING OUTLOOK MAIL ITEMS"
 93      'Don't change this code.
 94  
 95      Private Sub SaveAllMAPIFolderItems()
 96  
 97          Dim objOutlook As Outlook.Application
 98          Dim objNamespace As Outlook.NameSpace
 99          Dim objMAPIFolder As Outlook.MAPIFolder
100          Dim oNS As Outlook.NameSpace
101          Dim oInbox As Outlook.MAPIFolder
102          Dim oItem As Object   ' as Outlook.Mailitem 
103          Dim oAtt As Outlook.Attachment
104          Dim sSubject As String
105          Dim sType As String
106          Dim sSent As String
107  
108          Dim sUniqueFileName As String
109          Dim sUniqueAttFolderName As String
110  
111          objOutlook = New Outlook.Application
112          oNS = objOutlook.GetNamespace("MAPI")
113  
114          oNS.Logon(ShowDialog:=True, NewSession:=True)
115          'objMAPIFolder = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
116          objMAPIFolder = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail)
117  
118  
119          Try
120              For Each oItem In objMAPIFolder.Items
121  
122                  sSubject = oItem.Subject
123  
124                  'Dim someString As String = sSubject
125                  'Dim index As Integer = someString.IndexOf(":")
126                  'Dim replaced As String
127  
128                  'Dim character As Char
129                  'For Each character In someString
130                  '    If character = ":" Then
131                  '        replaced = someString.Replace(":", "")
132                  '    End If
133                  'Next
134  
135  
136                  'sUniqueFileName = conBasePath + replaced + "_bak_" + System.Guid.NewGuid().ToString
137  
138                  sUniqueFileName = conBasePath + "bak_" + System.Guid.NewGuid().ToString
139  
140                  oItem.SaveAs(sUniqueFileName + ".txt", Outlook.OlSaveAsType.olTXT)
141  
142                  If (oItem.Attachments.Count > 0) Then
143                      sUniqueAttFolderName = sUniqueFileName + "_Folder"
144                      MkDir(sUniqueAttFolderName)
145  
146                      For Each oAtt In oItem.Attachments
147                          sUniqueFileName = sUniqueAttFolderName + "\" + oAtt.FileName
148                          oAtt.SaveAsFile(sUniqueFileName)
149                      Next oAtt
150  
151                  End If
152  
153                  'End If 
154  
155              Next oItem
156  
157          Catch ex As System.Exception
158              MessageBox.Show(ex.ToString)
159          End Try
160  
161          oNS.Logoff()
162  
163          MsgBox("Processed", MsgBoxStyle.Information)
164  
165          If (MsgBoxResult.OK) Then
166              Me.Close()
167          End If
168  
169      End Sub
170  
171  #End Region
172  
173  #Region "CHECKING FOLDER IS AVAILABLE OR NOT"
174  
175      Private Sub IsFolderAvailable()
176  
177          Dim objDirInfo As Directory
178  
179          If objDirInfo.Exists(conBasePath) = True Then
180  
181              Directory.Delete(conBasePath, True)
182              Directory.CreateDirectory(conBasePath)
183  
184          Else
185  
186              Directory.CreateDirectory(conBasePath)
187  
188          End If
189  
190  
191      End Sub
192  
193  #End Region
194  
195  
196      Private Sub btnReadFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReadFile.Click
197  
198          Dim strFileSize As String = ""
199          Dim di As New IO.DirectoryInfo(conBasePath)
200          Dim aryFi As IO.FileInfo() = di.GetFiles("*.txt")
201          Dim fi As IO.FileInfo
202  
203          For Each fi In aryFi
204              Dim s As String
205              s = ReadTextFile(conBasePath & "\" & fi.Name)
206          Next
207  
208      End Sub
209  
210  
211      Private Function ReadTextFile(ByVal sFileName As String) As String
212  
213          Dim s As String
214  
215          Try
216              Dim oFile As FileStream = New FileStream(sFileName, FileMode.Open, FileAccess.Read, FileShare.Read)
217              Dim oReader As StreamReader = New StreamReader(oFile)
218  
219              s = oReader.ReadLine
220  
221              Dim strLine As String
222  
223              Do Until s Is Nothing
224                  strLine = oReader.ReadLine
225                  MsgBox(strLine)
226              Loop
227  
228  
229  
230              oReader.Close()
231              oFile.Close()
232  
233              ReadTextFile = s
234  
235          Catch
236  
237              ReadTextFile = "Unable to open file."
238  
239          End Try
240  
241      End Function
242  
243  
244  End Class
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.