Ejemplo n.º 1
0
        /// <summary>
        /// 送信処理
        /// </summary>
        /// <param name="smtpServer">SMTP サーバー名</param>
        /// <param name="smtpPort">SMTP ポート番号</param>
        /// <param name="smtpUserId">SMTP ユーザーID</param>
        /// <param name="smtpPassword">SMTP パスワード</param>
        /// <param name="message">メッセージ</param>
        /// <param name="logStream">ログ用 Stream</param>
        /// <param name="logMailStream">メールログ用 Stream</param>
        /// <returns></returns>
        private bool Send(
            string smtpServer,
            int smtpPort,
            string smtpUserId,
            string smtpPassword,
            MimeMessage message,
            Stream logStream,
            Stream logMailStream)
        {
            bool result = false;

            try {
                using (ProtocolLogger logger = new ProtocolLogger(logStream, true))
                    using (SmtpClient smtpClient = new SmtpClient(logger)) {
                        smtpClient.Connect(smtpServer, smtpPort);
                        smtpClient.Authenticate(smtpUserId, smtpPassword);

                        smtpClient.Send(message);

                        smtpClient.Disconnect(true);
                    }

                this.message.WriteTo(logMailStream);

                result = true;
            } catch (Exception ex) {
                throw ex;
            }

            return(result);
        }
Ejemplo n.º 2
0
        public void TestLogConnectMidline()
        {
            using (var stream = new MemoryStream()) {
                using (var logger = new ProtocolLogger(stream, true)
                {
                    RedactSecrets = false
                }) {
                    byte[] buf;

                    buf = Encoding.ASCII.GetBytes("PARTIAL LINE");
                    logger.LogClient(buf, 0, buf.Length);

                    logger.LogConnect(new Uri("proto://server.com"));

                    logger.LogServer(buf, 0, buf.Length);

                    logger.LogConnect(new Uri("proto://server.com"));
                }

                var buffer = stream.GetBuffer();
                int length = (int)stream.Length;

                var result = Encoding.ASCII.GetString(buffer, 0, length);

                Assert.AreEqual("C: PARTIAL LINE\r\nConnected to proto://server.com/\r\nS: PARTIAL LINE\r\nConnected to proto://server.com/\r\n", result);
            }
        }
Ejemplo n.º 3
0
 public void Send <T>(TakeServerCommand tcmd, T data) where T : class, new()
 {
     ProtocolLogger.WriteLog(data, MainCommand.TakeServer, (ushort)tcmd, LogerType.Info);
     if (socketConnected)
     {
         socket.Send((ushort)MainCommand.TakeServer, (ushort)tcmd, ProtocalSerialize.SerializeObject(data));
     }
 }
Ejemplo n.º 4
0
        public void TestLoggingWithCustomPrefixes()
        {
            using (var stream = new MemoryStream()) {
                using (var logger = new ProtocolLogger(stream, true)
                {
                    ClientPrefix = "C> ", ServerPrefix = "S> "
                }) {
                    logger.LogConnect(new Uri("pop://pop.skyfall.net:110"));

                    var cmd = Encoding.ASCII.GetBytes("RETR 1\r\n");
                    logger.LogClient(cmd, 0, cmd.Length);

                    using (var response = GetType().Assembly.GetManifestResourceStream("UnitTests.Net.Pop3.Resources.comcast.retr1.txt")) {
                        using (var filtered = new FilteredStream(response)) {
                            var buffer = new byte[4096];
                            int n;

                            filtered.Add(new Unix2DosFilter());

                            while ((n = filtered.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                logger.LogServer(buffer, 0, n);
                            }
                        }
                    }
                }

                stream.Position = 0;

                using (var reader = new StreamReader(stream)) {
                    string line;

                    line = reader.ReadLine();
                    Assert.AreEqual("Connected to pop://pop.skyfall.net:110/", line);

                    line = reader.ReadLine();
                    Assert.AreEqual("C> RETR 1", line);

                    using (var response = GetType().Assembly.GetManifestResourceStream("UnitTests.Net.Pop3.Resources.comcast.retr1.txt")) {
                        using (var r = new StreamReader(response)) {
                            string expected;

                            while ((expected = r.ReadLine()) != null)
                            {
                                line = reader.ReadLine();

                                Assert.AreEqual("S> " + expected, line);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 5
0
        public void TestDefaultSettings()
        {
            Assert.AreEqual("C: ", ProtocolLogger.DefaultClientPrefix, "DefaultClientPrefix");
            Assert.AreEqual("S: ", ProtocolLogger.DefaultServerPrefix, "DefaultServerPrefix");

            using (var logger = new ProtocolLogger(new MemoryStream())) {
                Assert.AreEqual("C: ", logger.ClientPrefix, "ClientPrefix");
                Assert.AreEqual("S: ", logger.ServerPrefix, "ServerPrefix");
                Assert.AreEqual("yyyy-MM-ddTHH:mm:ssZ", logger.TimestampFormat, "TimestampFormat");
                Assert.IsFalse(logger.LogTimestamps, "LogTimestamps");
                Assert.IsFalse(logger.RedactSecrets, "RedactSecrets");
            }
        }
Ejemplo n.º 6
0
        public bool OnNCRead(ushort mainCmd, ushort subCmd, string data)
        {
            try
            {
                if ((MainCommand)mainCmd != MainCommand.TakeServer)
                {
                    return(false);
                }

                switch ((TakeServerCommand)subCmd)
                {
                case TakeServerCommand.LoginFault:
                    Console.WriteLine("Central socket connection failed");
                    var tsLoginDtoFault = ProtocalSerialize.UnSerializeObject <TakeServerLoginDto>(data);
                    ProtocolLogger.WriteLog(tsLoginDtoFault, (MainCommand)mainCmd, subCmd, LogerType.Info);
                    break;

                case TakeServerCommand.LoginSuccess:
                    Console.WriteLine("Central socket connection success");
                    var tsLoginDtoSuccess = ProtocalSerialize.UnSerializeObject <TakeServerLoginDto>(data);
                    ProtocolLogger.WriteLog(tsLoginDtoSuccess, (MainCommand)mainCmd, subCmd, LogerType.Info);
                    socketConnected = true;
                    //发送当前比赛管理下 所有的比赛数据(断线重连)
                    //更改为重连后发送所有已经配对的比赛,使其重发完整数据  MatchManager.ForEach(o => o.SendAll());
                    break;

                case TakeServerCommand.MatchLink:
                    var tmLinkDto = ProtocalSerialize.UnSerializeObject <TakeMatchLinkDto>(data);
                    if (tmLinkDto.TakeType != collectorType)
                    {
                        break;
                    }
                    ProtocolLogger.WriteLog(tmLinkDto, (MainCommand)mainCmd, subCmd, LogerType.Info);
                    matchEntityManager.MatchLink(tmLinkDto.SrcMatchID, tmLinkDto.MatchID);
                    break;

                case TakeServerCommand.MatchReset:
                    var tmResetDto = ProtocalSerialize.UnSerializeObject <TakeMatchResetDto>(data);
                    ProtocolLogger.WriteLog(tmResetDto, (MainCommand)mainCmd, subCmd, LogerType.Info);
                    var srcMatchID = matchEntityManager.GetSrcMatchID(tmResetDto.MatchID);
                    matchEntityManager.Reset(srcMatchID);
                    break;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
            }
            return(true);
        }
Ejemplo n.º 7
0
        public void TestArgumentExceptions()
        {
            Assert.Throws <ArgumentNullException> (() => new ProtocolLogger((string)null));
            Assert.Throws <ArgumentNullException> (() => new ProtocolLogger((Stream)null));
            using (var logger = new ProtocolLogger(new MemoryStream())) {
                var buffer = new byte[1024];

                Assert.Throws <ArgumentNullException> (() => logger.LogConnect(null));
                Assert.Throws <ArgumentNullException> (() => logger.LogClient(null, 0, 0));
                Assert.Throws <ArgumentNullException> (() => logger.LogServer(null, 0, 0));
                Assert.Throws <ArgumentOutOfRangeException> (() => logger.LogClient(buffer, -1, 0));
                Assert.Throws <ArgumentOutOfRangeException> (() => logger.LogServer(buffer, -1, 0));
                Assert.Throws <ArgumentOutOfRangeException> (() => logger.LogClient(buffer, 0, -1));
                Assert.Throws <ArgumentOutOfRangeException> (() => logger.LogServer(buffer, 0, -1));
            }
        }
Ejemplo n.º 8
0
        public void TestOverridingDefaultSettings()
        {
            try {
                ProtocolLogger.DefaultClientPrefix = "C> ";
                ProtocolLogger.DefaultServerPrefix = "S> ";

                using (var logger = new ProtocolLogger(new MemoryStream())
                {
                    RedactSecrets = false
                }) {
                    Assert.AreEqual("C> ", logger.ClientPrefix, "ClientPrefix");
                    Assert.AreEqual("S> ", logger.ServerPrefix, "ServerPrefix");
                    Assert.AreEqual("yyyy-MM-ddTHH:mm:ssZ", logger.TimestampFormat, "TimestampFormat");
                    Assert.IsFalse(logger.LogTimestamps, "LogTimestamps");
                    Assert.IsFalse(logger.RedactSecrets, "RedactSecrets");
                }
            } finally {
                ProtocolLogger.DefaultClientPrefix = "C: ";
                ProtocolLogger.DefaultServerPrefix = "S: ";
            }
        }
Ejemplo n.º 9
0
        public bool OnConnect()
        {
            try
            {
                var code = ConfigSingleton.CreateInstance().GetAppConfig <string>("ValidCode");
                Console.WriteLine("Collector Socket Connected Success!");

                //发送登录信息
                TakeServerLoginDto tslLoginDto = new TakeServerLoginDto()
                {
                    TakeType = collectorType, ValidCode = code
                };
                string data = ProtocalSerialize.SerializeObject(tslLoginDto);
                ProtocolLogger.WriteLog <TakeServerLoginDto>(tslLoginDto, MainCommand.TakeServer, (ushort)TakeServerCommand.Login, LogerType.Info);

                socket.Send((ushort)MainCommand.TakeServer, (ushort)TakeServerCommand.Login, data);
                return(true);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
            }
            return(true);
        }
Ejemplo n.º 10
0
        public void TestArgumentExceptions()
        {
            var enumeratedRights = new [] { AccessRight.OpenFolder, AccessRight.CreateFolder };

            Assert.Throws <ArgumentNullException> (() => new AccessControl(null));
            Assert.Throws <ArgumentNullException> (() => new AccessControl(null, "rk"));
            Assert.Throws <ArgumentNullException> (() => new AccessControl(null, enumeratedRights));
            Assert.Throws <ArgumentNullException> (() => new AccessControl("name", (string)null));
            Assert.Throws <ArgumentNullException> (() => new AccessControl("name", (IEnumerable <AccessRight>)null));

            Assert.Throws <ArgumentNullException> (() => new AccessControlList(null));

            Assert.Throws <ArgumentNullException> (() => new AccessRights((IEnumerable <AccessRight>)null));
            Assert.Throws <ArgumentNullException> (() => new AccessRights((string)null));

            var rights = new AccessRights();

            Assert.Throws <ArgumentNullException> (() => rights.AddRange((string)null));
            Assert.Throws <ArgumentNullException> (() => rights.AddRange((IEnumerable <AccessRight>)null));

            Assert.Throws <ArgumentNullException> (() => new AlertEventArgs(null));

            Assert.Throws <ArgumentNullException> (() => new FolderNamespace('.', null));

            var             namespaces = new FolderNamespaceCollection();
            FolderNamespace ns;

            Assert.Throws <ArgumentNullException> (() => namespaces.Add(null));
            Assert.Throws <ArgumentNullException> (() => namespaces.Contains(null));
            Assert.Throws <ArgumentNullException> (() => namespaces.Remove(null));
            Assert.Throws <ArgumentOutOfRangeException> (() => ns             = namespaces[-1]);
            Assert.Throws <ArgumentOutOfRangeException> (() => namespaces[-1] = new FolderNamespace('.', ""));

            namespaces.Add(new FolderNamespace('.', ""));
            Assert.Throws <ArgumentNullException> (() => namespaces[0] = null);

            Assert.Throws <ArgumentNullException> (() => new FolderNotFoundException(null));
            Assert.Throws <ArgumentNullException> (() => new FolderNotFoundException("message", null));
            Assert.Throws <ArgumentNullException> (() => new FolderNotFoundException("message", null, new Exception("message")));

            Assert.Throws <ArgumentNullException> (() => new FolderNotOpenException(null, FolderAccess.ReadOnly));
            Assert.Throws <ArgumentNullException> (() => new FolderNotOpenException(null, FolderAccess.ReadOnly, "message"));
            Assert.Throws <ArgumentNullException> (() => new FolderNotOpenException(null, FolderAccess.ReadOnly, "message", new Exception("message")));

            Assert.Throws <ArgumentNullException> (() => new FolderRenamedEventArgs(null, "name"));
            Assert.Throws <ArgumentNullException> (() => new FolderRenamedEventArgs("name", null));

            Assert.Throws <ArgumentOutOfRangeException> (() => new MessageEventArgs(-1));

            Assert.Throws <ArgumentNullException> (() => new MessageFlagsChangedEventArgs(0, MessageFlags.Answered, null));
            Assert.Throws <ArgumentNullException> (() => new MessageFlagsChangedEventArgs(0, MessageFlags.Answered, null, 1));
            Assert.Throws <ArgumentNullException> (() => new MessageFlagsChangedEventArgs(0, UniqueId.MinValue, MessageFlags.Answered, null));
            Assert.Throws <ArgumentNullException> (() => new MessageFlagsChangedEventArgs(0, UniqueId.MinValue, MessageFlags.Answered, null, 1));

            Assert.Throws <ArgumentNullException> (() => new MessageLabelsChangedEventArgs(0, null));
            Assert.Throws <ArgumentNullException> (() => new MessageLabelsChangedEventArgs(0, null, 1));
            Assert.Throws <ArgumentNullException> (() => new MessageLabelsChangedEventArgs(0, UniqueId.MinValue, null));
            Assert.Throws <ArgumentNullException> (() => new MessageLabelsChangedEventArgs(0, UniqueId.MinValue, null, 1));

            Assert.Throws <ArgumentNullException> (() => new MessageSentEventArgs(null, "response"));
            Assert.Throws <ArgumentNullException> (() => new MessageSentEventArgs(new MimeMessage(), null));

            Assert.Throws <ArgumentNullException> (() => new MessageSummaryFetchedEventArgs(null));

            Assert.Throws <ArgumentNullException> (() => new MessagesVanishedEventArgs(null, false));

            Assert.Throws <ArgumentNullException> (() => new MetadataCollection(null));

            var metadataOptions = new MetadataOptions();

            Assert.Throws <ArgumentOutOfRangeException> (() => metadataOptions.Depth = 500);

            Assert.Throws <ArgumentOutOfRangeException> (() => new ModSeqChangedEventArgs(-1));
            Assert.Throws <ArgumentOutOfRangeException> (() => new ModSeqChangedEventArgs(-1, 1));
            Assert.Throws <ArgumentOutOfRangeException> (() => new ModSeqChangedEventArgs(-1, UniqueId.MinValue, 1));

            Assert.Throws <ArgumentOutOfRangeException> (() => new OrderBy(OrderByType.To, SortOrder.None));

            Assert.Throws <ArgumentNullException> (() => new ProtocolLogger((string)null));
            Assert.Throws <ArgumentNullException> (() => new ProtocolLogger((Stream)null));
            using (var logger = new ProtocolLogger(new MemoryStream())) {
                var buffer = new byte[1024];

                Assert.Throws <ArgumentNullException> (() => logger.LogConnect(null));
                Assert.Throws <ArgumentNullException> (() => logger.LogClient(null, 0, 0));
                Assert.Throws <ArgumentNullException> (() => logger.LogServer(null, 0, 0));
                Assert.Throws <ArgumentOutOfRangeException> (() => logger.LogClient(buffer, -1, 0));
                Assert.Throws <ArgumentOutOfRangeException> (() => logger.LogServer(buffer, -1, 0));
                Assert.Throws <ArgumentOutOfRangeException> (() => logger.LogClient(buffer, 0, -1));
                Assert.Throws <ArgumentOutOfRangeException> (() => logger.LogServer(buffer, 0, -1));
            }

            Assert.Throws <ArgumentNullException> (() => new UniqueIdMap(null, new [] { UniqueId.MinValue }));
            Assert.Throws <ArgumentNullException> (() => new UniqueIdMap(new [] { UniqueId.MinValue }, null));
        }
Ejemplo n.º 11
0
        public static void Main(string[] args)
        {
            var logger = new ProtocolLogger(Console.OpenStandardError());

            using (var client = new ImapClient(logger)) {
                client.Connect("imap.gmail.com", 993, true);

                // Remove the XOAUTH2 authentication mechanism since we don't have an OAuth2 token.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                client.Authenticate("*****@*****.**", "password");

                client.Inbox.Open(FolderAccess.ReadOnly);

                // keep track of the messages
                var messages = client.Inbox.Fetch(0, -1, MessageSummaryItems.Full | MessageSummaryItems.UniqueId).ToList();

                // connect to some events...
                client.Inbox.MessagesArrived += (sender, e) => {
                    // Note: the CountChanged event will fire when new messages arrive in the folder.
                    var folder = (ImapFolder)sender;

                    // New messages have arrived in the folder.
                    Console.WriteLine("{0}: {1} new messages have arrived.", folder, e.Count);

                    // Note: your first instict may be to fetch these new messages now, but you cannot do
                    // that in an event handler (the ImapFolder is not re-entrant).
                };

                client.Inbox.MessageExpunged += (sender, e) => {
                    var folder = (ImapFolder)sender;

                    if (e.Index < messages.Count)
                    {
                        var message = messages[e.Index];

                        Console.WriteLine("{0}: expunged message {1}: Subject: {2}", folder, e.Index, message.Envelope.Subject);

                        // Note: If you are keeping a local cache of message information
                        // (e.g. MessageSummary data) for the folder, then you'll need
                        // to remove the message at e.Index.
                        messages.RemoveAt(e.Index);
                    }
                    else
                    {
                        Console.WriteLine("{0}: expunged message {1}: Unknown message.", folder, e.Index);
                    }
                };

                client.Inbox.MessageFlagsChanged += (sender, e) => {
                    var folder = (ImapFolder)sender;

                    Console.WriteLine("{0}: flags for message {1} have changed to: {2}.", folder, e.Index, e.Flags);
                };

                Console.WriteLine("Hit any key to end the IDLE loop.");
                using (var done = new CancellationTokenSource()) {
                    var thread = new Thread(IdleLoop);

                    thread.Start(new IdleState(client, done.Token));

                    Console.ReadKey();
                    done.Cancel();
                    thread.Join();
                }

                if (client.Inbox.Count > messages.Count)
                {
                    Console.WriteLine("The new messages that arrived during IDLE are:");
                    foreach (var message in client.Inbox.Fetch(messages.Count, -1, MessageSummaryItems.Full | MessageSummaryItems.UniqueId))
                    {
                        Console.WriteLine("Subject: {0}", message.Envelope.Subject);
                    }
                }

                client.Disconnect(true);
            }
        }
Ejemplo n.º 12
0
        public void TestLoggingWithTimestamps()
        {
            string format;

            using (var stream = new MemoryStream()) {
                using (var logger = new ProtocolLogger(stream, true)
                {
                    LogTimestamps = true
                }) {
                    format = logger.TimestampFormat;

                    logger.LogConnect(new Uri("pop://pop.skyfall.net:110"));

                    var cmd = Encoding.ASCII.GetBytes("RETR 1\r\n");
                    logger.LogClient(cmd, 0, cmd.Length);

                    using (var response = GetType().Assembly.GetManifestResourceStream("UnitTests.Net.Pop3.Resources.comcast.retr1.txt")) {
                        using (var filtered = new FilteredStream(response)) {
                            var buffer = new byte[4096];
                            int n;

                            filtered.Add(new Unix2DosFilter());

                            while ((n = filtered.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                logger.LogServer(buffer, 0, n);
                            }
                        }
                    }
                }

                stream.Position = 0;

                using (var reader = new StreamReader(stream)) {
                    DateTime timestamp;
                    string   line;

                    line = reader.ReadLine();

                    Assert.IsTrue(TryExtractTimestamp(ref line, format, out timestamp), "Connect timestamp");
                    Assert.AreEqual("Connected to pop://pop.skyfall.net:110/", line);

                    line = reader.ReadLine();
                    Assert.IsTrue(TryExtractTimestamp(ref line, format, out timestamp), "C: RETR 1 timestamp");
                    Assert.AreEqual("C: RETR 1", line);

                    using (var response = GetType().Assembly.GetManifestResourceStream("UnitTests.Net.Pop3.Resources.comcast.retr1.txt")) {
                        using (var r = new StreamReader(response)) {
                            string expected;

                            while ((expected = r.ReadLine()) != null)
                            {
                                line = reader.ReadLine();

                                Assert.IsTrue(TryExtractTimestamp(ref line, format, out timestamp), "S: timestamp");
                                Assert.AreEqual("S: " + expected, line);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 13
0
        private static async Task <SendEmailResponse> SendMessageAsync(
            MimeMessage mimeMessage,
            SmtpServerConnectionDefinition smtpServerConnectionDefinition)
        {
            using (var logStream = new MemoryStream())
            {
                using (var protocolLogger = new ProtocolLogger(logStream, leaveOpen: false))
                {
                    using (var smtpClient = new MailKit.Net.Smtp.SmtpClient(protocolLogger))
                    {
                        SendEmailResponse result;

                        string logMessages;

                        var secureSocketOptions = GetSecureSocketOptions(smtpServerConnectionDefinition.SecureConnectionMethod);

                        try
                        {
                            await smtpClient.ConnectAsync(smtpServerConnectionDefinition.Host, smtpServerConnectionDefinition.Port, secureSocketOptions);
                        }
                        catch (Exception ex)
                        {
                            logMessages = GetLogMessages(logStream);

                            result = new SendEmailResponse(SendEmailResult.FailedToConnectToServer, ex.ToString(), logMessages);

                            return(result);
                        }

                        try
                        {
                            await smtpClient.AuthenticateAsync(smtpServerConnectionDefinition.Username, smtpServerConnectionDefinition.ClearTextPassword);
                        }
                        catch (Exception ex)
                        {
                            logMessages = GetLogMessages(logStream);

                            result = new SendEmailResponse(SendEmailResult.FailedToAuthenticateWithServer, ex.ToString(), logMessages);

                            return(result);
                        }

                        try
                        {
                            await smtpClient.SendAsync(mimeMessage);
                        }
                        catch (Exception ex)
                        {
                            logMessages = GetLogMessages(logStream);

                            result = new SendEmailResponse(SendEmailResult.FailedToSendEmailToServer, ex.ToString(), logMessages);

                            return(result);
                        }

                        try
                        {
                            await smtpClient.DisconnectAsync(true);
                        }
                        catch (Exception)
                        {
                            // This doesn't constitute a failure; the email has been sent.
                        }

                        logMessages = GetLogMessages(logStream);

                        result = new SendEmailResponse(SendEmailResult.Success, null, logMessages);

                        return(result);
                    }
                }
            }
        }
Ejemplo n.º 14
0
        public static void Main(string[] args)
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;

            currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

            string dataPath        = GetLocalAppDataPath();
            string MBoxViewerPath  = Path.Combine(dataPath, "MBoxViewer");
            string MailServicePath = Path.Combine(MBoxViewerPath, "MailService");
            string TempPath        = Path.Combine(MailServicePath, "Temp");

            string okFilePath               = MailServicePath + "\\ForwardMailSuccess.txt";
            string errorFilePath            = MailServicePath + "\\ForwardMailError.txt";
            string errorFilePathOldInstance = MailServicePath + "\\ForwardMailError2.txt";

            System.IO.DirectoryInfo info = Directory.CreateDirectory(TempPath);

            string loggerFilePath = FindKeyinArgs(args, "--logger-file");
            var    logger         = new FileLogger();

            logger.Open(loggerFilePath);
            logger.Log("Logger Open");

            try
            {
                // File.Delete doesn't seem to generate exceptions if file doesn't exist
                //if (File.Exists(okFilePath)
                File.Delete(okFilePath);
                //if (File.Exists(errorFilePath)
                File.Delete(errorFilePath);
                File.Delete(errorFilePathOldInstance);
            }
            catch (Exception ex)
            {
                string txt = String.Format("Delete Critical Files Failed\n{0}\n{1}\n{2}\n\n{3}",
                                           okFilePath, errorFilePath, errorFilePathOldInstance, ex.Message);
                bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, txt);
                logger.Log("Exception in Delete Critical Files: ", ex.ToString());
                System.Environment.Exit(ExitCodes.ExitMailAddress);
            }

            int numArgs = args.GetLength(0);

            if ((numArgs <= 0) || ((numArgs % 2) != 0))
            {
                string errorText = String.Format("Invalid command argument list: {0} .", String.Join(" ", args));
                bool   rval      = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n");
                logger.Log(errorText);
                System.Environment.Exit(ExitCodes.ExitCmdArguments);
            }

            /*
             * if (numArgs <= 0)
             * {
             *  logger.Log(@"Usage: --from addr --to addr1,addr2,.. --cc addr1,addr2,.. -bcc addr1,addr2,..
             *      --user login-user-name --passwd --login-user-password --smtp smtp-server-name", "");
             *  Debug.Assert(true == false);
             *  System.Environment.Exit(1);
             * }
             */
            string     instance               = "";
            IniFile    smtpIni                = null;
            EMailInfo  mailInfo               = new EMailInfo();
            SMTPConfig smtpConfig             = new SMTPConfig();
            string     smtpConfigFilePath     = "";
            string     UserPassword           = "";
            string     protocolLoggerFilePath = "";

            int tcpListenPort = 0;

            logger.Log("Command line argument list:");
            for (int j = 0, i = 0; j < numArgs; j = j + 2, i++)
            {
                string key = args[j];
                string val = args[j + 1];

                if (!key.StartsWith("--"))
                {
                    string errorText = String.Format("Invalid key: {0} ", key);
                    bool   rval      = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n");
                    logger.Log(errorText);
                    System.Environment.Exit(ExitCodes.ExitCmdArguments);
                }
                if ((j + 1) >= numArgs)
                {
                    string errorText = String.Format("Found key: {0} without value.", key);
                    bool   rval      = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n");
                    logger.Log(errorText);
                    System.Environment.Exit(ExitCodes.ExitCmdArguments);
                }
                if (key.CompareTo("--instance-id") == 0)
                {
                    instance = val;
                }
                else if (key.CompareTo("--smtp-protocol-logger") == 0)
                {
                    protocolLoggerFilePath = val;
                }
                else if (key.CompareTo("--from") == 0)
                {
                    mailInfo.From = val;
                }
                else if (key.CompareTo("--to") == 0)
                {
                    mailInfo.To = val;
                }
                else if (key.CompareTo("--cc") == 0)
                {
                    mailInfo.CC = val;
                }
                else if (key.CompareTo("--bcc") == 0)
                {
                    mailInfo.BCC = val;
                }
                else if (key.CompareTo("--user") == 0)
                {
                    mailInfo.To = val;
                }
                else if (key.CompareTo("--passwd") == 0)
                {
                    UserPassword = val;
                }
                else if (key.CompareTo("--smtp-cnf") == 0)
                {
                    smtpConfigFilePath = val;
                }
                else if (key.CompareTo("--tcp-port") == 0)
                {
                    tcpListenPort = int.Parse(val);
                }
                else if (key.CompareTo("--eml-file") == 0)
                {
                    mailInfo.EmlFilePath = val;
                }
                else if (key.CompareTo("--mail-text-file") == 0)
                {
                    mailInfo.TextFilePath = val;
                }
                else if (key.CompareTo("--logger-file") == 0)
                {
                    ; // see FindKeyinArgs(args, "--logger-file");
                }
                else
                {
                    logger.Log(String.Format("    Unknown Key: {0} {1}", args[j], args[j + 1]));
                }
                logger.Log(String.Format("    {0} {1}", args[j], args[j + 1]));
            }

            if (smtpConfigFilePath.Length == 0)
            {
                string errorText = String.Format("required --smtp-cnf command line argument missing.");
                bool   rval      = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n");
                logger.Log(errorText);
                System.Environment.Exit(ExitCodes.ExitCmdArguments);
            }

            if (!File.Exists(smtpConfigFilePath))
            {
                string errorText = String.Format("SMTP configuration file {0} doesn't exist.", smtpConfigFilePath);
                bool   rval      = FileUtils.CreateWriteCloseFile(errorFilePath, errorText + "\n");
                logger.Log(errorText);
                System.Environment.Exit(ExitCodes.ExitCmdArguments);
            }
            try
            {
                if (protocolLoggerFilePath.Length > 0)
                {
                    File.Delete(protocolLoggerFilePath);
                }
            }
            catch (Exception /*ex*/) {; } // ignore

            smtpIni = new IniFile(smtpConfigFilePath);

            string ActiveMailService = smtpIni.IniReadValue("MailService", "ActiveMailService");

            smtpConfig.MailServiceName   = smtpIni.IniReadValue(ActiveMailService, "MailServiceName");
            smtpConfig.SmtpServerAddress = smtpIni.IniReadValue(ActiveMailService, "SmtpServerAddress");
            smtpConfig.SmtpServerPort    = int.Parse(smtpIni.IniReadValue(ActiveMailService, "SmtpServerPort"));
            smtpConfig.UserAccount       = smtpIni.IniReadValue(ActiveMailService, "UserAccount");
            if (UserPassword.Length > 0)
            {
                smtpConfig.UserPassword = UserPassword;
            }
            else
            {
                smtpConfig.UserPassword = smtpIni.IniReadValue(ActiveMailService, "UserPassword");
            }
            smtpConfig.EncryptionType = int.Parse(smtpIni.IniReadValue(ActiveMailService, "EncryptionType"));

            logger.Log(smtpConfig.ToString());

            // Uncomment when you exec this application from MBoxViewer
            //smtpConfig.UserPassword = "";
            if (smtpConfig.UserPassword.Length == 0)
            {
                logger.Log("Waiting to receive password");
                smtpConfig.UserPassword = WaitForPassword(tcpListenPort, logger, errorFilePath);

                if (smtpConfig.UserPassword.Length > 0)
                {
                    logger.Log("Received non empty password");
                    //logger.Log("Received non empty password: "******"Received empty password");
                }

                int found = smtpConfig.UserPassword.IndexOf(":");
                if (found <= 0)
                {
                    // Old instance , log to differnt file
                    bool rval = FileUtils.CreateWriteCloseFile(errorFilePathOldInstance, "Received invalid id:password. Exitting\n");
                    System.Environment.Exit(ExitCodes.ExitCmdArguments);
                }
                string id     = smtpConfig.UserPassword.Substring(0, found);
                string passwd = smtpConfig.UserPassword.Substring(found + 1);
                smtpConfig.UserPassword = passwd;

                logger.Log("Command line instance id: ", instance);
                logger.Log("Received instance id: ", id);
                //logger.Log("Received password: "******"Received password: "******"xxxxxxxxxxxx");

                if (id.CompareTo(instance) != 0)
                {
                    // Old instance , log to different file
                    bool rval = FileUtils.CreateWriteCloseFile(errorFilePathOldInstance, "This is old instance. Exitting\n");
                    System.Environment.Exit(ExitCodes.ExitCmdArguments);
                }
            }

            MimeKit.ParserOptions opt = new MimeKit.ParserOptions();

            var From = new MailboxAddress("", smtpConfig.UserAccount);
            //
            InternetAddressList CCList  = new InternetAddressList();
            InternetAddressList BCCList = new InternetAddressList();
            InternetAddressList ToList  = new InternetAddressList();

            try
            {
                if (mailInfo.To.Length > 0)
                {
                    ToList = MimeKit.InternetAddressList.Parse(opt, mailInfo.To);
                }
                if (mailInfo.CC.Length > 0)
                {
                    CCList = MimeKit.InternetAddressList.Parse(opt, mailInfo.CC);
                }
                if (mailInfo.BCC.Length > 0)
                {
                    BCCList = MimeKit.InternetAddressList.Parse(opt, mailInfo.BCC);
                }
            }
            catch (Exception ex)
            {
                bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Parsing Internet Address list Failed\n", ex.Message);
                logger.Log("Exception in InternetAddressList.Parse: ", ex.ToString());
                System.Environment.Exit(ExitCodes.ExitMailAddress);
            }

            //
            string emlFilePath = mailInfo.EmlFilePath;

            // create the main textual body of the message
            var text = new TextPart("plain");

            try
            {
                text.Text = File.ReadAllText(mailInfo.TextFilePath, Encoding.UTF8);
            }
            catch (Exception ex)
            {
                bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Building Mime Mesage Failed\n", ex.Message);
                logger.Log("Exception in Building Mime Message: ", ex.ToString());
                System.Environment.Exit(ExitCodes.ExitMimeMessage);
            }

            logger.Log("Forwarding Eml file:", emlFilePath);
            MimeMessage msg = null;

            try
            {
                var message = new MimeMessage();
                message = MimeKit.MimeMessage.Load(emlFilePath);

                List <MimeMessage> mimeMessages = new List <MimeMessage>();
                mimeMessages.Add(message);

                msg = BuildMimeMessageWithEmlAsRFC822Attachment(text, mimeMessages, From, ToList, CCList, BCCList);
            }
            catch (Exception ex)
            {
                bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Building Mime Mesage Failed\n", ex.Message);
                logger.Log("Exception in Building Mime Message: ", ex.ToString());
                System.Environment.Exit(ExitCodes.ExitMimeMessage);
            }

            logger.Log("BuildMimeMessageWithEmlAsRFC822Attachment Done");

            //string msgAsString = MailkitConvert.ToString(msg);
            //string msgAsString = msg.ToString();
            //logger.Log("\n", msgAsString);

            // OAUTH2 works on Google but requires verification by Google and it seems to be chargable option if number of users > 100
            // Another problem is that ClientSecret can't be hardcoded in the application
            // For now we will just rely on User Account and User Password for authentication
            SaslMechanism oauth2    = null;;
            bool          useOAUTH2 = false;

            if (useOAUTH2)
            {
                string appClientId     = "xxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
                string appClientSecret = "yyyyyyyyyyyyyyyyyyyyyyyyyyy";

                var accessScopes = new[]
                {
                    // that is the only scope that works per info from jstedfast
                    "https://mail.google.com/",
                };

                var clientSecrets = new ClientSecrets
                {
                    ClientId     = appClientId,
                    ClientSecret = appClientSecret
                };
                oauth2 = GetAuth2Token(smtpConfig.UserAccount, clientSecrets, accessScopes);
            }

            IProtocolLogger smtpProtocolLogger = null;

            if (protocolLoggerFilePath.Length > 0)
            {
                smtpProtocolLogger = new ProtocolLogger(protocolLoggerFilePath);
            }
            else
            {
                smtpProtocolLogger = new NullProtocolLogger();
            }

            using (var client = new SmtpClient(smtpProtocolLogger))
            {
                try
                {
                    client.Connect(smtpConfig.SmtpServerAddress, smtpConfig.SmtpServerPort, (SecureSocketOptions)smtpConfig.EncryptionType);
                }
                catch (Exception ex)
                {
                    bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Connect to SMTP Server Failed\n", ex.Message);
                    logger.Log("Exception in Connect: ", ex.ToString());
                    System.Environment.Exit(ExitCodes.ExitConnect);
                }

                logger.Log(String.Format("Connected to {0} mail service", smtpConfig.MailServiceName));

                try
                {
                    if (useOAUTH2)
                    {
                        client.Authenticate(oauth2);
                    }
                    else
                    {
                        client.Authenticate(smtpConfig.UserAccount, smtpConfig.UserPassword);
                    }
                }
                catch (Exception ex)
                {
                    bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "SMTP Authentication Failed\n", ex.Message);
                    logger.Log("Exception in Authenticate: ", ex.ToString());
                    System.Environment.Exit(ExitCodes.ExitAuthenticate);
                }
                logger.Log("SMTP Authentication Succeeded");

                // Clear smtpConfig.UserPassword in case it cores
                smtpConfig.UserPassword = "";

                try
                {
                    client.Send(msg);
                }
                catch (Exception ex)
                {
                    bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Send Failed\n", ex.Message);
                    logger.Log("Exception in Send to SMTP Server: ", ex.ToString());

                    //string msgString = MailkitConvert.ToString(msg);
                    //string msgAsString = msg.ToString();

                    // To help to investigate Warning place at the begining of the serialized MimeMessage
                    // X - MimeKit - Warning: Do NOT use ToString() to serialize messages! Use one of the WriteTo() methods instead!
                    //logger.Log("\n", msgString);

                    System.Environment.Exit(ExitCodes.ExitSend);
                }

                string txt = "Mail Sending Succeeded";
                logger.Log(txt);
                bool retval = FileUtils.CreateWriteCloseFile(okFilePath, txt);

                try
                {
                    client.Disconnect(true);
                }
                catch (Exception ex)
                {
                    // Ignore, not a fatal error
                    //bool rval = FileUtils.CreateWriteCloseFile(errorFilePath, "Send Failed\n", ex.Message);
                    logger.Log("Exception in Disconnect to SMTP Server: ", ex.ToString());
                }
                logger.Log("SMTP Client Disconnected. All done.");
            }
            System.Environment.Exit(ExitCodes.ExitOk);
        }