Vardges Stepanyan Vardges Stepanyan - 2 months ago 21
Bash Question

Check SMTP server working or not with powershell {send-mailmessage}

How to check if SMTP server is working or not. Basically I have:

SMTPserver= mail.my1stdomain.com,
FromAddress=mymailbox@my1stdomain.com,
ToAddress=Recipient@my1stdomain.com.


I want to check if I can send email. If I can it is ok, but if the Powershell script output is an error, then I want to use my second SMTP server to notify that the first SMTP server failed to send email.

My second set of SMTP info is:

SMTPserver=mail.my2nddomain.com,
FromAddress=mymailbox@my2nddomain.com,
ToAddress=Recipient@my2nddomain.com


I've used this script to send email:

Send-MailMessage -from mymailbox@my1stdomain.com -to Recipient@my1stdomain.com -Subject "Test OK" -Body "Test is OK" -SmtpServer mail.my1stdomain.com


Of course to send email via second SMTP server I have to do this:

Send-MailMessage -from mymailbox@my2nddomain.com -to Recipient@my2nddomain.com -Subject "Test OK" -Body "Test is OK" -SmtpServer mail.my2nddomain.com


I don't know how to write IF case in case of 1st command fails

Answer

You can do a simple try catch:

try{
    Send-MailMessage -from mymailbox@my1stdomain.com -to Recipient@my1stdomain.com -Subject "Test OK" -Body "Test is OK" -SmtpServer mail.my1stdomain.com
   }
catch{
    Send-MailMessage -from mymailbox@my2nddomain.com -to Recipient@my2nddomain.com -Subject "Test OK" -Body "Test is OK" -SmtpServer mail.my2nddomain.com
   }

If the code block in try generates error it will run the catch block.