How-to: Send email with PowerShell

A PowerShell 1.0 function for sending email, in PowerShell 2.0 and above, you can use send-mailmessage instead.

Function SS64Mail($strSubject, $strBody, $strSenderemail, $strRecipientemail, $AttachFile)
      $strSMTP = "ExchangeServer01"  #Change this to your SMTP/Exchange server
      $MailMessage = New-Object System.Net.Mail.MailMessage
      $SMTPClient = New-Object System.Net.Mail.smtpClient
      $ = $strSMTP
      $Recipient = New-Object System.Net.Mail.MailAddress($strRecipientemail, "Recipient")
      $Sender = New-Object System.Net.Mail.MailAddress($strSenderemail, "Sender")
      $MailMessage.Sender = $Sender
      $MailMessage.From = $Sender
      $MailMessage.Subject = $strSubject
      $MailMessage.Body = $strBody
      if ($AttachFile -ne $null) {$MailMessage.attachments.add($AttachFile) }


$dtmToday = ((Get-Date).dateTime).tostring()
$strSubjectLine = "Daily Report - $dtmToday"    
$strBodyText = "report attached."
$strSender = ""
$strRecipient = ""
$Attachment = "C:\scripts\results.doc"
# Call the function to send the email
SS64Mail $strSubjectLine $strBodyText $strSender $strRecipient $Attachment

“In most companies, you don't get too much mail where people are saying, 'Hey, we lost this account.' But that's what you really need to know about, because it might change what you're doing. You need to know about competitive activity. You need to know about customer feedback that says things should be better” ~ Bill Gates

Related PowerShell Cmdlets:

PowerShell Functions

Copyright © 1999-2020
Some rights reserved