Check SMTP Certificate with PowerShell October 12, 2026 by sellout in Certificates For Your Powerscript terminal: $server = "smtp.myrelay.com" $port = 25 $result = @{} $tcp = [System.Net.Sockets.TcpClient]::new() $tls = $null function Read-SmtpReply($reader) { do { $line = $reader.ReadLine() if ($null -eq $line) { throw "SMTP server closed the connection." } Write-Host $line } while ($line -match '^\d{3}-') return $line } try { $connect = $tcp.ConnectAsync($server, $port) if (-not $connect.Wait(10000)) { throw "Connection timed out." } $stream = $tcp.GetStream() $stream.ReadTimeout = 10000 $stream.WriteTimeout = 10000 $reader = [System.IO.StreamReader]::new( $stream, [System.Text.Encoding]::ASCII, $false, 1024, $true) $writer = [System.IO.StreamWriter]::new( $stream, [System.Text.Encoding]::ASCII, 1024, $true) $writer.NewLine = "`r`n" $writer.AutoFlush = $true if ((Read-SmtpReply $reader) -notmatch '^220 ') { throw "Unexpected SMTP greeting." } $writer.WriteLine("EHLO diagnostic.local") if ((Read-SmtpReply $reader) -notmatch '^250 ') { throw "EHLO failed." } $writer.WriteLine("STARTTLS") if ((Read-SmtpReply $reader) -notmatch '^220 ') { throw "Server did not accept STARTTLS." } $reader.Dispose() $writer.Dispose() $validation = [System.Net.Security.RemoteCertificateValidationCallback] { param($sender, $certificate, $chain, $errors) if ($null -ne $certificate) { $result.Certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($certificate) } $result.Errors = $errors $result.ChainStatus = ( $chain.ChainStatus | ForEach-Object { "$($_.Status): $($_.StatusInformation.Trim())" } ) -join "; " return ($errors -eq [System.Net.Security.SslPolicyErrors]::None) } $tls = [System.Net.Security.SslStream]::new($stream, $false, $validation) $tls.AuthenticateAsClient($server) Write-Host "TLS validation succeeded. Protocol: $($tls.SslProtocol)" } catch { Write-Warning $_.Exception.GetBaseException().Message } if ($result.Certificate) { $cert = $result.Certificate $san = $cert.Extensions | Where-Object { $_.Oid.Value -eq "2.5.29.17" } [pscustomobject]@{ Subject = $cert.Subject Issuer = $cert.Issuer ValidFrom = $cert.NotBefore Expires = $cert.NotAfter Thumbprint = $cert.Thumbprint AlternativeNames = if ($san) { $san.Format($true) } else { "(none)" } ValidationErrors = $result.Errors ChainStatus = $result.ChainStatus } | Format-List $cert.Dispose() } if ($tls) { $tls.Dispose() } $tcp.Dispose()