Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, 
[email protected], 
[email protected]. 

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, 
[email protected], 
[email protected]

I've used this script to send email:

Send-MailMessage -from [email protected] -to [email protected] -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 [email protected] -to [email protected] -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

like image 338
Vardges Stepanyan Avatar asked Mar 12 '23 04:03

Vardges Stepanyan


1 Answers

You can do a simple try catch:

try{
    Send-MailMessage -from [email protected] -to [email protected] -Subject "Test OK" -Body "Test is OK" -SmtpServer mail.my1stdomain.com
   }
catch{
    Send-MailMessage -from [email protected] -to [email protected] -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.

like image 171
Farhad Farahi Avatar answered Apr 06 '23 10:04

Farhad Farahi