Partager via


How to: Programmatically search for an email address in contacts

Applies to: yesVisual Studio noVisual Studio for Mac

Note

This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here

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

Applies to: The information in this topic applies to VSTO Add-in projects for Outlook. For more information, see Features available by Office application and project type.

Example

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    SearchforEmail("example.com");
}

private void SearchforEmail(string partialAddress)
{
    string contactMessage = string.Empty;
    Outlook.ContactItem foundContact;
    Outlook.MAPIFolder contacts = (Outlook.MAPIFolder)
        this.Application.ActiveExplorer().Session.GetDefaultFolder
         (Outlook.OlDefaultFolders.olFolderContacts);
    foreach (var contact in contacts.Items)
    {
        //The contacts folder may also distribution list so check to make sure we have a ContactItem
        if (contact is Outlook.ContactItem)
        {
            foundContact = contact as Outlook.ContactItem;
            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);
}

Compile 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