Send email to O365 using Powershell when MFA is enabled

Mario onMicrosoft 41 Reputation points
2021-05-04T15:23:15.267+00:00

Hi,

I want to create a Powershell script to send an email to my O365 mailbox when MFA is enabled. Eventually this script will be run from different applications as from a UPS application.

I am using Direct Send to O365. I am sure all the parameters are good. I receive as error: "Mailbox unavailable. The server response was: 5.7.1 Service ....".

Can someone tell me what I am doing wrong?

My Powershell script:

Create credentials

$username = "xxxxxx@YY "
$password = "pppppppp"
$myPwd = ConvertTo-SecureString -string $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -argumentlist $username, $myPwd

Build email parameters

$mailParams = @{
SmtpServer = 'xxxxxxxx.mail.protection.outlook.com'
Port = '25'
UseSSL = $true
From = 'xxxxxx@YY '
To = 'xxxxxx@YY '
Subject = "Subject: Test Direct send "
Body = "Body: Direct send"
Credential = $cred
}

Send the email

Send-MailMessage @mailParams

Exchange Server Management
Exchange Server Management
Exchange Server: A family of Microsoft client/server messaging and collaboration software.Management: The act or process of organizing, handling, directing or controlling something.
7,503 questions
0 comments No comments
{count} votes

Accepted answer
  1. Andy David - MVP 145.6K Reputation points MVP
    2021-05-04T15:26:47.49+00:00

    Don't use a MFA enabled account.

    Either user a service account that doesnt have MFA applied (Yuck)

    or use the App only method with Exchange Powershell and authenticate with a certificate (YAA!)

    https://learn.microsoft.com/en-us/powershell/exchange/app-only-auth-powershell-v2?view=exchange-ps

    or...
    Send the messages anonymously from the application

    0 comments No comments

0 additional answers

Sort by: Most helpful