简体   繁体   中英

How Can I use EWS to retrieve Outlook contacts?

I want my outlook contacts to be displayed in a Grid View. How can Exchange webservice help me in that?

First off, grab EWS from NuGet:

Install-Package EWS-Api-2.0

Next, establish a connection to your Exchange server:

String username = "account@contoso.com";
String password = "mypassword";

ExchangeService ews = new ExchangeService();
ews.Credentials = new WebCredentials(username, password);

// If you have the Exchange URI, it's faster to provide it. However,
// if you don't you can auto-acquire it. User EITHER of the following:
ews.Url = new Url("https://exchange.server.com/ews/exchange.asmx"); // your own URL
ews.AutodiscoverUrl(username, x => {
  // here you can validate `x`. For testing purposes, allow all Urls
  return true;
});

Next, we grab the contacts:

// Contacts sit in the "contacts" folder
Folder contactsFolder = Folder.Bind(ews, WellKnownFolderName.Contacts);
// grab 100 entries at a time
ItemView itemView = new ItemView(100); // list 100 entries at a time
// retrieve first 100
FinditemsResults<item> items = contactsFolder.FindItems(itemView);

// iterate over the entries
foreach (var contact in items.OfType<Contact>())
{
    Console.WriteLine(contact.Id.UniqueId);
    Console.WriteLine("\t{0,-20}: {1}", "NickName", contact.NickName);
    Console.WriteLine("\t{0,-20}: {1}", "DisplayName", contact.DisplayName);
    Console.WriteLine("\t{0,-20}: {1}", "Email Address", contact.EmailAddresses[0]);
    Console.WriteLine();
}

From there, you can place the above in a loop and check items.MoreAvailable to see if you need to grab another 100 entries. Make sure to also provide the offset parameter to the ItemView on subsequent calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM