Using Powershell to Send Emails via 365

Finally can do this via OAuth ( No Username and password Azure APP ) AND Non-Interactive

https://github.com/richfaj/SmtpClientDiag/blob/master/SmtpClientDiag.psm1

$clientID = "XXXXXXXXXXX"
$Clientsecret = "XXXXXXXXXXX"
$tenantID = "XXXXXXXXXXX"

$MailSender = "[email protected]"

#Connect to GRAPH API
$tokenBody = @{
    Grant_Type    = "client_credentials"
    Scope         = "https://graph.microsoft.com/.default"
    Client_Id     = $clientId
    Client_Secret = $clientSecret
}
$tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenantID/oauth2/v2.0/token" -Method POST -Body $tokenBody
$headers = @{
    "Authorization" = "Bearer $($tokenResponse.access_token)"
    "Content-type"  = "application/json"
}

#Send Mail    
$URLsend = "https://graph.microsoft.com/v1.0/users/$MailSender/sendMail"
$BodyJsonsend = @"
                    {
                        "message": {
                          "subject": "Hello World from Microsoft Graph API",
                          "body": {
                            "contentType": "HTML",
                            "content": "This Mail is sent via Microsoft <br>
                            GRAPH <br>
                            API<br>
                            
                            "
                          },
                          "toRecipients": [
                            {
                              "emailAddress": {
                                "address": "[email protected]"
                              }
                            }
                          ]
                        },
                        "saveToSentItems": "false"
                      }
"@

Invoke-RestMethod -Method POST -Uri $URLsend -Headers $headers -Body $BodyJsonsend

SMTP Will be Decommed Soon ( Below )

  1. Make sure the account has an Exchange License
  2. Turn Security Default Off 
  3. Create an App Password for the account. MFA and Modern auth will Obviously be enabled for the account so you won’t be able to use thatIn Azure AD Get App Password for account


  1. Log into your Office 365 Admin account
  2. Click the Green HELP & SUPPORT button in the bottom left corner
  3. In the search bar, type:  Diag: Enable Basic Auth in EXO
  4. Click the Blue arrow to search
  5. Click the RUN TESTS button
  6. Once the tests are done, select SMTP in the Protocol to Opt Out dropdown.
  7. Click the check box below it.
  8. Click the UPDATE SETTINGS button
#New Security Policy

New-AuthenticationPolicy -Name "Allow Basic Auth for SMTP"
Set-AuthenticationPolicy -Identity "Allow Basic Auth for SMTP" -AllowBasicAuthWebServices:$false
Set-AuthenticationPolicy -Identity "Allow Basic Auth for SMTP" -AllowBasicAuthOutlookService:$false
Set-AuthenticationPolicy -Identity "Allow Basic Auth for SMTP" -AllowBasicAuthReportingWebServices:$false
Set-AuthenticationPolicy -Identity "Allow Basic Auth for SMTP" -AllowBasicAuthActiveSync:$false
Set-AuthenticationPolicy -Identity "Allow Basic Auth for SMTP" -AllowBasicAuthRest:$false
Set-AuthenticationPolicy -Identity "Allow Basic Auth for SMTP" -AllowBasicAuthPowershell:$false
Set-AuthenticationPolicy -Identity "Allow Basic Auth for SMTP" -AllowBasicAuthMapi:$false
Set-AuthenticationPolicy -Identity "Allow Basic Auth for SMTP" -AllowBasicAuthOfflineAddressBook:$false
Set-AuthenticationPolicy -Identity "Allow Basic Auth for SMTP" -AllowBasicAuthAutodiscover:$false
Set-AuthenticationPolicy -Identity "Allow Basic Auth for SMTP" -AllowBasicAuthRpc:$false
Set-AuthenticationPolicy -Identity "Allow Basic Auth for SMTP" -AllowBasicAuthSmtp:$true


#Apply Security Policy 

Set-User -Identity [email protected] -AuthenticationPolicy "Allow Basic Auth for SMTP"

#Turn on SMTP AUTH

Set-CASMailbox -Identity [email protected] -SmtpClientAuthenticationDisabled $false
# Enable TLS 1.2 as Security Protocol
[Net.ServicePointManager]::SecurityProtocol = `
    [Net.SecurityProtocolType]::Tls12 ;

#Username is UPN \ Email
#APP Password for password

$creds = Get-Credential

Send-MailMessage -From [email protected] -To [email protected] -Subject "Test Email" -Body "Test SMTP Service from Powershell on Port 587" -SmtpServer smtp.office365.com -Credential $creds -Usessl -Port 587
# Parameters
$fromEmail = "XXXXXXXXX"  # Your Office 365 email
$toEmail = "XXXXXXXXX"     # Recipient's email
$subject = "Test Email via SMTP"
$body = "This is a test email sent from PowerShell using an HVE account."
$smtpServer = "smtp.hve.mx.microsoft"
$smtpPort = 587
$username = "XXXXXXXXX"   # Your Office 365 email

$password = "XXXXXXXXX"  # Use app password if MFA is enabled, or regular password if basic auth is allowed



# Create credentials
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential ($username, $securePassword)




try {
    # Send email using Send-MailMessage
    Send-MailMessage `
        -From $fromEmail `
        -To $toEmail `
        -Subject $subject `
        -Body $body `
        -SmtpServer $smtpServer `
        -Port $smtpPort `
        -UseSsl `
        -Credential $credentials `
        -ErrorAction Stop

    Write-Host "Email sent successfully!" -ForegroundColor Green
}
catch {
    Write-Host "Error sending email: $_" -ForegroundColor Red
}
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...