Thursday, 12 September 2019

Fix: Send-MailMessage : The SMTP server requires a secure connection or the client was not authenticated

Problem :

You might have received the below error message when you try to send mail using the Send-MailMessage cmdlet.
Send-MailMessage : The SMTP server requires a secure connection or the client was not authenticated. The server
response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM
[PSXP216CAXXXX.XXXXXX.PROD.OUTLOOK.COM]
At line:1 char:1
+ Send-MailMessage -To "user@domain.com" -from "admin ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpExcept
   ion
    + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage
I have used the below script to send mail using Office 365 user account. In my case, I have got the above error while providing wrong password in my script and the problem solved after providing correct user credentials.
$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

Cause/Solution :

  • Possible Reason 1: Ensure that you have provided correct user credentials (User name and password).
  • Possible Reason 2: Ensure that you have provided the same user account for both Credential and From field.
  • Possible Reason 3: If you want to send mail on behalf of another user, then ensure that the user account has required permissions (ex: SendAs or SendOnBehalf) for the account that you provided in From field.
  • Possible Reason 4: If you face the issue with MFA enabled account, then you can generate an app password and then use an app password for that account, instead of the regular user password. Related thread: https://techcommunity.microsoft.com/t5/Identity-Authentication/Send-Mail-SMTP-through-Office-365-with-MFA/m-p/163867
  • Possible Reason 5: Make sure that you have used the option -UseSSL if your SMTP server requires a secure connection.

Advertisements
Advertisements

No comments:

Post a Comment