'Send-MailMessage - Unable to connect to the remote server

I work on a server on Windows Server 2016. My aim is to send a mail using PowerShell, I wrote the script below.

Send-MailMessage -From "[email protected]" -To "[email protected]" -Subject "votre objet" -SmtpServer "smtp.office365.com" -Body "Blablabla" -Credential "[email protected]" -Port "587" -UseSsl

This script works fine when I execute it on my PC, the mail is sent. So my script is OK.

When I execute it on the server I have this error "Unable to connect to the remote server". When I ping the smtp.office365.com, it is OK.

Does anyone have a idea about what is the problem?

Here the complete error:

Send-MailMessage : Impossible de se connecter au serveur distant
Au caractère Ligne:1 : 1
+ Send-MailMessage -From "[email protected]" -To "john.doe@myd ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation : (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException
    + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage


Solution 1:[1]

I just found a solution. I am now using port 25 and it works, the mail is correctly sent from the server.

Solution 2:[2]

I was getting this error when using smtp.live.com as the SMTP server (sending an email to my hotmail address, from my hotmail address). Was working until around Jan 2022.

After changing it to smtp.office365.com emails are working again.

Solution 3:[3]

step 1: include both $SMTPPort:25 AND $SMTPPort:587

Step2:You may have to allow access to "less secure apps" in your google account settings Go to https://myaccount.google.com/lesssecureapps and set it to "On" and try again

Solution 4:[4]

Get the user credentails

$username = "[email protected]"
$password = "" | ConvertTo-SecureString -AsPlainText -Force

Create hash for email

$email = @{
  from = $username
  to = "[email protected]"
  subject = "Hello"
  smtpserver = "smtp.gmail.com"
  body = "hi"
  credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $password
  Port = "587" 
  UseSsl = $true
}

Send-MailMessage @email

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Damien K.
Solution 2 KERR
Solution 3 raviteja
Solution 4 Jeremy Caney