Forum Discussion
Send-MailMessage with Powershell and Exchange Online with MFA
I am having difficulty with one of my scripts that blocks a user from signing into Office 365 then sends an email to my manager and HR when the script has completed.
I downloaded the Exchange Online Powershell Module and connected to EXOPSSession but I receive an error message that I need a secure connection to send a message. I know I created a secure connection with the old way to connect with Exchange Online but not sure how to do it when I connect to EXOPSession.
Can someone please point me in the right direction?
- Kevin_MorganIron Contributor
The Send-MailMessage cmdlet is not related with Exchange Online Powershell or EXOPSSession (MFA), this is normal Powershell utility command, so you have to individually pass required parameters (ex: username and password) to this cmdlet.
The below command works fine for me even with MFA enabled account.
$username = "user@domain.com" $password = "user_password" $sstr = ConvertTo-SecureString -string $password -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential -argumentlist $username, $sstr $body = "This is a test email" Send-MailMessage -To "admin@domain.com" -from "user@domain.com" -Subject 'Test message' -Body $body -BodyAsHtml -smtpserver smtp.office365.com -usessl -Credential $cred -Port 587
If you face issue with MFA enabled account, then you can generate app password and then use an app password for that account, instead of the regular user password.
Refer this post for more details : https://techcommunity.microsoft.com/t5/Identity-Authentication/Send-Mail-SMTP-through-Office-365-with-MFA/m-p/163867
- chendleyCopper Contributor
Thank you for the response.
Is there a way to not store the password within the script?
- Kevin_MorganIron ContributorYes you can store password in Windows Credentials Manager and retrieve it using PowerShell.
Check this post for more info: https://www.morgantechspace.com/2019/05/how-to-store-and-read-user-credentials-from-windows-credentials-manager.html
- Heineken022Copper Contributor
I figured out another way to do this without storing the password or creating an app password. Hopefully this helps.
$username = "email address removed for privacy reasons"
$password = Read-Host "Enter Password" -AsSecureString
$credentials = New-Object System.Management.Automation.PSCredential -argumentlist $username, $password