1
votes

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
3
Try telnet smtp.office365.com 587 - it's probably blocked (you might need to install telnet client to your server if you don't have it)Robert Dyjas
I already have telnet installed on the server. I tried your command line and obtain : "Connexion à smtp.office365.com...Impossible d’ouvrir une connexion à l’hôte, sur le port 587: Échec lors de la connexion" (With the traduction : Unable to open a connection on the host)Damien K.
So that confirms that firewall is blocking access.Robert Dyjas

3 Answers

0
votes

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

-1
votes

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

-2
votes

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