8

I am trying to setup an email PowerShell script that will let me send an email when the task scheduler runs the script. The problem i am getting is:

Exception calling "Send" with "1" argument(s): "The remote certificate is invalid according to the validation procedure."

I am running the following code:

$SMTPClient = New-Object Net.Mail.SmtpClient("SMTP", PORT)
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$MailMessage = (New-Object system.net.mail.mailmessage)
$MailMessage.from = ("FROM")
$MailMessage.To.Add("TO")
$MailMessage.Subject = ("Subject")
$MailMessage.Body = ("Body")
$Smtpclient.EnableSsl = ($true)
$SmtpClient.Timeout = (300000)
$SmtpClient.Send($MailMessage)
Write-Output "Message sent";

It gives me the error as specified above. Why?

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Josh
  • 345
  • 2
  • 3
  • 10
  • Try to remove the 'EnableSsl', also you can use `Send-MailMessage` cmdlet – Avshalom Apr 03 '16 at 12:37
  • I have to use SSL fro this particualar SMTP client. It does not work without. I think i have already tried the send-mailmessage cmdlet and the problem is that i did not know how to get all the parameters specified in that command, while smtpclient.send adds all of them in. Any other ideas? – Josh Apr 03 '16 at 13:25
  • 2
    [A quick and easy solution](https://social.technet.microsoft.com/Forums/en-US/d9e9af2b-3bb9-4cb4-8046-dd0a092bc456/send-email-by-powershell?forum=winserverpowershell). – Alexander Obersht Apr 03 '16 at 14:57
  • [Additional info and alternative solutions](http://stackoverflow.com/questions/777607/the-remote-certificate-is-invalid-according-to-the-validation-procedure-using) (in C#). – Alexander Obersht Apr 03 '16 at 15:04

3 Answers3

13

To resolve the issue, just before the send command:

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { return $true }
ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Josh
  • 345
  • 2
  • 3
  • 10
4

This still doesn't resolve the fact the you have an issue with your certificate, perhaps a mismatch with host, expired certificate or intermediate certificate. By adding this class above to your script before the call to Send you are disabling certificate validation, this is a workaround only if you do not need to address the certificate issue.

arreagac
  • 41
  • 1
2
$Smtpclient.EnableSsl = ($false)

it solved my problem :)

Aimee_King
  • 29
  • 2
  • Worth noting this just disables secure (TLS) connections. Which is fine if that's what you want, but it doesn't solve the problem and is insecure. – DiscoveryOV Jun 19 '23 at 15:54