示例#1
1
        public static List<PhotoData> GetPhotoData(bool deleteMessages)
        {
            var imagesData = new List<PhotoData>();
            OpenPOP.POP3.POPClient client = new POPClient( "mail.shockbyte.com.ar", 110, "*****@*****.**", "Password11", AuthenticationMethod.USERPASS );
            Console.WriteLine ("Connected");
            var count = client.GetMessageCount( );
            Console.WriteLine ("Message Count: " + count);
            for ( int i = 1; i <= count; i++ )
            {
                Console.WriteLine ("Message");
                var message = client.GetMessage( i, false );

                foreach ( Attachment att in message.Attachments )
                {
                    Console.WriteLine ("Att: " + att.ContentFileName);
                    var extPos = att.ContentFileName.LastIndexOf( "." );
                    if ( extPos >= 0 )
                    {
                        var ext = att.ContentFileName.Substring( extPos + 1 ).ToLowerInvariant( );

                        var photo = new PhotoData( ) { Data = att.DecodedAsBytes( ), From = message.From, Title = message.Subject, FileName = att.ContentFileName };

                        switch ( ext )
                        {
                            case "jpg":
                            case "jpeg":
                                photo.ImageType = "image/jpeg";
                                imagesData.Add( photo );

                                break;

                            case "gif":
                                photo.ImageType = "image/gif";
                                imagesData.Add( photo );

                                break;

                            case "png":
                                photo.ImageType = "image/png";
                                imagesData.Add( photo );

                                break;
                        }
                    }
                }
            }

            if ( deleteMessages )
            {
                client.DeleteAllMessages( );
            }

            client.Disconnect( );

            return imagesData;
        }
示例#2
0
        static void Main(string[] args)
        {
            DateTime start = DateTime.Now;
            POPClient c = new POPClient("212.42.77.244", 110, "*****@*****.**", "jgnbvf", AuthenticationMethod.USERPASS);
            c.ReceiveTimeOut = 10000000;
            int mc = c.GetMessageCount();
            for (int i = mc; i >= 1; i--)
            {

                OpenPOP.MIMEParser.Message m = c.GetMessageHeader(i);// c.GetMessage(i, false);

                Console.WriteLine(String.Format("{0} - {1}", i.ToString(), m.FromEmail));
                m = null;
            }
            c.Disconnect();
            Console.WriteLine(DateTime.Now - start);
        }
示例#3
0
        private void downloadReplaysButton_Click(object sender, RoutedEventArgs e)
        {
            string smtpUsername = smtpUsernameTextBox.Text;
            string smtpPassword = smtpPasswordTextBox.Text;
            string pop3Url = smtpUrlTextBox.Text;

            smtpUsername = "******";
            smtpPassword = "******";
            pop3Url = "pop3.live.com";

            if (string.IsNullOrEmpty(smtpUsername) || string.IsNullOrEmpty(smtpPassword) || string.IsNullOrEmpty(pop3Url))
                return;

            POPClient client = new POPClient();
            client.Connect(pop3Url, 995, true);
            client.Authenticate(smtpUsername, smtpPassword);
            if (!client.Connected) return;

            int totalEmails = client.GetMessageCount();

            for (int i = 83; i < totalEmails; i++)
            {
                OpenPOP.MIME.Header.MessageHeader header = client.GetMessageHeaders(i);
                if (header.Subject.IndexOf("SC2Replay", StringComparison.InvariantCultureIgnoreCase) == -1) continue;

                OpenPOP.MIME.Message message = client.GetMessage(i);

                if (message == null) continue;
                if (message.Attachments.Count != 1) continue;

                OpenPOP.MIME.Attachment attachment = message.Attachments[0];
                if (attachment.IsMIMEMailFile()) continue;

                if (attachment.Headers.ContentType.Name == null) continue;
                if (attachment.Headers.ContentType.Name.ToLower() != "sc2replay")
                    continue;

                attachment.SaveToFile(@"C:\waka.sc2replay");
            }
            client.Disconnect();
        }
示例#4
0
        public EmailAccountHelper(
            String name,
            String userPassword,
            String server,
            int port)
        {
            userName = name;
            password = userPassword;
            popServerName = server;
            popServerPort = port;

            //mailConnection
            //    = new POP3Connection(
            //    userName,
            //    password,
            //    popServerName,
            //    popServerPort);

            mailClient = new POPClient();
            mailClient.UseSSL = useSSL;
        }
示例#5
0
        public static Message[] Receive(HostConfigObject pop3config)
        {
            POPClient popClient = new POPClient();
            // Set timeouts to 5 seconds
            popClient.ReceiveTimeOut = 5000;
            popClient.SendTimeOut = 5000;
            bool connected = false;

            // Port is set to automatic, try SSL first, then STANDARD
            if (pop3config.Port == 0)
            {
                Console.WriteLine("Automatic port is activated for POP3 host.");
                Console.WriteLine("Trying to connect with SSL.");
                connected = Connect(popClient,pop3config.Host, SSL);
                if (!connected)
                {
                    Console.WriteLine("Connection denied.");
                    Console.WriteLine("Trying to connect at standard port [" + STANDARD + "].");
                    connected = Connect(popClient, pop3config.Host, STANDARD);
                    if (!connected)
                    {
                        Console.WriteLine("Connection denied.");
                    }
                    else
                    {
                        Console.WriteLine("Connection granted.");
                    }
                }
                else
                {
                    Console.WriteLine("Connection granted.");
                }
            }
            else
            {
                Console.WriteLine("Currently activated port: " + pop3config.Port);
                Console.WriteLine("Trying to connect at this port.");
                connected = Connect(popClient,pop3config.Host, pop3config.Port);
                if (!connected)
                {
                    Console.WriteLine("Connection denied.");
                }
                else
                {
                    Console.WriteLine("Connection granted.");
                }
            }

            bool errorOccured = false;
            // Contacting the server and login

            Message[] msgArray = null;
            if (connected){
                try {
                    Console.WriteLine("Starting authentication.");
                    AuthenticationMethod auth = AuthenticationMethod.TRYBOTH;
                    popClient.Authenticate(pop3config.Username, pop3config.Password, auth);
                    Logger.sendMessage("Login successful.", Logger.MessageTag.INFO);
                    Console.WriteLine("login successful.");

                    int msgCount = popClient.GetMessageCount();
                    Logger.sendMessage("Account statistics loaded. [" + msgCount + "] messages on server.", Logger.MessageTag.INFO);
                    Console.WriteLine("Account statistics loaded. [" + msgCount + "] messages on server.");

                    List<Message> msgs = new List<Message>();

                    //System.Windows.Forms.MessageBox.Show("Fetching first 3 messages only (Bugfixing)");
                    // Mailbox entries always start with "1"
                    for (int i = 1; i <= 3; i++) // msgCount
                    {
                        if (running)
                        {
                            // Receive complete email
                            Message msgObj = popClient.GetMessage(i, false);
                            if (msgObj != null)
                            {
                                msgs.Add(msgObj);
                            }
                        }
                    }

                    msgArray = (Message[])msgs.ToArray();
                }
                catch (Exception)
                {
                    errorOccured = true;
                    Logger.sendMessage("Problem while receiving message/s.", Logger.MessageTag.ERROR);
                }
                finally
                {
                    popClient.Disconnect();
                }
            }
            if (!errorOccured)
            {
                Logger.sendMessage("Received " + (msgArray != null ? msgArray.Length.ToString() : "no") + " mails from " + pop3config.Description + ".", Logger.MessageTag.INFO);
            }
            return msgArray;
        }
示例#6
0
 private static bool Connect(POPClient popClient, string host, int port)
 {
     bool connected = false;
     try
     {
         if (running)
         {
             popClient.Connect(host, port);
             Logger.sendMessage("Connecting to [" + host + "] using port [" + port + "]" + (port == SSL ? " SSL" : "") + ".", Logger.MessageTag.INFO);
             connected = true;
         }
     }
     catch (Exception)
     {
         Logger.sendMessage("Unable to connect to [" + host + "] using port [" + port + "]" + (port == SSL ? " SSL" : "") + ".", Logger.MessageTag.ERROR);
     }
     return connected;
 }
        /// <summary>
        /// Download and process email messages from the POP3 server.
        /// </summary>
        /// <param name="server">POP3 server information</param>
        public static void DownloadMessages()
        {
            Trace.WriteLine("Entered DownloadMessages().");

            // Get POP3 server info
            PopServer server = GetPopServer();
            Trace.WriteLine("  Retrieved POP server info.");

            // connect to POP3 server and download messages
            //FoeDebug.Print("Connecting to POP3 server...");
            POPClient popClient = new POPClient();
            popClient.IsUsingSsl = server.SslEnabled;

            popClient.Disconnect();
            popClient.Connect(server.ServerName, server.Port);
            popClient.Authenticate(server.UserName, server.Password);

            Trace.WriteLine("  Connected to POP3.");

            // get mail count
            int count = popClient.GetMessageCount();
            Trace.WriteLine("  There are " + count.ToString() + " messages in inbox.");

            // go through each message, from newest to oldest
            for (int i = count; i >= 1; i -= 1)
            {
                Trace.WriteLine("  Opening message #" + i.ToString());

                OpenPOP.MIMEParser.Message msg = popClient.GetMessage(i, true);
                if (msg != null)
                {
                    string subject = msg.Subject;
                    string fromEmail = msg.FromEmail;

                    Trace.WriteLine("  Message came from " + msg.FromEmail + " with subject \"" + msg.Subject + "\"");

                    // Check if fromEmail is the same as processor's email on file
                    if (fromEmail.ToLower() == FoeClientRegistry.GetEntry("processoremail").Value.ToLower())
                    {
                        Trace.WriteLine("  Message came from the processor.");

                        // parse subject line
                        string[] tokens = subject.Trim().Split(new char[] { ' ' });

                        // There should be 5 or 6 tokens
                        if (tokens.Length == 5)
                        {
                            Trace.WriteLine("  There are 5 tokens.");

                            // Get the request ID for this reply
                            string requestId = tokens[2];

                            // Check if request ID matches any request the client sent
                            FoeClientRequestItem req = FoeClientRequest.Get(requestId);

                            if (req != null)
                            {
                                Trace.WriteLine("  Message Request ID matched.");

                                // Found the matching request
                                // Download the full reply
                                OpenPOP.MIMEParser.Message wholeMsg = popClient.GetMessage(i, false);
                                string msgBody = (string)wholeMsg.MessageBody[0];

                                Trace.WriteLine("  Downloaded full message body.");

                                try
                                {
                                    // decompress it
                                    byte[] compressedMsg = Convert.FromBase64String(msgBody);
                                    Trace.WriteLine("  Decoded Base64 message.");

                                    byte[] decompressedMsg = CompressionManager.Decompress(compressedMsg);
                                    Trace.WriteLine("  Decompressed message.");

                                    string foe = Encoding.UTF8.GetString(decompressedMsg);
                                    Trace.WriteLine("  Retrieved original FOE message.");

                                    // Check what is the original request type
                                    if (req.Type.ToLower() == "registe")
                                    {
                                        Trace.WriteLine("  Registration reply. Processing message.");
                                        ProcessRegistrationReply(foe);
                                        Trace.WriteLine("  Registration reply processed.");
                                    }
                                    else if (req.Type.ToLower() == "catalog")
                                    {
                                        Trace.WriteLine("  Catalog reply. Processing message.");
                                        ProcessCatalogReply(foe);
                                        Trace.WriteLine("  Catalog reply processed.");
                                    }
                                    else if (req.Type.ToLower() == "feed")
                                    {
                                        Trace.WriteLine("  feed reply. Processing message.");
                                        ProcessCatalogReply(foe);
                                        Trace.WriteLine("  feed reply processed.");
                                    }
                                }
                                catch (Exception except)
                                {
                                    // the message is likely malformed
                                    // so just ignore it
                                    Trace.WriteLine("  Exception detected: \r\n" + except.ToString());
                                }
                            }
                            else
                            {
                                Trace.WriteLine("  Message ID mismatched.");
                            }
                        }
                        //content request's reply
                        else if (tokens.Length == 6)
                        {
                            Trace.WriteLine("  There are 6 tokens.");

                            // Get the request ID for this reply
                            string catalog = tokens[1];
                            string requestId = tokens[3];

                            // Check if request ID matches any request the client sent
                            FoeClientRequestItem req = FoeClientRequest.Get(requestId);

                            if (req != null)
                            {
                                Trace.WriteLine("  Message Request ID matched.");

                                // Found the matching request
                                // Download the full reply
                                OpenPOP.MIMEParser.Message wholeMsg = popClient.GetMessage(i, false);
                                string msgBody = (string)wholeMsg.MessageBody[0];

                                Trace.WriteLine("  Downloaded full message body.");

                                try
                                {
                                    byte[] compressed = Convert.FromBase64String(msgBody);
                                    byte[] decompressed = CompressionManager.Decompress(compressed);
                                    string foe = Encoding.UTF8.GetString(decompressed);

                                    // Check what is the original request type
                                    if (req.Type.ToLower() == "content")
                                    {
                                        Trace.WriteLine("  Content reply. Processing message.");
                                        ProcessContentReply(catalog, foe);
                                        Trace.WriteLine("  Content reply processed.");
                                    }
                                }
                                catch (Exception except)
                                {
                                    // the message is likely malformed
                                    // so just ignore it
                                    Trace.WriteLine("  Exception detected: \r\n" + except.ToString());
                                }
                            }
                            else
                            {
                                Trace.WriteLine("  Message ID mismatched.");
                            }
                        }
                        else
                        {
                            Trace.WriteLine("  Message does not have 5 tokens.");
                        }
                    }
                    else
                    {
                        Trace.WriteLine("  Message did not come from processor.");
                    }
                }
                // Delete the current message
                popClient.DeleteMessage(i);
                Trace.WriteLine("  Deleted current message in inbox.");
            }
            popClient.Disconnect();
            Trace.WriteLine("  Disconnected from POP server.");

            Trace.WriteLine("  Exiting DownloadMessages().");
        }
        /// <summary>
        /// Email Verifies account once successfully created
        /// Also inserts account to Database
        /// Verifies Yahoo, Gmail & Hotmail
        /// </summary>
        public void VerifiyAccountMultiThreaded(string email, string password, string proxyAddress, string proxyPort, string proxyUser, string proxyPassword, ref GlobusHttpHelper HttpHelper)
        {
            try
            {
                POPClient popClient = new POPClient();

                AddToListBox("Verifying through Email: " + email);
                AddToListBox("It may take some time, please wait...");

                #region Gmail
                if (email.Contains("@gmail"))
                {
                    if (popClient.Connected)
                        popClient.Disconnect();
                    popClient.Connect("pop.gmail.com", int.Parse("995"), true);
                    popClient.Authenticate(email, password);
                    int Count = popClient.GetMessageCount();

                    for (int i = Count; i >= 1; i--)
                    {
                        OpenPOP.MIME.Message Message = popClient.GetMessage(i);

                        string subject = Message.Headers.Subject;

                        if (Message.Headers.Subject.Contains("Action Required: Confirm Your Facebook Account"))
                        {
                            foreach (string href in GetUrlsFromString(Message.MessageBody[0]))
                            {
                                try
                                {
                                    string staticUrl = string.Empty;
                                    string email_open_log_picUrl = string.Empty;

                                    string strBody = Message.MessageBody[0];
                                    string[] arr = Regex.Split(strBody, "src=");
                                    foreach (string item in arr)
                                    {
                                        if (!item.Contains("<!DOCTYPE"))
                                        {
                                            if (item.Contains("static"))
                                            {
                                                string[] arrStatic = item.Split('"');
                                                staticUrl = arrStatic[1];
                                            }
                                            if (item.Contains("email_open_log_pic"))
                                            {
                                                string[] arrlog_pic = item.Split('"');
                                                email_open_log_picUrl = arrlog_pic[1];
                                                email_open_log_picUrl = email_open_log_picUrl.Replace("amp;", "");
                                                break;
                                            }
                                        }
                                    }

                                    string href1 = href.Replace("&amp;report=1", "");
                                    href1 = href.Replace("amp;", "");

                                    EmailVerificationMultithreaded(href1, staticUrl, email_open_log_picUrl, email, password, proxyAddress, proxyPort, proxyUser, proxyPassword, ref HttpHelper);

                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex.StackTrace);
                                }
                            }
                        }
                        else if (Message.Headers.Subject.Contains("Just one more step to get started on Facebook"))
                        {
                            foreach (string href in GetUrlsFromString(Message.MessageBody[0]))
                            {
                                try
                                {
                                    string staticUrl = string.Empty;
                                    string email_open_log_picUrl = string.Empty;

                                    string strBody = Message.MessageBody[0];
                                    string[] arr = Regex.Split(strBody, "src=");
                                    foreach (string item in arr)
                                    {
                                        if (!item.Contains("<!DOCTYPE"))
                                        {
                                            if (item.Contains("static"))
                                            {
                                                string[] arrStatic = item.Split('"');
                                                staticUrl = arrStatic[1];
                                            }
                                            if (item.Contains("email_open_log_pic"))
                                            {
                                                string[] arrlog_pic = item.Split('"');
                                                email_open_log_picUrl = arrlog_pic[1];
                                                email_open_log_picUrl = email_open_log_picUrl.Replace("amp;", "");
                                                break;
                                            }
                                        }
                                    }

                                    string href1 = href.Replace("&amp;report=1", "");
                                    href1 = href.Replace("amp;", "");

                                    EmailVerificationMultithreaded(href1, staticUrl, email_open_log_picUrl, email, password, proxyAddress, proxyPort, proxyUser, proxyPassword, ref HttpHelper);

                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex.StackTrace);
                                }
                            }
                        }

                    }
                }
                #endregion

                #region Yahoo
                else if (email.Contains("@yahoo"))
                {
                    ChilkatIMAP imap = new ChilkatIMAP();

                    imap.proxyAddress = proxyAddress;
                    imap.proxyPort = proxyPort;
                    imap.proxyUser = proxyUser;
                    imap.proxyPass = proxyPassword;
                    imap.GetFBMails(email, password);
                }



                #endregion

                #region Hotmail
                else if (email.Contains("@hotmail"))
                {
                    if (popClient.Connected)
                        popClient.Disconnect();
                    popClient.Connect("pop3.live.com", int.Parse("995"), true);
                    popClient.Authenticate(email, password);
                    int Count = popClient.GetMessageCount();

                    for (int i = Count; i >= 1; i--)
                    {
                        OpenPOP.MIME.Message Message = popClient.GetMessage(i);

                        string subject = Message.Headers.Subject;

                        if (Message.Headers.Subject.Contains("Action Required: Confirm Your Facebook Account"))
                        {
                            foreach (string href in GetUrlsFromString(Message.MessageBody[0]))
                            {
                                try
                                {
                                    string staticUrl = string.Empty;
                                    string email_open_log_picUrl = string.Empty;

                                    string strBody = Message.MessageBody[0];
                                    string[] arr = Regex.Split(strBody, "src=");
                                    foreach (string item in arr)
                                    {
                                        if (!item.Contains("<!DOCTYPE"))
                                        {
                                            if (item.Contains("static"))
                                            {
                                                string[] arrStatic = item.Split('"');
                                                staticUrl = arrStatic[1];
                                            }
                                            if (item.Contains("email_open_log_pic"))
                                            {
                                                string[] arrlog_pic = item.Split('"');
                                                email_open_log_picUrl = arrlog_pic[1];
                                                email_open_log_picUrl = email_open_log_picUrl.Replace("amp;", "");
                                                break;
                                            }
                                        }
                                    }

                                    string href1 = href.Replace("&amp;report=1", "");
                                    href1 = href.Replace("amp;", "");

                                    EmailVerificationMultithreaded(href1, staticUrl, email_open_log_picUrl, email, password, proxyAddress, proxyPort, proxyUser, proxyPassword, ref HttpHelper);

                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex.StackTrace);
                                }
                            }
                        }
                        else if (Message.Headers.Subject.Contains("Just one more step to get started on Facebook"))
                        {
                            foreach (string href in GetUrlsFromString(Message.MessageBody[0]))
                            {
                                try
                                {
                                    string staticUrl = string.Empty;
                                    string email_open_log_picUrl = string.Empty;

                                    string strBody = Message.MessageBody[0];
                                    string[] arr = Regex.Split(strBody, "src=");
                                    foreach (string item in arr)
                                    {
                                        if (!item.Contains("<!DOCTYPE"))
                                        {
                                            if (item.Contains("static"))
                                            {
                                                string[] arrStatic = item.Split('"');
                                                staticUrl = arrStatic[1];
                                            }
                                            if (item.Contains("email_open_log_pic"))
                                            {
                                                string[] arrlog_pic = item.Split('"');
                                                email_open_log_picUrl = arrlog_pic[1];
                                                email_open_log_picUrl = email_open_log_picUrl.Replace("amp;", "");
                                                break;
                                            }
                                        }
                                    }

                                    string href1 = href.Replace("&amp;report=1", "");
                                    href1 = href.Replace("amp;", "");

                                    EmailVerificationMultithreaded(href1, staticUrl, email_open_log_picUrl, email, password, proxyAddress, proxyPort, proxyUser, proxyPassword, ref HttpHelper);

                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex.StackTrace);
                                }
                            }
                        }

                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                if (ex.Message.Contains("InvalidPasswordException"))
                {
                    //AddToListBox("Invalid Password :"******"--- " + email);
                }
            }
            finally
            {
                //Write to text file
                //Also insert in Database
                try
                {
                    GlobusFileHelper.AppendStringToTextfileNewLine(email + ":" + password + ":" + proxyAddress + ":" + proxyPort + ":" + proxyUser + ":" + proxyPassword, Path.Combine(Globals.FD_DesktopPath, "CreatedAccounts.txt"));
                    DataBaseHandler.InsertQuery("Insert into tb_FBAccount values('" + email + "','" + password + "','" + proxyAddress + "','" + proxyPort + "','" + proxyUser + "','" + proxyPassword + "','" + "" + "','" + "" + "','" + AccountStatus.Status(ProfileStatus.AccountCreated) + "')", "tb_FBAccount");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                }
            }
        }
        /// <summary>
        /// Download and process email messages from the POP3 server.
        /// </summary>
        /// <param name="server">POP3 server information</param>
        public static void DownloadMessages()
        {
            // Get POP3 server info
            PopServer server = GetPopServer();

            // connect to POP3 server and download messages
            //FoeDebug.Print("Connecting to POP3 server...");
            POPClient popClient = new POPClient();
            popClient.IsUsingSsl = server.SslEnabled;

            popClient.Disconnect();
            popClient.Connect(server.ServerName, server.Port);
            popClient.Authenticate(server.UserName, server.Password);

            FoeDebug.Print("Connected to POP3.");

            // get mail count
            int count = popClient.GetMessageCount();

            // go through each message, from newest to oldest
            for (int i = count; i >= 1; i -= 1)
            {
                OpenPOP.MIMEParser.Message msg = popClient.GetMessage(i, true);
                if (msg != null)
                {
                    string subject = msg.Subject;
                    string fromEmail = msg.FromEmail;

                    // Check if fromEmail is the same as processor's email on file
                    if (fromEmail.ToLower() == FoeClientRegistry.GetEntry("processoremail").Value.ToLower())
                    {
                        // parse subject line
                        string[] tokens = subject.Trim().Split(new char[] { ' ' });

                        // There should be 5 tokens
                        if (tokens.Length == 5)
                        {
                            // Get the request ID for this reply
                            string requestId = tokens[2];

                            // Check if request ID matches any request the client sent
                            FoeClientRequestItem req = FoeClientRequest.Get(requestId);
                            if (req != null)
                            {
                                // Found the matching request
                                // Download the full reply
                                OpenPOP.MIMEParser.Message wholeMsg = popClient.GetMessage(i, false);
                                string msgBody = (string)wholeMsg.MessageBody[0];

                                try
                                {
                                    // decompress it
                                    byte[] compressedMsg = Convert.FromBase64String(msgBody);
                                    byte[] decompressedMsg = CompressionManager.Decompress(compressedMsg);
                                    string foeXml = Encoding.UTF8.GetString(decompressedMsg);

                                    // Check what is the original request type
                                    if (req.Type.ToLower() == "reg")
                                    {
                                        ProcessRegistrationReply(foeXml);
                                    }
                                    else if (req.Type.ToLower() == "content")
                                    {
                                        ProcessContentReply(foeXml);
                                    }
                                    else if (req.Type.ToLower() == "catalog")
                                    {
                                        ProcessCatalogReply(foeXml);
                                    }
                                }
                                catch (Exception)
                                {
                                    // the message is likely malformed
                                    // so just ignore it
                                }
                            }
                        }
                    }
                }
                // Delete the current message
                popClient.DeleteMessage(i);
            }
            popClient.Disconnect();
        }
示例#10
0
        private object[] PopMailScan()
        {
            POPClient currentPopClient = new POPClient();
            Message currentMessage;
            int msgNumber;
            int j = 0;
            object[] tmpObjectArray;

            try
            {
                Utils.MaMessage(String.Format(tsl.T("[POPSCANCONNECTING]"), DateTime.Now.ToString(TimeFormat), CurrentConfig.InputPopHost, CurrentConfig.InputPopPort));

                //Establishing connection to mail server
                currentPopClient.Connect(CurrentConfig.InputPopHost, CurrentConfig.InputPopPort);
                if (currentPopClient.Connected)
                {
                    // Retrieve credentials
                    Utils.MaMessage(String.Format(tsl.T("[POPSCANCONNECTED]"), DateTime.Now.ToString(TimeFormat), CurrentConfig.InputPopHost), Utils.maMessageLineType.WriteLine, Utils.maMessageOutput.ConsoleAndLog, CurrentConfig.LogFile);
                    GetCredentials(ref CurrentConfig.InputPopLogin, ref CurrentConfig.InputPopPassword, "[LOGININPUT]", "[PASSWORDINPUT]");
                    //Authenticate
                    currentPopClient.Authenticate(CurrentConfig.InputPopLogin, CurrentConfig.InputPopPassword);
                    // Get message Number
                    msgNumber = currentPopClient.GetMessageCount();
                    Utils.MaMessage(String.Format(tsl.T("[POPSCANFOUND]"), DateTime.Now.ToString(TimeFormat), msgNumber), Utils.maMessageLineType.WriteLine, Utils.maMessageOutput.ConsoleAndLog, CurrentConfig.LogFile);
                    //dimension array
                    tmpObjectArray = new object[msgNumber];

                    // Setting array
                    for (int i=0; i<msgNumber ; i++)
                    {
                       //Get message header
                        currentMessage = currentPopClient.GetMessageHeader(i + 1);
                        // If subject matches filter
                        if (currentMessage.Subject.Contains(CurrentConfig.InputPopFilter))
                        {
                            // Get message
                            Utils.MaMessage(String.Format(tsl.T("[POPSCANRETRIEVING]"), DateTime.Now.ToString(TimeFormat), i + 1, msgNumber));
                            currentMessage = currentPopClient.GetMessage(i + 1, false);
                            // If there is an attachment, store message and delete it
                            if (currentMessage.HasAttachment)
                            {
                                tmpObjectArray[j] = currentMessage;
                                if (CurrentConfig.InputPopDeleteMessages)
                                {
                                    currentPopClient.DeleteMessage(i + 1);
                                }
                                j++;
                            }
                            else
                                Utils.MaMessage(String.Format(tsl.T("[POPSCANNOATT]"), DateTime.Now.ToString(TimeFormat), i + 1, msgNumber));

                        }
                        else
                        {
                            Utils.MaMessage(String.Format(tsl.T("[POPSCANNOMATCH]"), DateTime.Now.ToString(TimeFormat), i + 1, msgNumber,CurrentConfig.InputPopFilter, currentMessage.Subject));

                        }
                    }
                    tmpObjectArray = Utils.ResizeObjectArray(tmpObjectArray, j);

                    currentPopClient.Disconnect();
                    return tmpObjectArray;
                }
                else
                {
                    throw new Exception(tsl.T("[POPSCANNOCONNECTION]"));
                }
            }
            catch (Exception e)
            {
                Utils.MaMessage(String.Format(tsl.T("[POPSCANERROR]"), DateTime.Now.ToString(TimeFormat), e.Message), Utils.maMessageLineType.WriteLine, Utils.maMessageOutput.ConsoleAndLog, CurrentConfig.LogFile);
                return null;
            }
        }
示例#11
0
        public void ReceiveProcessMails()
        {
            //inserts.Clear();
              mails.Clear();

              Message m = null;
              byte[] bytes;
              String uid = "";
              DateTime dt = DateTime.Now;
              string sdt = "";
              DatabaseMailRecord mail;
              POPClient popClient = new POPClient();
              listReport = new List<IridiumExtremeBinaryReport>();
              try
              {
            log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "Log Iniciado");

            //string TableName = config.getConfigValue("databasesection", "tablename", "tablename");

            int hours = config.getConfigValue("messagesection", "purgetimehours", 30);
            log.writeToLogFile("purgetimehours {0}", hours);

            string s = config.getConfigValue("popsection", "PopServer", "");
            int ins = config.getConfigValue("popsection", "PopPort", 80);
            popClient.Connect(s, ins);
            log.writeToLogFile("Conectado a {0}:{1}", s, ins);

            s = config.getConfigValue("popsection", "PopUsername", "");
            popClient.Authenticate(s, config.getConfigValue("popsection", "PopPassword", ""));
            log.writeToLogFile("Autenticado {0}", s);

            int Count = popClient.GetMessageCount();
            log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "Hay {0} mensajes", Count);

            IridiumExtremeBinaryReport.NumsWithComma = config.getConfigValue("messagesection", "numswithcomma", true);

            for (int i = Count; i >= 1; i -= 1)
            {
              try
              {
            uid = popClient.GetMessageUID(i);
            m = popClient.GetMessage(i, true);

            try
            {
              dt = DateTime.Parse(m.Date);
              sdt = dt.Ticks.ToString();
            }
            catch (Exception)
            {
              sdt = "0";
            }
            if (md.isMail(uid, sdt))
            {
              if (dt.AddHours(hours) < DateTime.Now)
              {
                string strLog = string.Format("Mail muy antiguo {0}, fecha: '{1}', id {2}", i, dt.ToString("yyyy/MM/dd HH:mm:ss"), uid);
                try
                {
                  //popClient.DeleteMessage(i);
                  log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "{0}, fue borrado exitosamente", strLog);
                }
                catch (Exception ex)
                {
                  log.writeToLogFile(LogType.LOG_ERR, "ReceiveProcessMails", "{0}, hubo un error al intentar borrarlo: {1}", strLog, ex.Message);
                }
              }
              continue;
            }
            else
            {
              md.addValue(uid, sdt);
              if (m != null)
              {
                if (m.HasAttachment)
                {
                  m = popClient.GetMessage(i, false);
                  if (m.Attachments.Count > 0)
                  {
                    foreach (OpenPOP.MIMEParser.Attachment a in m.Attachments)
                    {
                      string attachName = m.GetAttachmentFileName(a);
                      string extension = Path.GetExtension(attachName);

                      if (extension.Equals(config.getValue("AttachmentType")))
                      {
                        mail = new DatabaseMailRecord();
                        mail.Uid = uid;

                        string imei = "desconocido";
                        imei = getIdFromSubject(m.Subject);
                        //try
                        //{
                        //  mail.Data = a.DecodeAsText();
                        //}
                        // catch (Exception)
                        //{
                        //  bytes = a.DecodedAsBytes();
                        //  mail.Data = HexAscii.ConvertToHexAscii(bytes);
                        //  log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "El archivo no es string, procesando como binario");
                        //}
                        try
                        {
                          bytes = a.DecodedAsBytes();
                          saveToDisck(bytes, attachName, @"\MESSAGES_INBOX");
                          mail.Data = HexAscii.ConvertToHexAscii(bytes);
                          log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "El archivo no es string, procesando como binario");
                        }
                        catch (Exception) { }
                        mail.DataTime = dt;
                        mails.Add(mail);
                        string strlog = string.Format("Mail {0}, fecha: '{1}', id {2}", i, dt.ToString("yyyy/MM/dd HH:mm:ss"), uid);
                        strlog = string.Format("{0}, subject: {1}, atachment: {2}", strlog, m.Subject, attachName);
                        strlog = string.Format("{0}, contenido: '{1}', de {2}", strlog, mail.Data.Replace('\r', ' '), m.From);
                        log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", strlog);
                        IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport();
                        string type = "MO";
                        if (IridiumExtremeBinaryReport.TryParse(HexAscii.ConvertToBytes(mail.Data), imei, out report, type))
                        {
                          if (report.inbox)
                          {
                            string TableName = config.getConfigValue("databasesection", "tableinbox", "tablename");
                            inserts.Add(report.ToInsertSQL(true, TableName));
                          }
                          if (report.posiciones)
                          {
                            string TableName = config.getConfigValue("databasesection", "tableposition", "tablename");
                            inserts.Add(report.ToInsertSQL(true, TableName));
                          }
                          //listReport.Add(report);
                        }
                      }
                      else
                      {
                        if (extension.Equals(".htm"))
                        {
                          if (m.Subject.Contains("SBD Mobile Terminated Message Queued for Unit:"))
                          {
                            //string data = mail.Data.Replace('\r', ' ');
                            string filename = getBetween(m.RawMessage, "Filename: ", "\r");
                            string imei = getBetween(m.RawMessage, "IMEI: ", "\r");
                            DateTime time = DateTime.Parse(m.Date);
                            string gatewayStatus = "";
                            if (m.RawMessage.Contains("The following mobile-terminated message was queued for delivery"))
                            {
                              gatewayStatus = "The mobile-terminated message was queued for delivery";
                            }
                            try
                            {
                              OdbcCommand comm;
                              string sql = "";
                              List<string> updates = new List<string>();
                              if (ConnectToDatabase(out comm))
                              {
                                string TableName = config.getValue("tablesent");
                                sql = string.Format("update {0} set GATEWAY_DATETIME = '{1}' where ATTACHMENT_FILENAME = '{2}' and EQP_ESN = '{3}'", TableName, time.ToString("yyyy/MM/dd HH:mm:ss"), filename, imei);
                                //updates.Add(sql);
                                inserts.Add(sql);
                                sql = string.Format("update {0} set GATEWAY_STATUS = '{1}' where ATTACHMENT_FILENAME = '{2}' and EQP_ESN = '{3}'", TableName, gatewayStatus, filename, imei);
                                //updates.Add(sql);
                                inserts.Add(sql);
                                //foreach (string query in updates)
                                //{
                                //  comm.CommandText = query;
                                //  comm.ExecuteNonQuery();
                                //}
                              }

                            }
                            catch (Exception ex)
                            { }
                          }

                        }
                      }
                    }
                  }
                }
                else
                {
                  log.writeToLogFile(LogType.LOG_ERR, "ReceiveProcessMails", "El mail {0} esta corrupto o es erroneo", i);
                }
              }
            }
              }
              catch (Exception ex)
              {
            if (m != null)
              log.writeToLogFile(LogType.LOG_ERR, "ReceiveProcessMails", "Hubo un en un mail {0}, {1}, error: {2}", m.From, m.Date, ex.Message);
            else
              log.writeToLogFile(LogType.LOG_ERR, "ReceiveProcessMails", "Hubo un en un mail {0}, error: {1}", uid, ex.Message);
              }
            }
              }
              catch (Exception ex)
              {
            log.writeToLogFile(LogType.LOG_ERR, "ReceiveProcessMails", "Hubo un error: {0} ", ex.Message);
              }
              finally
              {
            popClient.Disconnect();
            log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "Desconectado");
            log.Flush();
              }
        }
示例#12
0
 static void CheckMail()
 {
     try
     {
         Console.WriteLine("Checking Mailbox");
         POPClient pop3 = new POPClient();
         pop3.Connect(settings.Default.EmailHost, 110, false);
         pop3.Authenticate(settings.Default.EmailUsername, settings.Default.EmailPassword);
         int i = 0;
         while (i <= pop3.GetMessageCount())
         {
             Console.WriteLine(pop3.GetMessageCount());
             var msg = pop3.GetMessage(i);
             if (msg != null && msg.MessageBody.Capacity > 0 && !string.IsNullOrEmpty(msg.MessageBody[0]) && msg.Headers.From.ToString() == settings.Default.EmailFromAddress)
             {
                 Console.WriteLine("Marking message for deletion..");
                 pop3.DeleteMessage(i);
                 string msgbody = msg.MessageBody[0].Replace("\n", " ");
                 msgbody = msgbody.Replace("\r", " ");
                 var msgsplit = new StringStream(msgbody);
                 msgbody = msgsplit.NextWord("=====");
                 BuildNotifier.Irc.CommandHandler.Msg(settings.Default.NotificationChannel, msgbody);
                 Console.WriteLine(msgbody);
             }
             i++;
         }
         Console.WriteLine("Closing connection, deleting messages");
         pop3.Disconnect();
     }
     catch (Exception e)
     {
         WriteErrorSystem.WriteError(null, e.Message + e.Data + e.Source + e.StackTrace);
     }
 }
示例#13
0
           public override Email readEmail(string email, string password, string proxyAddress, string proxyPort, string proxyUser, string proxyPassword, string DOB, ref GlobusHttpHelper HttpHelper, string registrationstatus)
           {
               //throw new NotImplementedException();//Ajay to code this part

               Email objEmail = new Email();

               string realEmail = string.Empty;

               try
               {
                   objEmail.username = email;
                   objEmail.password = password;

                   realEmail = email;
                   POPClient popClient = new POPClient();

                   #region Hotmail
                   if (email.Contains("@hotmail"))
                   {
                       try
                       {
                           // Code For [email protected]
                           if (email.Contains("+") || email.Contains("%2B"))
                           {
                               try
                               {
                                   string replacePart = email.Substring(email.IndexOf("+"), (email.IndexOf("@", email.IndexOf("+")) - email.IndexOf("+"))).Replace("+", string.Empty);
                                   email = email.Replace("+", string.Empty).Replace("%2B", string.Empty).Replace(replacePart, string.Empty);
                               }
                               catch(Exception ex)
                               {
                                   GlobusLogHelper.log.Error("Error : "+ex.StackTrace);
                               }
                           }

                           if (popClient.Connected)
                               popClient.Disconnect();
                           popClient.Connect("pop3.live.com", int.Parse("995"), true);  //live
                           popClient.Authenticate(email, password);
                           int Count = popClient.GetMessageCount();

                           for (int i = Count; i >= 1; i--)
                           {
                               try
                               {
                                   OpenPOP.MIME.Message Message = popClient.GetMessage(i);

                                   string subject = Message.Headers.Subject;

                                   if (Message.Headers.Subject.Contains("Action Required: Confirm Your Facebook Account"))
                                   {
                                       foreach (string href in GetUrlsFromString(Message.MessageBody[0]))
                                       {
                                           try
                                           {
                                               string staticUrl = string.Empty;
                                               string email_open_log_picUrl = string.Empty;

                                               string strBody = Message.MessageBody[0];
                                               string[] arr = Regex.Split(strBody, "src=");
                                               foreach (string item in arr)
                                               {
                                                   if (!item.Contains("<!DOCTYPE"))
                                                   {
                                                       if (item.Contains("static"))
                                                       {
                                                           string[] arrStatic = item.Split('"');
                                                           staticUrl = arrStatic[1];
                                                       }
                                                       if (item.Contains("email_open_log_pic"))
                                                       {
                                                           try
                                                           {
                                                               string[] arrlog_pic = item.Split('"');
                                                               email_open_log_picUrl = arrlog_pic[1];
                                                               email_open_log_picUrl = email_open_log_picUrl.Replace("amp;", "");
                                                           }
                                                           catch(Exception ex)
                                                           {
                                                               GlobusLogHelper.log.Error("Error :"+ex.StackTrace);
                                                           }
                                                           break;
                                                       }
                                                   }
                                               }

                                               string href1 = href.Replace("&amp;report=1", "");
                                               href1 = href.Replace("amp;", "");


                                               objEmail.body = strBody;
                                               objEmail.subject = Message.Headers.Subject;
                                               List<System.Net.Mail.MailAddress> lstTo = Message.Headers.To;

                                               foreach (System.Net.Mail.MailAddress item in lstTo)
                                               {
                                                   try
                                                   {
                                                       objEmail.to = objEmail.to + item.ToString();
                                                   }
                                                   catch (Exception ex)
                                                   {
                                                       GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
                                                   }
                                               }

                                               objEmail.from = Message.Headers.From.ToString();

                                               objEmail.mailType = MailType.hotmail;

                                               // if (href1.Contains(Uri.EscapeDataString(realEmail)))
                                               {
                                                   EmailVerificationMultithreaded(href1, staticUrl, email_open_log_picUrl, realEmail, password, proxyAddress, proxyPort, proxyUser, proxyPassword, ref HttpHelper);
                                               }

                                           }
                                           catch (Exception ex)
                                           {
                                               GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
                                           }
                                       }
                                   }
                                   else if (Message.Headers.Subject.Contains("Just one more step to get started on Facebook"))
                                   {
                                       foreach (string href in GetUrlsFromString(Message.MessageBody[0]))
                                       {
                                           try
                                           {
                                               string staticUrl = string.Empty;
                                               string email_open_log_picUrl = string.Empty;

                                               string strBody = Message.MessageBody[0];
                                               string[] arr = Regex.Split(strBody, "src=");
                                               foreach (string item in arr)
                                               {
                                                   try
                                                   {
                                                       if (!item.Contains("<!DOCTYPE"))
                                                       {
                                                           if (item.Contains("static"))
                                                           {
                                                               string[] arrStatic = item.Split('"');
                                                               staticUrl = arrStatic[1];
                                                           }
                                                           if (item.Contains("email_open_log_pic"))
                                                           {
                                                               string[] arrlog_pic = item.Split('"');
                                                               email_open_log_picUrl = arrlog_pic[1];
                                                               email_open_log_picUrl = email_open_log_picUrl.Replace("amp;", "");
                                                               break;
                                                           }
                                                       }
                                                   }
                                                   catch (Exception ex)
                                                   {
                                                       GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
                                                   }
                                               }

                                               string href1 = href.Replace("&amp;report=1", "");
                                               href1 = href.Replace("amp;", "");


                                               objEmail.body = strBody;
                                               objEmail.subject = Message.Headers.Subject;
                                               List<System.Net.Mail.MailAddress> lstTo = Message.Headers.To;

                                               foreach (System.Net.Mail.MailAddress item in lstTo)
                                               {
                                                   try
                                                   {
                                                       objEmail.to = objEmail.to + item.ToString();
                                                   }
                                                   catch (Exception ex)
                                                   {
                                                       GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
                                                   }
                                               }

                                               objEmail.from = Message.Headers.From.ToString();

                                               objEmail.mailType = MailType.hotmail;

                                               // if (href1.Contains(Uri.EscapeDataString(realEmail)))
                                               {
                                                   EmailVerificationMultithreaded(href1, staticUrl, email_open_log_picUrl, realEmail, password, proxyAddress, proxyPort, proxyUser, proxyPassword, ref HttpHelper);
                                               }

                                           }
                                           catch (Exception ex)
                                           {
                                               GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
                                           }
                                       }
                                   }
                               }
                               catch (Exception ex)
                               {
                                   GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
                               }

                           }
                       }
                       catch (Exception ex)
                       {
                           GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
                       }
                   }
                   #endregion
               }
               catch (Exception ex)
               {
                   GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
               }

               return objEmail;
           }
        /// <summary>
        /// Download email messages from the POP3 server for a given Foe message processor.
        /// </summary>
        /// <param name="server">POP3 server information</param>
        /// <param name="processorEmail">The current Foe message processor's email address.</param>
        public static void DownloadMessages(PopServer server, string processorEmail)
        {
            // connect to POP3 server and download messages
            //FoeDebug.Print("Connecting to POP3 server...");
            POPClient popClient = new POPClient();
            popClient.IsUsingSsl = server.SslEnabled;

            popClient.Disconnect();
            popClient.Connect(server.ServerName, server.Port);
            popClient.Authenticate(server.UserName, server.Password);

            FoeDebug.Print("Connected to POP3.");

            // get mail count
            int count = popClient.GetMessageCount();

            FoeDebug.Print("Server reported " + count.ToString() + " messages.");

            // go through each message, from newest to oldest
            for (int i = count; i >= 1; i -= 1)
            {
                //FoeDebug.Print("Opening mail message...");

                OpenPOP.MIMEParser.Message msg = popClient.GetMessage(i, true);
                if (msg != null)
                {
                    // Get subject and verify sender identity
                    // Subject line in the mail header should look like one of the followings:
                    //
                    // Normal request (for news feed and content):
                    //   Subject: Request <Request ID> by <User ID>
                    //
                    // Registration request:
                    //   Subject: Register <Request ID> by Newbie
                    //
                    // where:
                    // Request ID is the request ID generated by the Foe client
                    // User ID is the user's ID as assigned by the server

                    //FoeDebug.Print("Message is not null. Getting message details.");

                    string subject = msg.Subject;
                    string fromEmail = msg.FromEmail;

                    //FoeDebug.Print("Subject: " + subject);
                    //FoeDebug.Print("From: " + fromEmail);

                    // parse subject line
                    string[] tokens = subject.Trim().Split(new char[] { ' ' });
                    if (tokens.Length == 4)
                    {
                        // check what type of request is it
                        string requestType = tokens[0].ToUpper();
                        string requestId = tokens[1];
                        string userId = tokens[3];

                        FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                                "subject: " + subject + "requestType: "+ requestType);
                        if (requestType.ToUpper().CompareTo("REGISTE") == 0)
                        {
                            //FoeDebug.Print("This is a registration message.");
                            // It's a registration request
                            SaveRegistrationRequest(requestId, fromEmail, processorEmail);

                            FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                                "Received registration request from " + fromEmail);
                        }
                        else if (requestType.ToUpper().CompareTo("CATALOG") == 0)
                        {
                            // get user info by email address
                            FoeUser user = FoeServerUser.GetUser(fromEmail);

                            // verify user's email against the user ID
                            if ((user != null) && (userId == user.UserId) && (processorEmail == user.ProcessorEmail))
                            {
                                FoeDebug.Print("User verified.");

                                // the user's identity is verified
                                SaveCatalogRequest(requestId, user.Email, processorEmail);

                            }
                            else
                            {
                                //FoeDebug.Print("User is not registered. Request not processed.");
                                FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning,
                                    "Received content request from unregistered user " + fromEmail);
                            }
                        }
                        else if (requestType.ToUpper().CompareTo("CONTENT") == 0)
                        {
                            //FoeDebug.Print("This is a content request message.");

                            // It's a content request.
                            // We need to verify the user's identify first.

                            //FoeDebug.Print("Verifying user identity...");

                            // get user info by email address
                            FoeUser user = FoeServerUser.GetUser(fromEmail);

                            // verify user's email against the user ID
                            if ((user != null) && (userId == user.UserId) && (processorEmail == user.ProcessorEmail))
                            {
                                FoeDebug.Print("User verified.");

                                // the user's identity is verified
                                // get the full message body
                                OpenPOP.MIMEParser.Message wholeMsg = popClient.GetMessage(i, false);
                                string msgBody = (string)wholeMsg.MessageBody[0];

                                try
                                {
                                    // decompress it
                                    byte[] compressedMsg = Convert.FromBase64String(msgBody);
                                    byte[] decompressedMsg = CompressionManager.Decompress(compressedMsg);
                                    string foe = Encoding.UTF8.GetString(decompressedMsg);

                                    string[] catalogs = foe.Trim().Split(new char[] { ',' });
                                    // save request
                                    if (catalogs.Length == 0)
                                    {
                                        return;
                                    }
                                    SaveContentRequest(requestId, user.Email, catalogs, processorEmail);

                                    //FoeDebug.Print("Request saved and pending processing.");
                                    FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                                        "Received content request from verified user " + fromEmail);
                                }
                                catch (Exception except)
                                {
                                    // the message is likely malformed
                                    // so just ignore it
                                    FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning,
                                        "Received malformed content request from verified user " + fromEmail + "\r\n" +
                                        except.ToString() +
                                        "Raw message:\r\n" + msgBody + "\r\n");

                                    //throw except;
                                }
                            }
                            else
                            {
                                //FoeDebug.Print("User is not registered. Request not processed.");
                                FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning,
                                    "Received content request from unregistered user " + fromEmail);
                            }
                        }
                        else if (requestType.ToUpper().CompareTo("FEED") == 0)
                        {
                            //FoeDebug.Print("This is a content request message.");

                            // It's a content request.
                            // We need to verify the user's identify first.

                            //FoeDebug.Print("Verifying user identity...");

                            // get user info by email address
                            FoeUser user = FoeServerUser.GetUser(fromEmail);

                            // verify user's email against the user ID
                            if ((user != null) && (userId == user.UserId) && (processorEmail == user.ProcessorEmail))
                            {
                                FoeDebug.Print("User verified.");

                                // the user's identity is verified
                                // get the full message body
                                OpenPOP.MIMEParser.Message wholeMsg = popClient.GetMessage(i, false);
                                string msgBody = (string)wholeMsg.MessageBody[0];

                                try
                                {
                                    // decompress it
                                    byte[] compressedMsg = Convert.FromBase64String(msgBody);
                                    byte[] decompressedMsg = CompressionManager.Decompress(compressedMsg);
                                    string foe = Encoding.UTF8.GetString(decompressedMsg);

                                    string[] array = foe.Trim().Split(new char[] { ',' });
                                    // save request
                                    if (array.Length == 0)
                                    {
                                        return;
                                    }
                                    SaveFeedRequest(requestId, user.Email, array, processorEmail);

                                    //FoeDebug.Print("Request saved and pending processing.");
                                    FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                                        "Received feed request from verified user " + fromEmail);
                                }
                                catch (Exception except)
                                {
                                    // the message is likely malformed
                                    // so just ignore it
                                    FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning,
                                        "Received malformed feed request from verified user " + fromEmail + "\r\n" +
                                        except.ToString() +
                                        "Raw message:\r\n" + msgBody + "\r\n");

                                    //throw except;
                                }
                            }
                            else
                            {
                                //FoeDebug.Print("User is not registered. Request not processed.");
                                FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning,
                                    "Received content request from unregistered user " + fromEmail);
                            }
                        }
                        else
                        {
                            // Non-Foe message
                            FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                                "Received non-Foe message from " + fromEmail);
                        }
                    }
                    else
                    {
                        // Non-Foe message
                        FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message,
                            "Received non-Foe message from " + fromEmail);
                    }

                    // Delete the current message
                    popClient.DeleteMessage(i);
                }
            }
            popClient.Disconnect();
        }
        public void Execute(XmlNode node)
        {
            if (node.Attributes == null) return;

            XmlAttribute server = node.Attributes["Server"];
            XmlAttribute port = node.Attributes["Port"];
            XmlAttribute username = node.Attributes["Username"];
            XmlAttribute password = node.Attributes["Password"];
            XmlAttribute connectionStringName = node.Attributes["ConnectionStringName"];
            
            var popClient = new POPClient();
            popClient.Connect(server.Value, int.Parse(port.Value), false);
            popClient.Authenticate(username.Value, password.Value);
            int count = popClient.GetMessageCount();

            if (count <= 0)
            {
                popClient.Disconnect();
                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionStringName.Value].ConnectionString))
                {
                    connection.Open();
                    List<Product> productsFromBase = GetRelatedProductsFromBase(connection);
                    List<Product> allHouseFlowers = GetFlowers(connection);
                    foreach (var product in allHouseFlowers)
                    {
                        string diam = GetDiametr(product.ShortDescription);
                        int diametr;
                        if (Int32.TryParse(diam, out diametr))
                        {
                            List<Product> neededRelatedProducts = GetNeededRelatedProducts(productsFromBase, diametr);
                            List<Product> existingRelatedProducts = GetExistingRelatedProducts(connection, product.Id);
                            foreach (var p in existingRelatedProducts)
                            {
                                neededRelatedProducts.RemoveAll(x => (x.Id == p.Id));
                            }

                            UpdateRelatedProducts(connection, neededRelatedProducts, product);
                        }
                    }
                }
                return;
            }

            for (int i = count; i >= 1; i -= 1)
            {
                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionStringName.Value].ConnectionString))
                {
                    connection.Open();
                    Message message = popClient.GetMessage(i);
                    string[] rows = message.MessageBody[0].Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (string row in rows)
                    {
                        try
                        {
                            string[] cols = row.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                            if (cols[2].Contains("."))
                                continue;
                            string sku = cols[0];
                            decimal price = decimal.Parse(cols[1]);
                            int quantity = int.Parse(cols[2]);

                            using (var command = new SqlCommand(UpdateProductVariantQuery, connection))
                            {
                                command.Parameters.Add(new SqlParameter("@Sku", sku));
                                command.Parameters.Add(new SqlParameter("@Price", price));
                                command.Parameters.Add(new SqlParameter("@StockQuantity", quantity));

                                command.ExecuteNonQuery();
                            }

                            if (cols.Length == 5)
                            {
                                int height;
                                int diameter;
                                bool heightParsed = int.TryParse(cols[3], out height);
                                bool diameterParsed = int.TryParse(cols[4], out diameter);

                                using (var command = new SqlCommand(UpdateProductVariantQuery, connection))
                                {
                                    command.Parameters.Add(new SqlParameter("@Sku", sku));
                                    Product product = null;

                                    int saoHeightId = 0;
                                    if (heightParsed && height != 0)
                                    {
                                        product = GetProduct(connection, sku);

                                        if (height < 11) saoHeightId = 54;
                                        else if (height >= 11 && height < 16) saoHeightId = 55;
                                        else if (height >= 16 && height < 21) saoHeightId = 56;
                                        else if (height >= 21 && height < 26) saoHeightId = 57;
                                        else if (height >= 26 && height < 31) saoHeightId = 58;
                                        else if (height >= 31 && height < 50) saoHeightId = 64;
                                        else if (height >= 50) saoHeightId = 60;

                                        if (product != null && !SaoExists(connection, product.Id, saoHeightId))
                                        {
                                            InsertSao(connection, product.Id, saoHeightId);
                                        }

                                    }

                                    int saoDiameterId = 0;
                                    if (diameterParsed && diameter != 0)
                                    {
                                        if (product == null)
                                            product = GetProduct(connection, sku);

                                        if (diameter < 11) saoDiameterId = 16;
                                        else if (diameter >= 11 && diameter < 16) saoDiameterId = 18;
                                        else if (diameter >= 16 && diameter < 21) saoDiameterId = 48;
                                        else if (diameter >= 21 && diameter < 26) saoDiameterId = 49;
                                        else if (diameter >= 26 && diameter < 31) saoDiameterId = 50;
                                        else if (diameter >= 31 && diameter < 50) saoDiameterId = 51;
                                        else if (diameter >= 50) saoDiameterId = 52;

                                        if (product != null && !SaoExists(connection, product.Id, saoDiameterId))
                                        {
                                            InsertSao(connection, product.Id, saoDiameterId);
                                        }
                                    }

                                    if (product != null)
                                    {
                                        string oldShortDescription = product.ShortDescription;
                                        string oldFullDescription = product.FullDescription;

                                        if (diameterParsed && heightParsed)
                                        {
                                            if (!product.ShortDescription.ToLower().Contains("(см)"))
                                                product.ShortDescription += (product.ShortDescription == string.Empty ? "" : "<br />") + string.Format("{0}X{1}(см)", height, diameter);
                                            if (!product.FullDescription.ToLower().Contains("высота"))
                                                product.FullDescription += (product.FullDescription == string.Empty ? "" : "<br />") + string.Format("Высота - {0} см", height);
                                            if (!product.FullDescription.ToLower().Contains("диаметр"))
                                                product.FullDescription += (product.FullDescription == string.Empty ? "" : "<br />") + string.Format("Диаметр - {0} см", diameter);
                                        }
                                        else if (heightParsed)
                                        {
                                            if (!product.ShortDescription.Contains(string.Format("{0}X-(см)", height)))
                                                product.ShortDescription += (product.ShortDescription == string.Empty ? "" : "<br />") + string.Format("{0}X-(см)", height);
                                            if (!product.FullDescription.ToLower().Contains("высота"))
                                                product.FullDescription += (product.FullDescription == string.Empty ? "" : "<br />") + string.Format("Высота - {0} см", height);
                                        }
                                        else if (diameterParsed)
                                        {
                                            if (!product.ShortDescription.Contains(string.Format("-X{0}(см)", diameter)))
                                                product.ShortDescription += (product.ShortDescription == string.Empty ? "" : "<br />") + string.Format("-X{0}(см)", diameter);
                                            if (!product.FullDescription.ToLower().Contains("диаметр"))
                                                product.FullDescription += (product.FullDescription == string.Empty ? "" : "<br />") + string.Format("Диаметр - {0} см", diameter);
                                        }

                                        
                                        if (oldShortDescription != product.ShortDescription || oldFullDescription != product.FullDescription)
                                            UpdateProduct(connection, product);                                     
                                    }
                                }
                            }
                        }
                        catch (Exception exc)
                        {
                            LogManager.InsertLog(LogTypeEnum.AdministrationArea, string.Format("Error while sync with 1C. The line is '{0}'.", row), exc);
                        }
                    }
                }

                popClient.DeleteMessage(i);
                popClient.Disconnect();
            }
            NopCache.Clear();
        }