在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。