[SMTP.SendAsApp] - Powershell script - Client Credential Flow for SMTP AUTH in Exchange Online

Why use "SMTP.SendAsApp"?

In Azure AD Application grant to SMTP.SendAsApp doesn't grant permissions to send unless the full mailbox permissions is added to the mailbox, whereas graph API permission "mail.send" application-level grant would allow application rights to send as anyone, so SMTP.SendAsApp makes it more secure to use, also when the message is sent it is saved in the user Sent Items.

How to use it?
  1. Register an App in Azure AD.
  2. Add API Permissions "SMTP.SendAsApp"
    1. Click on API Permissions >> Add Permissions >> API My Organization uses, Type "Office 365 Exchange Online" and select it. 
    2. Select "Application Permissions" 

    3. Grant Admin Consent.

    1. Next, Connect to Exchange Online and Azure AD and create a new Service Principal in Exchange Online.
      1. Run the following cmd to Create.
      2. $ASP=Get-AzureADServicePrincipal -Filter "DisplayName eq 'SMTP AUTH'"
        New-ServicePrincipal -DisplayName $ASP.DisplayName -AppId $ASP.AppId -ObjectId $ASP.ObjectId
        Add-MailboxPermission -AccessRights FullAccess -User $ASP.AppId -Identity labadmin@lab365.in
    2. After this, you are ready to send the message.
  3. To send the message download the script Send-MailMessageOauth.
  4. and use the code example below the send the mail message.
#app details for authentication
$secret="this is secret"
$appID="24dd196b-0f36-415e-b47f-2bcca0948db3"
$dirid="ab85c7a1-366d-44ba-acc6-924fa0950045"

#Fetch Token
$AT=Get-MsalToken -ClientId $appID -ClientSecret (ConvertTo-SecureString $secret -AsPlainText -Force) `
-TenantId $dirid -Scope 'https://outlook.office365.com/.default'

#Get-JWTDetails -token $at.AccessToken
$from="labadmin@lab365.in"
$to="Sunil@lab365.com"
Send-MailMessageOAuth -userName $from -To $to -Subject "Test msg using SMTP AUTH" `
-token $at.AccessToken -Body "This is a test msg."

Comments