Page tree

Welcome to FreeSoftwareServers Confluence Wiki

Skip to end of metadata
Go to start of metadata

Note: I haven't actually had a reason to test this, but wanted to save it as I liked the code (tongue)

https://stackoverflow.com/questions/35127673/mandatory-and-default-parameters-of-a-function


 Function Send-EMail {
      Param (
          [Parameter(Mandatory=$true)]  [String]$EmailTo   = "ToAddr@gmx.at", # default
          [Parameter(Mandatory=$true)]  [String]$EmailFrom = "FromAddr@gmail.com", #default
          [Parameter(Mandatory=$true)]  [String]$Subject,
          [Parameter(Mandatory=$true)]  [String]$Body,
          [Parameter(mandatory=$false)] [String]$Attachment,
          [Parameter(mandatory=$true)]  [String]$Password
      )
          $SMTPServer = "smtp.gmail.com"
          $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
          if ($attachment -ne $null) {
              $SMTPattachment = New-Object System.Net.Mail.Attachment($attachment)
              $SMTPMessage.Attachments.Add($STMPattachment)
          }
          $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
          $SMTPClient.EnableSsl = $true
          $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom.Split("@")[0], $Password);
          $SMTPClient.Send($SMTPMessage)
          Remove-Variable -Name SMTPMessage
          Remove-Variable -Name SMTPClient
          Remove-Variable -Name Password
          Remove-Variable -Name Body
          Remove-Variable -Name Subject

  } #End Function Send-EMail
  ....
  $subj = "Subject"
  $body = @" Body-Text  "@
  Send-EMail -Subject $subj -Body $body -Password "myPWD" -Attachment $logFile
  • No labels