当前位置: 首页 > 知识库问答 >
问题:

如何使用EWS托管API从Microsoft Exchange检索所有联系人?

阎咏思
2023-03-14
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个答案

徐峰
2023-03-14

似乎您在FindItems()方法方面已经做得很好了。

为了获得所有联系人,您需要添加的只是一个SearchFilter,在这种情况下,我建议使用Exists()筛选器,因为您可以简单地说查找带有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
 类似资料:
  • 我想从一个邮箱中搜索名字中包含某些关键字的所有附件,我正在使用C#EWS托管API(2.2版)来完成这一操作。我可以使用Item.hasAttachment:true属性访问带有附件的项,并且代码按预期工作。但办理时间很长。 我需要知道是否有一个更好更快的方法来访问一个邮箱/文件夹中的附件使用EWS。不是检查每一个邮件项目,有没有一种方法应用过滤器的附件在文件夹级别? 下面是用于按name关键字提

  • 我正在尝试使用EWS获取所有联系人(全局地址列表和用户联系人文件夹)。 > service.resolveName(“smtp:”)-这有一个限制,即只获取前100个字符,因为我希望获取所有联系人,以便可以在网格中与分页一起显示。此外,打开returnContactDetail=true(以及特定于联系人架构的属性设置)不会返回联系人信息(显示名称、公司名称等) NameResolutionCol

  • 如何知道使用Exchange EWS API共享了哪个日历。

  • 当我在AEM上使用下面的查询QueryDebug 以及形成的URL/JSON QueryBuilder链接。 我可以看到每个资产的所有属性,包括jcr:内容,元数据如下: 我需要将相同的结果返回到服务/endpoint,我正在为客户构建AEM。当我将上述查询转换为查询生成器API时 如何检索所有值? 如果我使用,我们只能看到下的属性,而不能看到其他属性。 和 如果我使用

  • 我正在尝试使用查询检索dynamodb表中的所有项。下面是我的代码: 但是,我收到以下错误: 我的代码非常简单,出自boto dynamodb2文档,因此我不确定为什么会出现上述错误。任何见解都将受到赞赏(这是新的,有点迷失)。谢谢 编辑:我有一个散列键和一个范围键。我能够通过特定的哈希键进行查询。例如 但我如何检索所有项目?

  • 如何在不创建多个字符串的情况下获得所有列和记录?假设我在那个表中有10列,我不需要把它存储到一个对象中 谢了。