Skip to content

Instantly share code, notes, and snippets.

@runmaxde
Last active February 14, 2024 15:16
Show Gist options
  • Save runmaxde/c71132e9795419e9066195e01e62f106 to your computer and use it in GitHub Desktop.
Save runmaxde/c71132e9795419e9066195e01e62f106 to your computer and use it in GitHub Desktop.
outlook-grap-api-get-all-folders-and-ids.js
// Retrieve the token from the browser via https://developer.microsoft.com/en-us/graph/graph-explorer
// 1. Click "Sign in with Microsoft" and sign in with your account
// 2. Select a Outlook mailbox request, e.g. "GET /me/mailFolders"
// 3. Click Tab "Modify permissions", select "Mail.Read" and click "Modify permissions"
// 4. Click Tab "Access token" and copy the token
// 5. Paste the token into the const TOKEN below
const TOKEN = ""
// cleanup the graph response for /mailFolders request to only include the id, displayName and childFolderCount
function cleanupFoldersResponse(data) {
return data.value.map(({ id, displayName, childFolderCount }) => { return { id, displayName, childFolderCount } })
}
// fetch all root folders from the mailbox via the Graph API (https://graph.microsoft.com/v1.0/me/mailFolders)
async function fetchRootFolders() {
const response = await fetch('https://graph.microsoft.com/v1.0/me/mailFolders', {
method: 'GET',
headers: {
'Authorization': `Bearer ${TOKEN}`
}
})
const data = await response.json()
return data
}
// fetch all folders in a specific folder via the Graph API (https://graph.microsoft.com/v1.0/me/mailFolders/{folderId}/childFolders)
async function fetchFolders(folderId) {
const response = await fetch(`https://graph.microsoft.com/v1.0/me/mailFolders/${folderId}/childFolders`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${TOKEN}`
}
})
const data = await response.json()
return data
}
// ##### MAIN #####
// check if the ROOT_FOLDER_NAME exists and get its id
const root_folders_list = cleanupFoldersResponse(await fetchRootFolders())
//console.log(root_folders_list);
// fetch folders for each root folder
const root_with_sub_folders_list = await Promise.all(root_folders_list.map(async (folder) => {
if (folder.childFolderCount === 0) return { ...folder, childFolders: [] }
const childFolders = await fetchFolders(folder.id)
return {
...folder,
childFolders: cleanupFoldersResponse(childFolders)
}
}))
// log as tree
root_with_sub_folders_list.forEach((root) => {
console.log(`<${root.displayName}> (${root.id})`)
root.childFolders.forEach((sub) => {
console.log(` <${sub.displayName}> (${sub.id})`)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment