Wednesday, January 16, 2013

Send Email notification when web server is down

If you are managing more then one web server its tough to manage everyone and check ragularly . so i have metion the code which send email notification when the server is down .

It ping production server and check

using System;

using System.Net;

using System.Net.NetworkInformation;

using System.Text;

using System.Configuration;

using System.Net.Mail;


namespace PingServer

{

    public class PingExample

    {

       

        public static void Main(string[] args)

        {

            try

            {

                Ping ping = new Ping();

                string sServers = ConfigurationManager.AppSettings["SERVER_LIST"];

                string [] sServerList = sServers.Split(',');

                foreach (string server in sServerList)

                {

                    try

                    {

                        PingReply reply = ping.Send(server);

                        if (reply.Status == IPStatus.Success)

                            Console.WriteLine("Server " + server + " running");

                        else

                        {

                            Console.WriteLine("Server " + server + " down");

                            SendMail("Server " + server + " down", "SERVER_STATUS", new string[] { "me@mycompany.com", "mymanager@mycompany.com" });

                        }

                    }

                    catch

                    {

                        Console.WriteLine(server + " is not reachable.Exception raised by ping.Send()");

                    }

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine(ex.Message);

            }

            Console.Read();

        }

        public static void SendMail(String message, String subject, String[] notificationList)

        {

            try

            {

                MailMessage MyMessage = new MailMessage();

                MyMessage.From = new MailAddress("me@mycompany.com");

                foreach (String email in notificationList)

                    MyMessage.To.Add(new MailAddress(email));


                MyMessage.Subject = subject;

                MyMessage.Body = message;


                SmtpClient emailClient = new SmtpClient("smtp.me.mycompany.com");

                emailClient.Send(MyMessage);

            }

            catch

            {

            }

        }

    }

}

No comments:

Post a Comment