从所有 Outlook 联系人文件夹中获取联系人 Microsoft Graph联系人、文件、夹中、Outlook

2023-09-07 09:12:36 作者:残蝉躁晚

我正在使用 Microsoft Graph 使用以下代码检索联系人文件夹:

I am using Microsoft Graph to retrieve Contact Folders using the following code:

GraphServiceClient client = new GraphServiceClient(new DelegateAuthenticationProvider(
    (requestMessage) => {
        requestMessage.Headers.Authorization = 
          new AuthenticationHeaderValue("Bearer", accessToken);
        return Task.FromResult(0);
    }));

var contactsData = await client
    .Me
    .Contacts
    .Request()
    .Top(1000)
    .GetAsync();

上面的代码返回联系人,但只返回默认文件夹中的联系人.我想从所有用户的文件夹中检索联系人.

This above code returns the Contacts, but only returns Contacts from the default folder. I want to retrieve Contacts from all of the user's folders.

我尝试过先获取文件夹,然后再获取联系人,但它返回 Null Reference Exception,因为联系人为 null.

I have tried like getting folders first and then their contacts, but it returns a Null Reference Exception as Contacts are null.

var Folders = client
    .Me
    .ContactFolders
    .Request()
    .Top(1000)
    .GetAsync();

Folders.Wait();
var contacts = Folders.Result.SelectMany(a => a.Contacts).ToList();

推荐答案

首先,这个示例代码是在.net core中创建的,你应该通过以下代码在配置中设置GraphScopes:

First of all, this sample code is created in .net core, you should set up GraphScopes in configuration by following code:

"GraphScopes": "User.Read User.ReadBasic.All Mail.Send MailBoxSettings.ReadWrite Contacts.ReadWrite"

另请注意,ContactFolders 仅在有多个文件夹时才会返回结果.永远不会返回默认的联系人文件夹.如果用户没有其他文件夹,这将返回一个空结果.如果要获取主文件夹和需要分别获取的附加文件夹然后合并结果.

Also note that ContactFolders will only return results if there are multiple folders. The default Contacts folder is never returned. If a user has no additional folders, this will return an empty result. If you want to get the main folder and the additional folders you need to get them respectively then combine the result.

// Get the defaultContacts
var defaultContacts = await graphClient
    .Me
    .Contacts
    .Request()
    .GetAsync();

// Get the contactFolders
var contactFolders = await graphClient
    .Me
    .ContactFolders
    .Request()
    .GetAsync();

// Use this to store the contact from all contact folder.
List<Contact> contactFolderContacts = new List<Contact>();

if (contactFolders.Count > 0) {
    for (int i = 0; i < contactFolders.Count; i++) {
        var folderContacts = await graphClient
            .Me
            .ContactFolders[contactFolders[i].Id]
            .Contacts
            .Request()
            .GetAsync();

        contactFolderContacts.AddRange(folderContacts.AsEnumerable());
    }

    // This will combine the contact from main folder and the additional folders.
    contactFolderContacts.AddRange(defaultContacts.AsEnumerable());
} else {
    // This user only has the default contacts folder
    contactFolderContacts.AddRange(defaultContacts.AsEnumerable());
}

// Use this to test the result.
foreach (var item in contactFolderContacts) {
    Debug.WriteLine("first:" + item.EmailAddresses);
}