Public/Get-NSPConditionalAccessCoverageMailSetup.ps1

function Get-NSPConditionalAccessCoverageMailSetup {
    <#
    .SYNOPSIS
        Offline: the Exchange Online commands that let the coverage app send reports as one mailbox only.
    .DESCRIPTION
        The coverage app is never granted Mail.Send in Entra ID: that permission can send as any
        mailbox in the tenant. Exchange Online RBAC for Applications instead grants the role
        'Application Mail.Send' limited to a management scope that matches the one sender mailbox.
 
        Run the returned commands in Exchange Online PowerShell (ExchangeOnlineManagement) as an
        Exchange administrator, then turn the reports on:
            Set-NSPConditionalAccessCoverageSetting -TenantProfile $profilePath -MailFrom <sender> -MailTo <recipients>
        Nothing here changes the tenant; the admin runs the commands.
    .EXAMPLE
        (Get-NSPConditionalAccessCoverageMailSetup -TenantProfile $profilePath -From 'alerts@contoso.example').Commands
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]$TenantProfile,
        [Parameter(Mandatory)][string]$From,
        [string]$ConfigRoot
    )

    if ($TenantProfile -is [string]) { $TenantProfile = Get-Content -LiteralPath $TenantProfile -Raw | ConvertFrom-Json }
    $tenantId = Get-NSPConditionalAccessMapValue $TenantProfile 'TenantId'
    $recordPath = Join-Path (Get-NSPConditionalAccessLocalPath -Kind CoverageApps -ConfigRoot $ConfigRoot) "$tenantId.json"
    if (-not (Test-Path -LiteralPath $recordPath)) { throw 'No coverage app is registered on this host. Run Register-NSPConditionalAccessCoverageApp -Execute first.' }
    $record = Get-Content -LiteralPath $recordPath -Raw | ConvertFrom-Json
    $objectId = if ($record.PSObject.Properties['ServicePrincipalId'] -and $record.ServicePrincipalId) { $record.ServicePrincipalId }
    else { '<object ID of the NSP-M365-ConditionalAccess-Coverage enterprise application>' }
    $scope = 'NSP coverage report sender'
    $senderAddress = $From -replace "'", "''"

    [pscustomobject]@{
        ClientId = $record.ClientId
        From = $From
        Commands = @(
            'Connect-ExchangeOnline'
            "New-ServicePrincipal -AppId '$($record.ClientId)' -ObjectId '$objectId' -DisplayName 'NSP-M365-ConditionalAccess-Coverage'"
            "New-ManagementScope -Name '$scope' -RecipientRestrictionFilter `"PrimarySmtpAddress -eq '$senderAddress'`""
            "New-ManagementRoleAssignment -App '$($record.ClientId)' -Role 'Application Mail.Send' -CustomResourceScope '$scope'"
            "Test-ServicePrincipalAuthorization -Identity '$($record.ClientId)' -Resource '$senderAddress' # expect InScope True for Application Mail.Send"
        )
        Next = "Then: Set-NSPConditionalAccessCoverageSetting -TenantProfile <profile> -MailFrom '$From' -MailTo <recipients> [-MailWhen Problems|Changes|Always]"
    }
}