如何使用 EWS 托管 API 从 Microsoft Exchange 检索所有联系人?
Posted
技术标签:
【中文标题】如何使用 EWS 托管 API 从 Microsoft Exchange 检索所有联系人?【英文标题】:How to retrieve all contacts from Microsoft Exchange using EWS Managed API? 【发布时间】:2016-05-13 10:44:15 【问题描述】:我需要做的就是从 Microsoft Exchange 检索所有联系人。我做了一些研究,对我来说最好的选择应该是使用 EWS 托管 API。我正在使用 Visual Studio 和 C# 编程语言。
我认为我能够连接到 Office365 帐户,因为我能够在程序中向特定电子邮件发送消息。但我无法检索联系人。
如果我直接在源代码中创建联系人,联系人将在 Office365->人员应用程序中创建。但我不知道为什么!我以为我正在使用 Exchange 应用程序。
总结: 是否有可能如何从 Office365->Admin->Exchange->Acceptencers->Contacts 获取所有联系人?
这是我的代码:
class Program
static void Main(string[] args)
// connecting to my Exchange account
ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.Credentials = new WebCredentials("office365email@test.com", "password123");
/*
// debugging
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
*/
service.AutodiscoverUrl("office365email@test.com", RedirectionUrlValidationCallback);
// send a message works good
EmailMessage email = new EmailMessage(service);
email.ToRecipients.Add("matoskok1@gmail.com");
email.Subject = "HelloWorld";
email.Body = new MessageBody("Toto je testovaci mail");
email.Send();
// Create the contact creates a contact in Office365 -> People application..Don't know why there and not in Office365 -> Exchange
/*Contact contact = new Contact(service);
// Specify the name and how the contact should be filed.
contact.GivenName = "Brian";
contact.MiddleName = "David";
contact.Surname = "Johnson";
contact.FileAsMapping = FileAsMapping.SurnameCommaGivenName;
// Specify the company name.
contact.CompanyName = "Contoso";
// Specify the business, home, and car phone numbers.
contact.PhoneNumbers[PhoneNumberKey.BusinessPhone] = "425-555-0110";
contact.PhoneNumbers[PhoneNumberKey.HomePhone] = "425-555-0120";
contact.PhoneNumbers[PhoneNumberKey.CarPhone] = "425-555-0130";
// Specify two email addresses.
contact.EmailAddresses[EmailAddressKey.EmailAddress1] = new EmailAddress("brian_1@contoso.com");
contact.EmailAddresses[EmailAddressKey.EmailAddress2] = new EmailAddress("brian_2@contoso.com");
// Specify two IM addresses.
contact.ImAddresses[ImAddressKey.ImAddress1] = "brianIM1@contoso.com";
contact.ImAddresses[ImAddressKey.ImAddress2] = " brianIM2@contoso.com";
// Specify the home address.
PhysicalAddressEntry paEntry1 = new PhysicalAddressEntry();
paEntry1.Street = "123 Main Street";
paEntry1.City = "Seattle";
paEntry1.State = "WA";
paEntry1.PostalCode = "11111";
paEntry1.CountryOrRegion = "United States";
contact.PhysicalAddresses[PhysicalAddressKey.Home] = paEntry1;
// Specify the business address.
PhysicalAddressEntry paEntry2 = new PhysicalAddressEntry();
paEntry2.Street = "456 Corp Avenue";
paEntry2.City = "Seattle";
paEntry2.State = "WA";
paEntry2.PostalCode = "11111";
paEntry2.CountryOrRegion = "United States";
contact.PhysicalAddresses[PhysicalAddressKey.Business] = paEntry2;
// Save the contact.
contact.Save();
*/
// msdn.microsoft.com/en-us/library/office/jj220498(v=exchg.80).aspx
// Get the number of items in the Contacts folder.
ContactsFolder contactsfolder = ContactsFolder.Bind(service, WellKnownFolderName.Contacts);
Console.WriteLine(contactsfolder.TotalCount);
// Set the number of items to the number of items in the Contacts folder or 50, whichever is smaller.
int numItems = contactsfolder.TotalCount < 50 ? contactsfolder.TotalCount : 50;
// Instantiate the item view with the number of items to retrieve from the Contacts folder.
ItemView view = new ItemView(numItems);
// To keep the request smaller, request only the display name property.
view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ContactSchema.DisplayName);
// Retrieve the items in the Contacts folder that have the properties that you selected.
FindItemsResults<Item> contactItems = service.FindItems(WellKnownFolderName.Contacts, view);
// Display the list of contacts.
foreach (Item item in contactItems)
if (item is Contact)
Contact contact1 = item as Contact;
Console.WriteLine(contact1.DisplayName);
Console.ReadLine();
// end of Main() method
/*===========================================================================================================*/
private static bool CertificateValidationCallBack(
object sender,
System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
// If the certificate is a valid, signed certificate, return true.
if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None)
return true;
// If there are errors in the certificate chain, look at each error to determine the cause.
if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) != 0)
if (chain != null && chain.ChainStatus != null)
foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus)
if ((certificate.Subject == certificate.Issuer) &&
(status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot))
// Self-signed certificates with an untrusted root are valid.
continue;
else
if (status.Status != System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError)
// If there are any other errors in the certificate chain, the certificate is invalid,
// so the method returns false.
return false;
// When processing reaches this line, the only errors in the certificate chain are
// untrusted root errors for self-signed certificates. These certificates are valid
// for default Exchange server installations, so return true.
return true;
else
// In all other cases, return false.
return false;
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
// The default for the validation callback is to reject the URL.
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
if (redirectionUri.Scheme == "https")
result = true;
return result;
【问题讨论】:
【参考方案1】:看起来你已经在 FindItems() 方法上做得很好了。
为了获取所有联系人,您只需要添加一个 SearchFilter,在这种情况下,我建议您使用 Exists() 过滤器,因为您可以简单地说 Find All contacts with an id。
如果您需要处理联系人的完整 Windows 应用程序示例,请参阅下面的示例,请参阅我的 github 页面 github.com/rojobo
Dim oFilter As New SearchFilter.Exists(ItemSchema.Id)
Dim oResults As FindItemsResults(Of Item) = Nothing
Dim oContact As Contact
Dim blnMoreAvailable As Boolean = True
Dim intSearchOffset As Integer = 0
Dim oView As New ItemView(conMaxChangesReturned, intSearchOffset, OffsetBasePoint.Beginning)
oView.PropertySet = BasePropertySet.IdOnly
Do While blnMoreAvailable
oResults = pService.FindItems(WellKnownFolderName.Contacts, oFilter, oView)
blnMoreAvailable = oResults.MoreAvailable
If Not IsNothing(oResults) AndAlso oResults.Items.Count > 0 Then
For Each oExchangeItem As Item In oResults.Items
Dim oExchangeContactId As ItemId = oExchangeItem.Id
//do something else
Next
If blnMoreAvailable Then oView.Offset = oView.Offset + conMaxChangesReturned
End If
Loop
【讨论】:
匈牙利表示法还活着!我已经十多年没见过了。【参考方案2】:How to retrieve all contacts from Microsoft Exchange using EWS Managed API?
如果您的问题是如何使用 EWS 检索 Exchange 联系人,那么您已经完成了。
Office365->People 是处理您的 Exchange 联系人的正确应用。如果您查看 People 应用程序 URL,它类似于 https://outlook.office365.com/owa/?realm=xxxxxx#exsvurl=1&ll-cc=1033&modurl=2,owa 是 Outlook Web 应用程序的同义词。
【讨论】:
您好 Jackie,谢谢您的回答。我需要从outlook.office365.com/owa/…获取所有联系人 具体来自Office365->People->通讯录 outlook.office365.com/owa/…> 是的,那么您已经拥有的代码就是这样做的方法。 好的,现在可以了。那么全球地址列表 (GAL) 呢?有什么方法可以使用 EWS Managed APi 从 GAL 获取信息? 如果这回答了你的问题,你能标记一下吗?我们可以打开一个新问题来使用 EWS 访问 GAL。以上是关于如何使用 EWS 托管 API 从 Microsoft Exchange 检索所有联系人?的主要内容,如果未能解决你的问题,请参考以下文章