MSGraph – mail

Send mail via Graph

$AppId = "xxx"  
$TenantId = "xxx"  
$AppSecret = 'xxx'  

$uri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"  
$body = @{  
    client_id     = $AppId
    scope         = "https://graph.microsoft.com/.default"
    client_secret = $AppSecret
    grant_type    = "client_credentials" }  
  
$tokenRequest = Invoke-WebRequest -Method Post -Uri $uri -ContentType "application/x-www-form-urlencoded" -Body $body -UseBasicParsing  
$token = ($tokenRequest.Content | ConvertFrom-Json).access_token  
$headers = @{Authorization = "Bearer $token"}  

$accesstoken = ($token | ConvertTo-SecureString -AsPlainText -Force)
Connect-MgGraph -AccessToken $accesstoken -NoWelcome

$MailSenderUPN = "xxx@xxx.com"
$SendMailBody = @{
    Message = @{
        Subject = "Test"
        Body = @{
            ContentType = "HTML"
            Content =  "
                Test"`
        }
        ToRecipients = @(
            @{
                EmailAddress = @{
                    Address = 'yyy@xxx.com'
                }
            }
        )
    }
}
$SendMailUrl = "https://graph.microsoft.com/v1.0/users/$MailSenderUPN/SendMail"
Invoke-RestMethod -Uri $SendMailUrl -Headers @{Authorization = "Bearer $($token)"}  -Method Post -Body $($SendMailBody | convertto-json -depth 4) -ContentType "application/json; charset=utf-8"

Read mail through API

Invoke-RestMethod -Headers @{Authorization = "Bearer $($Tokenresponse.access_token)"} -Uri "https://graph.microsoft.com/v1.0/users/c@deuzk.com/mailFolders" -Method Get

Restrict send mail

Prérequis :
– Création d’un mail enabled security group, contenant les utilisateurs autorisés à émettre
– Récupération des valeurs suivantes :
– AppId : ApplicationId de votre application
– GrpName : Nom du groupe créé précédemment
– PolicyScopeGroupId : Email du groupe créé précédemment
– Ajout de la permission mail.send sur l’application

Se connecter au module Exchange-Online puis exécuter le bout de code suivant

$AppId = ""
$GrpName = ""
$PolicyScopeGroupId = ""
New-ApplicationAccessPolicy -AppId $AppId -PolicyScopeGroupId $PolicyScopeGroupId -AccessRight RestrictAccess -Description "Restrict this app to members of distribution group $GrpName"

Vérifier la bonne création de l’Application Access Policy :

Get-ApplicationAccessPolicy

Vous pourrez ensuite tester l’accès de votre application via la cmdlet :

Test-ApplicationAccessPolicy -Identity $GrpName -AppId $AppId