title: Wait 60 seconds then resend if Send-MailMessage failed Powershell
body: <p>I have a script that sends an email if a task fails (SendMailErr). I would like to add in retrying to send the email if the previous send-mailmessage failed. I had tried to put it into a try catch finally loop within the function but it didn't work as expected. Here is my code</p>
  
  <pre><code>$waitMail = 60
  $sendErr = "Error Sending Email to SI Team: $_. Retrying in $waitMail minute(s)"
  
  function SendMailErr { 
  $MessageParameters = @{
      From = $from
      To = $to
      Subject = "ALERT: Backup Failed for $env:ComputerName.$env:USERDNSDOMAIN - $((Get-Date).ToShortDateString())"
      Body = $body | Out-String 
      SmtpServer = $Smtp
      Priority = "High"
      Attachments = $attachments
  }
  try {   Send-MailMessage @MessageParameters -EA Stop
          Exit
      }
  catch { Write-Log $sendErr
          Sleep $waitMail
          Send-MailMessage @MessageParameters
          Exit
        }
  finaly {  
          Write-Log "Error: Unable to send email to SI Team"
          Exit
  }
  </code></pre>
  
  <p>Any suggestions would be greatly appreciated. I'm sure there's a better way to structure it, my googling just hasn't found it yet.</p>
  
  <p>Thanks,
  Amelia</p>
  
  <hr>
  
  <p>I've figured this out in my own clumsy way...</p>
  
  <p>Thank you to the person that pointed out I had an Exit within the trap.</p>
  
  <p>The following works for me now</p>
  
  <pre><code>function SendMailErr { 
  $MessageParameters = @{
      From = $from
      To = $to
  Subject = "ALERT: Backup Failed for $env:ComputerName.$env:USERDNSDOMAIN - $((Get-Date).ToShortDateString())"
  SmtpServer = $smtp
      Body = $body
  Priority = "High"
  
  }
  try {
      Send-MailMessage @MessageParameters  -EA Stop;
  
      }
  catch { Write-Host $sendErr
      Sleep $waitMail
      Send-MailMessage @MessageParameters
        }
  
  Exit
  }
  </code></pre>