Try sending email 5 times?

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



Hello

I need to try to send email from powerscript, but sometimes it fails
due to server load. Usually, sending the email again immediately fixes
it. I tried to use the following code but it would not work.

if ($messages -ne $null) {
$EmailSuccessfullySent = $False
[int] $CurrentEmailAttemptCount = 0
[int] $TotalEmailAttemptCount = 5
Clear-Item "variable:Error"
while ($EmailSuccessfullySent -eq $False -and
$CurrentEmailAttemptCount -lt $TotalEmailAttemptCount) {
write-verbose "Send the email"
[String] $EmailTo = "email@xxxxxxxxx"
[String] $EmailFrom = "email@xxxxxxxxx"
[String] $Subject = "Subject"
[Bool] $IsBodyHtml = $False
[String] $SmtpHost = "smpt.whatever.com"
[Int] $Port = 25

$objSmtpClient = new-object System.Net.Mail.SmtpClient
$objSmtpClient.Host = $SmtpHost
$objSmtpClient.Port = $Port
$objMessage = new-object System.Net.Mail.MailMessage
$objMessage.From = $EmailFrom
$objMessage.To.Add($EmailTo)
$objMessage.Subject = $Subject
$objMessage.IsBodyHtml = $IsBodyHtml
$objMessage.Body = $Output
$objSmtpClient.Send($objMessage)

if ($Error -ne $Null) {
write-verbose "Error while sending email"
$EmailSuccessfullySent = $False
$CurrentEmailAttemptCount++
Clear-Item "variable:Error"
[String] $SmtpHost = "mail.actewagl.net.au"
}
else {
$EmailSuccessfullySent = $True
write-verbose "Email sent successfully to ($EmailTo)"
write-Output "Email sent successfully to ($EmailTo)"
}

}

}



I tried a lot of other things with the Trap block, but nothing worked.
Does anyone have any suggestions?

Thanks

.