Sergio Calderon
Sergio Calderon

Reputation: 857

Can I use TLS with Send-MailMessage cmdlet?

I am trying to send an email using PowerShell, but need to use TLS. Any way I can do that using Send-MailMessage cmdlet?

This is my code:

$file = "c:\Mail-content.txt"

if (test-path $file)
{

    $from = "[email protected]"
    $to = "<[email protected]>","<[email protected]>"
    $pc = get-content env:computername
    $subject = "Test message " + $pc
    $smtpserver ="172.16.201.55"
    $body = Get-Content $file | Out-String


[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { return $true }

     foreach ($recipient in $to)
    {
        write-host "Sent to $to"
        Send-MailMessage -smtpServer $smtpserver -from $from -to $recipient -subject $subject  -bodyAsHtml $body -Encoding ([System.Text.Encoding]::UTF8)
    }



}
else
{
write-host "Configuración"
}

Thanks a lot!

Upvotes: 8

Views: 60476

Answers (2)

Justin Ngayan
Justin Ngayan

Reputation: 11

I have been fighting this all day. The fix for me ended up being needing to run this in a separate line first, and then I was able to run my Send-MailMessage commands:

[System.Net.ServicePointManager]::SecurityProtocol = 'Tls,TLS11,TLS12'

Thank you for the suggestion!

Upvotes: 1

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174435

Make sure your specify the -UseSsl switch:

Send-MailMessage -SmtpServer $smtpserver -UseSsl -From $from -To $recipient -Subject $subject -BodyAsHtml $body -Encoding ([System.Text.Encoding]::UTF8)

If the SMTP server uses a specific port for SMTP over TLS, use the -Port parameter:

Send-MailMessage -SmtpServer $smtpserver -Port 465 -UseSsl -From $from -To $recipient -Subject $subject -BodyAsHtml $body -Encoding ([System.Text.Encoding]::UTF8)

If you want to make sure that TLS is always negotiated (and not SSL 3.0), set the SecurityProtocol property on the ServicePointManager class:

[System.Net.ServicePointManager]::SecurityProtocol = 'Tls,TLS11,TLS12'

Upvotes: 14

Related Questions