1. partial class EmailService : ServiceBase
  2. {
  3.     private static MessageQueue msgQ = null;
  4.     private static object lockObject = new object();
  5.     private SmtpClient objSmtpClient;
  6.     private MailMessage objMailMsg;
  7.     private string mailFrom="";
  8.     EmailMessage msg;
  9.  
  10.    Log Log;
  11.     public EmailService()
  12.     {
  13.         InitializeComponent();
  14.         Log l= new Log();            
  15.     }
  16.  
  17.     public void OnStart()
  18.    // protected override void OnStart(string[] args)        
  19.     {
  20.         string queuePath = ConfigurationManager.AppSettings["mqPath"];
  21.         mailFrom = ConfigurationManager.AppSettings["notificationemail"];
  22.         string SMTPSSLConfig = ConfigurationManager.AppSettings["smtpclientssl"];
  23.         if (string.IsNullOrEmpty(queuePath))
  24.         {
  25.             throw new Exception("Message queue path not defined in app.config.");
  26.         }
  27.         if (string.IsNullOrEmpty(mailFrom))
  28.         {
  29.             throw new Exception("Sender email used to send  notifications is not defined in app.config.");
  30.         }
  31.         if (string.IsNullOrEmpty(SMTPSSLConfig))
  32.         {
  33.             throw new Exception("SMTP SSL config not defined in app.config.");
  34.         }
  35.         objSmtpClient = new SmtpClient();
  36.         objSmtpClient.EnableSsl = Convert.ToBoolean(SMTPSSLConfig);
  37.  
  38.         //QueueService.InsureQueueExists(queuePath);
  39.         msgQ = new MessageQueue(queuePath);
  40.         msgQ.Formatter = new BinaryMessageFormatter();
  41.         msgQ.MessageReadPropertyFilter.SetAll();
  42.         msgQ.ReceiveCompleted += new ReceiveCompletedEventHandler(msgQ_ReceiveCompleted);
  43.         msgQ.BeginReceive();
  44.         try
  45.         {
  46.             if (!MessageQueue.Exists(queuePath))
  47.             {
  48.                 MessageQueue.Create(queuePath);
  49.                 Log.WriteMessageQueueInitialParamsLog(System.DateTime.Now.ToString()+" :Message queue successfully created at following location:"+queuePath);
  50.             }
  51.             else
  52.             {
  53.                 Log.WriteMessageQueueInitialParamsLog(System.DateTime.Now.ToString() + ": Message Queue Path: " + msgQ.Path);
  54.             }                
  55.         }
  56.         catch (Exception ex)
  57.         {
  58.             Log.WriteCommonLog(System.DateTime.Now.ToString() + " :Error checking message queue existence:\n"+GetExceptionMessageString(ex));  
  59.         }
  60.  
  61.         //eventLog1.WriteEntry(System.DateTime.Now.ToString()+" :EmailService started successfully." );
  62.         Log.WriteMessageQueueInitialParamsLog(System.DateTime.Now.ToString()+" :Message queue started successfully.");
  63.  
  64.     }
  65.  
  66.     private void msgQ_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
  67.     {
  68.         try
  69.         {
  70.             lock (lockObject)
  71.             {
  72.                 msg = (EmailMessage)e.Message.Body;
  73.                 Log.WriteMessageQueueLog(System.DateTime.Now.ToString() + " :Message retrieved from message Queue: From:" + msg.From + "  To:" + msg.To + "  Subject:" + msg.Subject);
  74.                 SendEmail(msg);
  75.             }
  76.  
  77.             // Listen for the next message.
  78.             msgQ.BeginReceive();
  79.         }
  80.         catch(Exception ex)
  81.         {
  82.             Log.WriteCommonLog(GetExceptionMessageString(ex));
  83.         }
  84.     }
  85.     protected override void OnStop()
  86.     {
  87.         msgQ.Close();
  88.         //eventLog1.WriteEntry(System.DateTime.Now.ToString()+" :EmailService stopped.");
  89.         Log.WriteMessageQueueInitialParamsLog(System.DateTime.Now.ToString()+" :Message queue stopped successfully.");
  90.     }
  91.     private void SendEmail(EmailMessage objMail)
  92.     {
  93.         try
  94.         {
  95.             if(string.IsNullOrEmpty(mailFrom) || string.IsNullOrEmpty(objMail.To))
  96.                 throw new Exception("Either sender email address is null or receiver email address is null.");
  97.  
  98.             objMailMsg = new MailMessage(new MailAddress(mailFrom), new MailAddress(objMail.To));
  99.             objMailMsg.ReplyTo = new MailAddress(mailFrom);
  100.             objMailMsg.IsBodyHtml = true;
  101.             objMailMsg.Subject = objMail.Subject;
  102.             objMailMsg.Body = objMail.Message;
  103.             objSmtpClient.Send(objMailMsg);
  104.             Log.WriteEmailLog("Email Sent:  DateTime:" + System.DateTime.Now.ToString() + "  To:" + objMail.To + "  From:" + mailFrom + "  Subject:" + objMail.Subject);
  105.             System.Threading.Thread.Sleep(1000);
  106.         }
  107.         catch (System.Net.Mail.SmtpException se)
  108.         {
  109.             if (se.StatusCode == SmtpStatusCode.MailboxBusy)
  110.             {
  111.                 new QueueService().QueueMessage(objMail);
  112.                 Log.WriteCommonLog("SMTP Exception:" + GetExceptionMessageString(se));
  113.             }
  114.             else
  115.             {
  116.                 Log.WriteCommonLog("SMTP Exception:" + GetExceptionMessageString(se));
  117.             }
  118.         }
  119.         catch (System.Net.WebException we)
  120.         {
  121.             if ((we.Status == System.Net.WebExceptionStatus.ConnectFailure) || (we.Status == System.Net.WebExceptionStatus.ConnectionClosed) || (we.Status == System.Net.WebExceptionStatus.ReceiveFailure) || (we.Status == System.Net.WebExceptionStatus.Timeout) || (we.Status == System.Net.WebExceptionStatus.NameResolutionFailure))
  122.             {
  123.                 new QueueService().QueueMessage(objMail);
  124.                 Log.WriteCommonLog("Web Exception:" + GetExceptionMessageString(we));
  125.             }
  126.             else
  127.             {
  128.                 Log.WriteCommonLog("Web Exception:" + GetExceptionMessageString(we));
  129.             }
  130.         }
  131.         catch (Exception ex)
  132.         {
  133.             Log.WriteCommonLog("Web Exception:" + GetExceptionMessageString(ex));
  134.         }
  135.  
  136.     }
  137.     private string GetExceptionMessageString(Exception exc)
  138.     {
  139.         return "\nException thrown by EmailService\n" + System.DateTime.Now.ToString() + "\nInner Exception:" + exc.InnerException + "\nException Message:" + exc.Message + "\nSource:" + exc.Source + "\nStack Trace:" + exc.StackTrace;
  140.     }
  141. }