Reputation: 11
I've got some draft code, eventually I will modify this to output daily via email, but am wondering if anyone knows how to get it to output more than 10 results. I'm querying emails sent by a certain mailbox, but I only get 10 results. The link for futher results seems to go into $sentemails.'@odata.nextLink' , but I basically want to get all the results dumping into $sentemails then I can export that to a csv. Please can someone help me?
Connect-MgGraph
# Define variables
$TenantId = "CENSORED"
$ClientId = "CENSORED"
$ClientSecret = "CENSORED"
$UserPrincipalName = "CENSORED"
# Define date range for filtering (change as needed)
$StartDate = "2025-02-10T00:00:00Z"
$EndDate = "2025-02-11T00:00:00Z"
# Get authentication token using client credentials
$Body = @{
grant_type = "client_credentials"
client_id = $ClientId
client_secret = $ClientSecret
scope = "https://graph.microsoft.com/.default"
}
$AuthResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token" -Method Post -Body $Body
$AccessToken = $AuthResponse.access_token
# Define headers for Microsoft Graph API
$Headers = @{
"Authorization" = "Bearer $AccessToken"
"Content-Type" = "application/json"
}
# Get received emails
$ReceivedEmailsUrl = "https://graph.microsoft.com/v1.0/users/$UserPrincipalName/messages?`$filter=receivedDateTime ge $StartDate and receivedDateTime lt $EndDate&`$select=subject,from,receivedDateTime"
$ReceivedEmails = Invoke-RestMethod -Uri $ReceivedEmailsUrl -Headers $Headers -Method Get
# Get sent emails
$SentEmailsUrl = "https://graph.microsoft.com/v1.0/users/$UserPrincipalName/mailFolders/sentitems/messages?`$filter=sentDateTime ge $StartDate and sentDateTime lt $EndDate&`$select=subject,toRecipients,sentDateTime"
$SentEmails = Invoke-RestMethod -Uri $SentEmailsUrl -Headers $Headers -Method Get
Write-Host "`nSent Emails for $UserPrincipalName"
$SentEmails.value | ForEach-Object { Write-Host "To: $($_.toRecipients.emailAddress.address) | Subject: $($_.subject) | Sent: $($_.sentDateTime)" }
#Link for further results
$sentemails.'@odata.nextLink'
Upvotes: 0
Views: 8