在C#中,使用Exchange Web Services (EWS) 可以實現對Microsoft Exchange Server上的聯系人信息進行管理。以下是一個簡單的示例,展示了如何使用EWS API添加、查詢和刪除聯系人:
首先,確保已安裝Microsoft.Exchange.WebServices
NuGet包。在Visual Studio中,可以通過以下步驟安裝:
然后,編寫代碼來管理聯系人:
using System;
using Microsoft.Exchange.WebServices.Data;
namespace EwsContactsDemo
{
class Program
{
static void Main(string[] args)
{
// 設置Exchange服務器連接
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
service.Credentials = new WebCredentials("username", "password", "domain");
service.Url = new Uri("https://your-exchange-server/ews/exchange.asmx");
// 創建新聯系人
Contact newContact = new Contact(service);
newContact.GivenName = "John";
newContact.Surname = "Doe";
newContact.EmailAddresses[EmailAddressKey.EmailAddress1] = new EmailAddress("john.doe@example.com");
newContact.PhoneNumbers[PhoneNumberKey.MobilePhone] = "555-1234";
newContact.Save();
// 查詢聯系人
SearchFilter searchFilter = new SearchFilter.IsEqualTo(ContactSchema.EmailAddress1, "john.doe@example.com");
ItemView itemView = new ItemView(10);
FindItemsResults<Item> contactResults = service.FindItems(WellKnownFolderName.Contacts, searchFilter, itemView);
foreach (Contact contact in contactResults)
{
Console.WriteLine($"Name: {contact.DisplayName}");
Console.WriteLine($"Email: {contact.EmailAddresses[EmailAddressKey.EmailAddress1].Address}");
Console.WriteLine($"Phone: {contact.PhoneNumbers[PhoneNumberKey.MobilePhone]}");
}
// 刪除聯系人
if (contactResults.TotalCount > 0)
{
Contact contactToDelete = contactResults.Items[0] as Contact;
contactToDelete.Delete(DeleteMode.HardDelete);
}
}
}
}
請注意,您需要將上述代碼中的username
、password
、domain
和your-exchange-server
替換為實際的Exchange服務器連接信息。
這個示例展示了如何使用EWS API創建、查詢和刪除聯系人。您可以根據需要修改代碼以滿足您的需求。更多關于EWS API的信息,請參考官方文檔:Exchange Web Services (EWS) Managed API。