smartd_mailer.ps1 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #
  2. # smartd mailer script
  3. #
  4. # Home page of code is: http://www.smartmontools.org
  5. #
  6. # Copyright (C) 2016 Christian Franke
  7. #
  8. # SPDX-License-Identifier: GPL-2.0-or-later
  9. #
  10. # $Id: smartd_mailer.ps1 4760 2018-08-19 18:45:53Z chrfranke $
  11. #
  12. $ErrorActionPreference = "Stop"
  13. # Parse command line and check environment
  14. $dryrun = $false
  15. if (($args.Count -eq 1) -and ($args[0] -eq "--dryrun")) {
  16. $dryrun = $true
  17. }
  18. $toCsv = $env:SMARTD_ADDRCSV
  19. $subject = $env:SMARTD_SUBJECT
  20. $file = $env:SMARTD_FULLMSGFILE
  21. if (!((($args.Count -eq 0) -or $dryrun) -and $toCsv -and $subject -and $file)) {
  22. echo `
  23. "smartd mailer script
  24. Usage:
  25. set SMARTD_ADDRCSV='Comma separated mail addresses'
  26. set SMARTD_SUBJECT='Mail Subject'
  27. set SMARTD_FULLMSGFILE='X:\PATH\TO\Message.txt'
  28. .\$($MyInvocation.MyCommand.Name) [--dryrun]
  29. "
  30. exit 1
  31. }
  32. # Set default sender address
  33. if ($env:COMPUTERNAME -match '^[-_A-Za-z0-9]+$') {
  34. $hostname = $env:COMPUTERNAME.ToLower()
  35. } else {
  36. $hostname = "unknown"
  37. }
  38. if ($env:USERDNSDOMAIN -match '^[-._A-Za-z0-9]+$') {
  39. $hostname += ".$($env:USERDNSDOMAIN.ToLower())"
  40. } elseif ( ($env:USERDOMAIN -match '^[-_A-Za-z0-9]+$') `
  41. -and ($env:USERDOMAIN -ne $env:COMPUTERNAME) ) {
  42. $hostname += ".$($env:USERDOMAIN.ToLower()).local"
  43. } else {
  44. $hostname += ".local"
  45. }
  46. $from = "smartd daemon <root@$hostname>"
  47. # Read configuration
  48. . .\smartd_mailer.conf.ps1
  49. # Create parameters
  50. $to = $toCsv.Split(",")
  51. $body = Get-Content -Path $file | Out-String
  52. $parm = @{
  53. SmtpServer = $smtpServer; From = $from; To = $to
  54. Subject = $subject; Body = $body
  55. }
  56. if ($port) {
  57. $parm += @{ Port = $port }
  58. }
  59. if ($useSsl) {
  60. $parm += @{ useSsl = $true }
  61. }
  62. if ($username -and ($password -or $passwordEnc)) {
  63. if (!$passwordEnc) {
  64. $secureString = ConvertTo-SecureString -String $password -AsPlainText -Force
  65. } else {
  66. $passwordEnc = $passwordEnc -replace '[\r\n\t ]',''
  67. $secureString = ConvertTo-SecureString -String $passwordEnc
  68. }
  69. $credential = New-Object -Typename System.Management.Automation.PSCredential -Argumentlist $username,$secureString
  70. $parm += @{ Credential = $credential }
  71. }
  72. # Send mail
  73. if ($dryrun) {
  74. echo "Send-MailMessage" @parm
  75. } else {
  76. Send-MailMessage @parm
  77. }