How to: Search for an E-Mail Address in Contacts

Applies to

The information in this topic applies only to the specified Visual Studio Tools for Office projects and versions of Microsoft Office.

Project type

  • Application-level projects

Microsoft Office version

  • Outlook 2003

  • Outlook 2007

For more information, see Features Available by Application and Project Type.

This example searches a contact folder for contacts that have the domain name example.com in their e-mail addresses.

Example

Private Sub ThisAddIn_Startup(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Startup
    SearchForEmail("example.com")
End Sub 

Public Sub SearchForEmail(ByVal partialAddress As String)
    Dim contactMessage As String = String.Empty
    Dim contacts As Outlook.MAPIFolder = Me.Application.ActiveExplorer().Session _
        .GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts)
    For Each foundContact As Outlook.ContactItem In contacts.Items
        If Not (foundContact.Email1Address Is Nothing) Then 
            If foundContact.Email1Address.Contains(partialAddress) Then
                contactMessage = contactMessage & "New contact" _
                & foundContact.FirstName & " " & foundContact.LastName _
                & " Email Address is " & foundContact.Email1Address & _
                ". " & vbCrLf
            End If 
        End If 
    Next 
    If contactMessage.Length > 0 Then 
    Else
        contactMessage = "No Contacts were found." 
    End If
    MessageBox.Show(contactMessage)
End Sub
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    SearchforEmail("example.com");
}

private void SearchforEmail(string partialAddress)
{
    string contactMessage = string.Empty;
    Outlook.MAPIFolder contacts = (Outlook.MAPIFolder)
        this.Application.ActiveExplorer().Session.GetDefaultFolder
         (Outlook.OlDefaultFolders.olFolderContacts);
    foreach (Outlook.ContactItem foundContact in contacts.Items)
    {
                     if (foundContact.Email1Address != null)
                     {              
                         if (foundContact.Email1Address.Contains(partialAddress))
         {
            contactMessage = contactMessage + "New contact"
            + foundContact.FirstName + " " + foundContact.LastName
            + " Email Address is " + foundContact.Email1Address +
            ". \n";
         }
                     } 
    }
    if (!(contactMessage.Length > 0))
    {
        contactMessage = "No Contacts were found.";
    }
    MessageBox.Show(contactMessage);
}

Compiling the Code

This example requires:

  • Contacts that have the domain name example.com in their e-mail addresses (for example, somebody@example.com), and that have first names and last names.

See Also

Tasks

How to: Send E-Mail Programmatically

How to: Access Outlook Contacts

How to: Add an Entry to Outlook Contacts

Concepts

Working with Contact Items