Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

How to resend an email if send-MailMessage fails?

$
0
0

My company's SMTP server is a little wonky.  Every so often when I send an email to it from Powershell it will fail because the STMP server refuses the connection.

 

I'd like to create some Powershell code so that Powershell can detect when the send-mailmessage cmdlet fails and will retry to send the email.

 

After Googling around the Internet I found one solution that goes something like this:

---------

function SendMailErr { 
$MessageParameters = @{
    From = $from
    To = $to
Subject = "subject text"
SmtpServer = $smtp
    Body = $body
Priority = "High"

}
try {
    Send-MailMessage @MessageParameters  -EA Stop;

    }
catch { Write-Host $sendErr
    Sleep $waitMail
    Send-MailMessage @MessageParameters
      }

Exit
}
---------

So basically it appears that this person created a function called "SendMailErr" and parameterized all of the send-mailmessage parameters.
Then he uses a try-catch routine to write to an error log then pause for some time and then try sending it again.
Now, being the Powershell noob that I am, these are the questions I have:

  1. Does the "catch" part need some logic to tell it how to detect when the "try send-mailmessage" part fails? Or does it simply detect any kind of failure and automatically goes to the "catch" part?
  2. On the "try" part what do the commands "-EA STOP" mean? Is that an alias for something?
  3. Will this try-catch routine continue looping until send-mailmessage successfully completes?
  4. And finally, is there a more elegant way of solving this problem?

         


        Viewing all articles
        Browse latest Browse all 6937

        Trending Articles