You'd want to build an array of PSCustomObjects, that looks something like this:
$rows = [PSCustomObject]@{UPN = 'bernard@bernarc'; "Unread email Count" = 21;"Emails not flagged count" = 21;"Total Inbox emails" = 21},
[PSCustomObject]@{UPN = 'BernardMwanza@'; "Unread email Count" = 69;"Emails not flagged count" = 99;"Total Inbox emails" = 99},
[PSCustomObject]@{UPN = 'Test_Userberna@'; "Unread email Count" = 4;"Emails not flagged count" = 4;"Total Inbox emails" = 4}
I haven't run this, but add your code to it in the appropriate places:
$body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>MY HTML MESSAGE BODY</title>
</head><body>
The report for your users emails actions is:\b\b
'
$body = "The report for your users emails actions is:\b\b"
$props = @{ SMTPServer = "smtp.office365.com"
From = "fromemailhere"
To = "toemailhere"
Subject = "OFFICE 365 USER MAILBOXES AUDIT"
EnableSsl = $true
Port = 587
BodyAsHtml = $true
Credentials = New-Object System.Net.NetworkCredential("emailaddress", "passwordhere");
}
[array]$rows = @()
# YOUR code to get the list of users, connections, tokens, etc. goes here
###### process the users here
foreach ($mailUser in $mailUsers) {
# grab all users UPNs
$mail_user = $mailUser.UserPrincipalName
# grab unread emails count
$graphuri = "https://graph.microsoft.com/v1.0/users/$mail_user/mailfolders/Inbox/messages?filter=isRead ne true&count=true"
# Grab unflagged emails count
$graphuri_1 = "https://graph.microsoft.com/v1.0/users/$mail_user/mailfolders/Inbox/messages?$filter=flag/flagStatus ne 'flagged' & flag/flagStatus ne 'complete'&count=true"
# grab total inbox emails count
$graphuri_2 = "https://graph.microsoft.com/v1.0/users/$mail_user/mailfolders/Inbox/messages?$skip=0&count=true"
$resp = Invoke-RestMethod -Method get -Uri $graphuri -ContentType "application/json" -Headers @{Authorization = ("bearer {0}" -f $accessToken) }
$resp_1 = Invoke-RestMethod -Method get -Uri $graphuri_1 -ContentType "application/json" -Headers @{Authorization = ("bearer {0}" -f $accessToken) }
$resp_2 = Invoke-RestMethod -Method get -Uri $graphuri_2 -ContentType "application/json" -Headers @{Authorization = ("bearer {0}" -f $accessToken) }
$rows += [PSCustomObject]@{
UPN = $mail_user
"Unread email Count" = $resp.'@odata.count'
"Emails not flagged count" = $resp_1.'@odata.count'
"Total Inbox emails" = $resp_2.'@odata.count'
}
}
$body += $rows | ConvertTo-Html -Fragment
Send-MailMessage @props -body $body
# you can export the $rows array to a CSV here (no need to append):
$rows | Export-CSV $reportfile -NoTypeInformation