Skip to main content
Skip table of contents

PowerShell Script: Test mailbox access via Graph API

Use this script to test credentials for o365 mailbox access.

Note: Graph API is the modern approach to credentialing to Office 365 mailboxes. EWS is deprecated. Refer to the annountment here for more detail. All customer’s should migrate to Graph API mailbox access.

  • Requests for a Graph access token using client credentials

  • Calls /users/{mailbox}/messages to confirm the app can read the mailbox

  • Surfaces permission or consent issues cleanly

POWERSHELL
# ============================================
# Variables
# ============================================
$tenantId     = "<TENANT_ID>"
$clientId     = "<CLIENT_ID>"
$clientSecret = "<CLIENT_SECRET>"
$mailbox      = "user@domain.com"

# ============================================
# Request OAuth2 Token for Microsoft Graph
# ============================================
$tokenBody = @{
    client_id     = $clientId
    scope         = "https://graph.microsoft.com/.default"
    client_secret = $clientSecret
    grant_type    = "client_credentials"
}

$tokenResponse = Invoke-RestMethod `
    -Method Post `
    -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" `
    -Body $tokenBody

$accessToken = $tokenResponse.access_token

if (-not $accessToken) {
    Write-Host "Failed to obtain access token" -ForegroundColor Red
    exit
}

Write-Host "Access token acquired successfully" -ForegroundColor Green

# ============================================
# Test Mailbox Access via Microsoft Graph
# ============================================
$headers = @{
    Authorization = "Bearer $accessToken"
}

$graphUrl = "https://graph.microsoft.com/v1.0/users/$mailbox/messages?`$top=1"

try {
    $result = Invoke-RestMethod -Method Get -Uri $graphUrl -Headers $headers
    Write-Host "Successfully accessed mailbox: $mailbox" -ForegroundColor Green

    if ($result.value) {
        Write-Host "Sample message:" 
        $result.value | Select-Object subject, receivedDateTime
    } else {
        Write-Host "Mailbox is accessible but contains no messages"
    }
}
catch {
    Write-Host "Failed to access mailbox: $mailbox" -ForegroundColor Red
    Write-Host $_.Exception.Message
}
JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.