![](/img/trans.png)
[英]NEED SUGGESTION: How to write a Microsoft Outlook Add-In that can select multiple GROUPS(folders) of contacts all at once?
[英]Get Contacts from All Outlook Contact folders Microsoft Graph
我使用Microsoft Graph使用以下代码检索联系人文件夹:
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();
上面的代码返回联系人,但只返回默认文件夹中的联系人。 我想从所有用户的文件夹中检索联系人。
我尝试先获取文件夹,然后尝试获取联系人,但是当联系人为null
,它会返回Null Reference Exception
。
var Folders = client
.Me
.ContactFolders
.Request()
.Top(1000)
.GetAsync();
Folders.Wait();
var contacts = Folders.Result.SelectMany(a => a.Contacts).ToList();
我现在没有环境在这台机器上进行测试,但据我所知,你可以使用选项查询参数来过滤子文件夹中的联系人。
你需要找出所有的子文件夹
GET / users / {id | 通过UserPrincipalName} / contactFolders
在每个子文件夹中查找联系人
GET / me / contactFolder / {id} / childFolders / {id} / contacts
有关更多联系人文件夹和联系人相关信息 请阅读这些文档。 https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/user_list_contactfolders https://developer.microsoft.com/en-us/graph/docs/api-reference/beta / API / user_list_contacts
首先,此示例代码是在.net核心中创建的,您应该通过以下代码在配置中设置GraphScopes:
"GraphScopes": "User.Read User.ReadBasic.All Mail.Send MailBoxSettings.ReadWrite Contacts.ReadWrite"
另请注意,如果有多个文件夹,ContactFolders将仅返回结果。 永远不会返回默认的联系人文件夹。 如果用户没有其他文件夹,则返回空结果。 如果要获取主文件夹和分别获取它们所需的其他文件夹,请合并结果。
// 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.