Question:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
$file = "c:\Mail-content.txt" if (test-path $file) { $from = "afgarciact@gmail.com" $to = " $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!
Answer:
Make sure your specify the -UseSsl
switch:
1 2 |
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:
1 2 |
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:
1 2 |
[System.Net.ServicePointManager]::SecurityProtocol = 'Tls,TLS11,TLS12' |