Sending emails via SMTP Service in .Net

When sending emails via SMTP in .NET, developers seldom check to ensure the SMTP service is installed and running. Here's some code to perform the check and start the service if it isn't running

//Check for SMTP Service Using System.ServiceProcess
ServiceController[] services = ServiceController.GetServices();
bool bServiceInstalled= false;
ServiceController smtpServ = null;
// Loop through all the services and find the SMTP Service.
foreach(ServiceController service in services)
   if (service.ServiceName.ToLower() == "smtpsvc") {
      bServiceInstalled = true;
      smtpServ = service;
if (!bServiceInstalled) {
      ("SMTP Service is not installed on this " + 
      "machine.", "SMTPService",MessageBoxButtons.OK);
else {
   //Start if it is not running
   if (smtpServ != null) {
      if (smtpServ.Status != ServiceControllerStatus.Running) {
         MessageBox.Show("SMTP Service not running..." + 
            "Starting Service...");
         catch(Exception ex)
            MessageBox.Show(ex.Message,"SMTP Service",
By [)ia6l0 iii   Popularity  (1409 Views)