Send email to O365 using Powershell when MFA is enabled

Mario onMicrosoft 41 Reputation points


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 = ''
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,226 questions
0 comments No comments
{count} votes

Accepted answer
  1. Andy David - MVP 138.4K Reputation points MVP

    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!)

    Send the messages anonymously from the application

    0 comments No comments

0 additional answers

Sort by: Most helpful