Exemplo n.º 1
0
        /// <summary>
        /// Starts the Service (this method is called by the SCM)
        /// </summary>
        /// <param name="args">Initialization Arguments</param>
        /// <remarks>This service do not treat any argument passed thru the <paramref name="args"/></remarks>
        protected override void OnStart(string[] args)
        {
            try
            {
                // Creates a Cancellation Token
                CancellationToken = new CancellationTokenSource();

                // Load Information from App.Config File
                ConfigFileParser parser = new ConfigFileParser();

                // Initialize Server
                var server = new SMTPRouter.Server(parser.SmtpHost.Host, parser.SmtpHost.Port, parser.SmtpHost.RequiresAuthentication, parser.SmtpHost.UseSSL, "SMTPRouter", parser.QueuePath)
                {
                    MessageLifespan = new TimeSpan(0, 15, 0),
                };

                foreach (var smtp in parser.SmtpConnections)
                {
                    server.DestinationSmtps.Add(smtp.Key, smtp.Value);
                }

                foreach (var routingRule in parser.RoutingRules)
                {
                    server.RoutingRules.Add(routingRule);
                }

                foreach (var ipAddress in parser.AcceptedIPAddresses)
                {
                    server.Router.AcceptedIPAddresses.Add(ipAddress);
                }

                foreach (var ipAddress in parser.RejectedIPAddresses)
                {
                    server.Router.RejectedIPAddresses.Add(ipAddress);
                }

                // Initialize Services
                Task.WhenAll(server.StartAsync(CancellationToken.Token)).ConfigureAwait(false);

                // Create Log Entry to inform the service was started
                StringBuilder sb = new StringBuilder();

                // Print Smtp Host
                sb.AppendLine($"{nameof(SMTPRoutingService)} started successfully");
                sb.AppendLine("-----------------------------------------------------------------------------------");
                sb.AppendLine("Smtp Host");
                sb.AppendLine($"   Host..............: {parser.SmtpHost.Host}");
                sb.AppendLine($"   Port..............: {parser.SmtpHost.Port.ToString()}");
                sb.AppendLine($"   Authentication....: {parser.SmtpHost.RequiresAuthentication.ToString()}");
                sb.AppendLine();

                // Print Smtp Connections
                sb.AppendLine("Smtp Connections");

                if (parser.SmtpConnections.Count == 0)
                {
                    sb.AppendLine("   No Smtp Connections Found");
                }
                else
                {
                    foreach (var s in parser.SmtpConnections)
                    {
                        sb.AppendLine($"   Key...............: {s.Value.Key}");
                        sb.AppendLine($"   Description.......: {s.Value.Description}");
                        sb.AppendLine($"   Host..............: {s.Value.Host}");
                        sb.AppendLine($"   Port..............: {s.Value.Port}");
                        sb.AppendLine($"   Use SSL...........: {s.Value.UseSSL}");
                        sb.AppendLine($"   Authentication....: {s.Value.RequiresAuthentication.ToString()}");
                        sb.AppendLine($"   User..............: {s.Value.User}");
                        sb.AppendLine($"   Password..........: {s.Value.Password}");
                    }
                }
                sb.AppendLine();

                // Print Routing Rules
                sb.AppendLine("Routing Rules");

                if (parser.RoutingRules.Count == 0)
                {
                    sb.AppendLine("   No Routing Rules Found");
                }
                else
                {
                    foreach (var r in parser.RoutingRules)
                    {
                        sb.AppendLine($"   Sequence..........: {r.ExecutionSequence}");
                        sb.AppendLine($"   Smtp Key..........: {r.SmtpConfigurationKey}");
                    }
                }

                // Writes to the log
                this.EventLog.WriteEntry(sb.ToString(), EventLogEntryType.SuccessAudit);
            }
            catch (Exception e)
            {
                // Error Starting the Server

                // Log the Error
                StringBuilder sb = new StringBuilder();

                sb.AppendLine($"Error starting the {nameof(SMTPRoutingService)}");
                sb.AppendLine("-----------------------------------------------------------------------------------");
                sb.AppendLine($"Exception............: {e.GetType().ToString()}");
                sb.AppendLine($"   Message...........: {e.Message}");
                sb.AppendLine($"   Stack Trace.......: {e.StackTrace}");

                if (e.InnerException != null)
                {
                    sb.AppendLine();
                    sb.AppendLine($"Inner Exception......: {e.InnerException.GetType().ToString()}");
                    sb.AppendLine($"   Message...........: {e.InnerException.Message}");
                    sb.AppendLine($"   Stack Trace.......: {e.InnerException.StackTrace}");
                }

                this.EventLog.WriteEntry(sb.ToString(), EventLogEntryType.Error);

                // Changes the ExitCode to inform the SCM that the service failed
                this.ExitCode = 1;
                this.Stop();
            }
        }
Exemplo n.º 2
0
        static void TestServer()
        {
            // Creates the Server
            var server = new SMTPRouter.Server("localhost", 25, false, false, "SMTPRouter", "C:\\SMTPRouter2\\Queues")
            {
                MessageLifespan = new TimeSpan(0, 15, 0),
                RoutingRules    = new List <Models.RoutingRule>()
                {
                    new Models.MailFromDomainRoutingRule(10, "gmail.com", "gmail"),
                    new Models.MailFromDomainRoutingRule(20, "hotmail.com", "hotmail")
                },
                DestinationSmtps = new Dictionary <string, Models.SmtpConfiguration>
                {
                    { "gmail", new Models.SmtpConfiguration()
                      {
                          Key                    = "gmail",
                          Host                   = "smtp.gmail.com",
                          Description            = "Google Mail SMTP",
                          Port                   = 587,
                          RequiresAuthentication = true,
                          User                   = Smtp_Gmail_User,
                          Password               = Smtp_Gmail_Pwd,
                          SecureSocketOption     = 1,
                          ActiveConnections      = 1,
                          GroupingOption         = FileGroupingOptions.GroupByDateAndHour
                      } },
                    { "hotmail", new Models.SmtpConfiguration()
                      {
                          Key                    = "hotmail",
                          Host                   = "smtp.live.com",
                          Description            = "Hotmail SMTP",
                          Port                   = 587,
                          RequiresAuthentication = true,
                          User                   = Smtp_Hotmail_User,
                          Password               = Smtp_Hotmail_Pwd,
                          SecureSocketOption     = 1,
                          ActiveConnections      = 1,
                          GroupingOption         = FileGroupingOptions.GroupByDateAndHour
                      } }
                },
            };

            // Hook Events
            server.ListenerStarted += ((o, e) =>
            {
                server.Listener.SessionCreated += Server_SessionCreated;
                server.Listener.SessionCommandExecuting += Server_SessionCommandExecuting;
                server.Listener.SessionCompleted += Server_SessionCompleted;
                server.Listener.ListeningStarted += Server_ListeningStarted;
                server.Listener.MessageReceived += Server_MessageReceived;
                server.Listener.MessageReceivedWithErrors += Server_MessageReceivedWithErrors;
            });

            server.RouterStarted += ((o, e) =>
            {
                //server.Router.AcceptedIPAddresses.Add("127.0.0.1");
                //server.Router.RejectedIPAddresses.Add("127.0.0.1");

                server.Router.MessageRoutedSuccessfully += Server_MessageRoutedSuccessfully;
                server.Router.MessageNotRouted += Server_MessageNotRouted;
                server.Router.MessagePurging += Server_MessagePurging;
                server.Router.MessagesPurged += Server_MessagesPurged;
                server.Router.MessageNotSent += Server_MessageNotSent;
                server.Router.MessageSentSuccessfully += Server_MessageSentSuccessfully;
                server.Router.SmtpConnectedSuccessfully += Server_SmtpConnectedSuccessfully;
                server.Router.SmtpNotConnected += Server_SmtpNotConnected;
                server.Router.SmtpConnectionEnded += Server_SmtpConnectionEnded;
            });

            // Initialize Services
            Task.WhenAll(server.StartAsync(CancellationToken.None)).ConfigureAwait(false);

            // Pause Routing
            //server.Router.IsPaused = true;

            // Send Emails
            int numberOfEmails = 10;

            for (int iMail = 1; iMail <= numberOfEmails; iMail++)
            {
                SendEmail(Smtp_Gmail_User, Smtp_Gmail_User, iMail);
                //SendEmailTweakHeader(Smtp_Gmail_User, new List<string>() { Smtp_Gmail_User }, new List<string>() { Smtp_Gmail_User, Smtp_Gmail_User }, iMail);
                //SendEmailBcc(Smtp_Gmail_User, new List<string>() { Smtp_Gmail_User }, new List<string>() { Smtp_Hotmail_User }, iMail);
            }

            //SendEmail(Smtp_Gmail_User, Smtp_Gmail_User, 1);
            //SendEmail(Smtp_Hotmail_User, Smtp_Hotmail_User, 2);
        }