Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use TLS with Send-MailMessage cmdlet?

Tags:

powershell

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!

like image 966
Sergio Calderon Avatar asked Oct 10 '16 21:10

Sergio Calderon


People also ask

How does send-MailMessage work?

The Send-MailMessage cmdlet uses the From parameter to specify the message's sender. The To parameter specifies the message's recipients. The Cc parameter sends a copy of the message to the specified recipient. The Bcc parameter sends a blind copy of the message.

What can I use instead of MailMessage?

NET MailKit. The most generic method that would replace SmtpClient and Send-MailMessage would be the recommended replacement, which is MailKit. This is a third-party, open-source library but maintained by a Microsoft employee and officially recommended for use in the documentation.

How do I send an email from PowerShell scripts in Outlook?

$UserCredential1 = Get-Credential. Import-CSV "<Path toCSV file>" | Foreach {Send-MailMessage -To $_. EmailAddress -from <The sender email address> -Subject '<>' -Body '<>' -BodyAsHtml -smtpserver "smtp.office365.com" -usessl -Credential $UserCredential1 -Port 587}


1 Answers

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'
like image 194
Mathias R. Jessen Avatar answered Sep 21 '22 13:09

Mathias R. Jessen