PowerShell comes with the cmdlet Send-MailMessage so you can easily send off emails and even include attachments. All you need is the name of an SMTP server that accepts your request and does the mail transport, and your authentication credentials.

However, there are three important caveats these days when using this cmdlet:

  • PowerShell 7 claims the cmdlet is deprecated, and while that is true, there is no better replacement. As long as you intend to send plain emails you can safely continue to use this cmdlet
  • Email is sent using secure communications these days so you should always include the -UseSSL switch parameter
  • On older Windows boxes, PowerShell cannot communicate with many servers via SSL due to an outdated TLS setting. While modern Windows versions have upgraded TLS to version 1.2, older versions still use 1.0 which is not accepted by most servers anymore.

If sending email via Send-MailMessage fails for you, make sure you use -UseSsl. Also specify the port to use. Try port 465, and if that raises exceptions, try port 587.

If you still can’t get Send-MailMessage to communicate with your SMTP server, check for typos in the SMTP server name, and as a last resort manually enable TLS 1.2 by running:

"Starting!"
$a = Read-Host -Prompt 'Enter something'
"Entered: $a"
"Completed"

In a nutshell, a typical Send-MailMessage call would look like this:

# must match your email address
# Most hosters do not accept email addresses with a different domain
$from = '[email protected]' 
# send email to:
$to = '[email protected]'
# if you want to add attachments, specify here and use -Attachments 
# else, remove that parameter
$file = 'c:\path\to\attachment.txt'
$subject = 'Mail from PowerShell'
$body = 'Here is the content'
$smtp = 'some.smtpserver'  
# your username (sometimes your internal mailbox name), prompts for password:
$cred = Get-Credential -Message 'Enter your email username or email address'

# send mail (one line without line break):
Send-MailMessage -From $from -To $to -Attachments $file -Subject $subject -Body $body -Encoding UTF8 -SmtpServer $smtp -UseSsl -Port 587 -Credential $cred




Twitter This Tip! ReTweet this Tip!

Anonymous