/// <summary>
        /// 获取发件人
        /// </summary>
        /// <param name="mailIndex"></param>
        /// <returns></returns>
        public override String GetSenderName(Int32 mailIndex)
        {
            // RfcMailAddress address = pop3Client.GetMessageHeaders(mailIndex).From;
            RfcMailAddress address = message.Headers.From;

            return(address.DisplayName);
        }
Пример #2
0
        /// <summary>
        /// Creates the sender.
        /// </summary>
        /// <param name="siteId">The site id.</param>
        /// <param name="mailAddress">The mail address.</param>
        /// <returns></returns>
        private tbl_Contact CreateSender(Guid siteId, RfcMailAddress mailAddress)
        {
            var contact = new tbl_Contact
            {
                ID            = Guid.NewGuid(),
                SiteID        = siteId,
                UserFullName  = mailAddress.DisplayName,
                Email         = mailAddress.Address,
                IsNameChecked = false,
                UserIP        = string.Empty,
                RefferURL     = string.Empty,
                StatusID      = _dataManager.Status.SelectDefault(siteId).ID
            };


            var nameChecker = new NameChecker(Settings.ADONetConnectionString);
            var nameCheck   = nameChecker.CheckName(contact.UserFullName, NameCheckerFormat.FIO, Correction.Correct);

            if (!string.IsNullOrEmpty(nameCheck))
            {
                contact.UserFullName  = nameCheck;
                contact.Surname       = nameChecker.Surname;
                contact.Name          = nameChecker.Name;
                contact.Patronymic    = nameChecker.Patronymic;
                contact.IsNameChecked = nameChecker.IsNameCorrect;
            }

            return(contact);
        }
Пример #3
0
        public void ParsingMailAddressList()
        {
            const string addressList = "\"John McDaniel\" <*****@*****.**>, [email protected], <*****@*****.**>";

            string[] expectedAddress          = { "*****@*****.**", "*****@*****.**", "*****@*****.**" };
            string[] expectedRaw              = { "\"John McDaniel\" <*****@*****.**>", "*****@*****.**", "<*****@*****.**>" };
            string[] expectedDisplay          = { "John McDaniel", "", "", "" };
            bool[]   expectedValidMailAddress = { true, true, true, true };
            List <RfcMailAddress> list        = RfcMailAddress.ParseMailAddresses(addressList);

            Assert.AreEqual(expectedAddress.Length, list.Count, "Number of items parsed");
            for (int i = 0; i < list.Count; i++)
            {
                Assert.IsTrue(list[i].HasValidMailAddress, string.Format("HasValidMailAddress: {0}", i));
                Assert.AreEqual(expectedAddress[i], list[i].MailAddress.Address, string.Format("Email Address: {0}", i));
                Assert.AreEqual(expectedDisplay[i], list[i].DisplayName);
                Assert.AreEqual(expectedRaw[i], list[i].Raw, string.Format("Email Raw: {0}", i));
                Assert.AreEqual(expectedValidMailAddress[i], list[i].HasValidMailAddress);
                if (expectedValidMailAddress[i])
                {
                    Assert.IsTrue(list[i].Address.Equals(list[i].MailAddress.Address));
                    Assert.IsTrue(list[i].DisplayName.Equals(list[i].MailAddress.DisplayName));
                }
            }
        }
Пример #4
0
        /// <summary>Returns the best defined first, last name from the email address.</summary>
        /// <param name="address">The email address to get the name from.</param>
        /// <returns>A dictionary with keys of 'first' and 'last'.</returns>
        private Dictionary <string, string> getFullNameFromAddress(RfcMailAddress address)
        {
            Dictionary <string, string> retNames = new Dictionary <string, string>();

            if (!string.IsNullOrWhiteSpace(address.DisplayName))
            {
                //Split the words..
                if (address.DisplayName.Contains(','))
                {
                    string[] names1 = address.DisplayName.Split(',');

                    retNames.Add("last", names1[0].Trim());
                    retNames.Add("first", names1[names1.Count() - 1].Trim());
                }
                else
                {
                    string[] names1 = address.DisplayName.Split(' ');

                    if (names1.Count() == 1)
                    {
                        retNames.Add("first", names1[0].Trim());
                        retNames.Add("last", "--");
                    }
                    else
                    {
                        retNames.Add("first", names1[0].Trim());
                        retNames.Add("last", names1[names1.Count() - 1].Trim());
                    }
                }
            }
            else
            {
                retNames.Add("last", "--");
                retNames.Add("first", "--");
            }

            //Trim the First and Last names, incase..
            if (retNames["first"].Length > 49)
            {
                retNames["first"] = retNames["first"].Substring(0, 49);
            }
            if (retNames["last"].Length > 49)
            {
                retNames["last"] = retNames["last"].Substring(0, 49);
            }
            if (string.IsNullOrWhiteSpace(retNames["first"].Trim()))
            {
                retNames["first"] = "--";
            }
            if (string.IsNullOrWhiteSpace(retNames["last"].Trim()))
            {
                retNames["last"] = "--";
            }

            return(retNames);
        }
Пример #5
0
        public void ParsingMailAddressNoBrackets()
        {
            const string address         = "*****@*****.**";
            const string expectedAddress = address;

            RfcMailAddress rfcAddress = RfcMailAddress.ParseMailAddress(address);

            Assert.IsTrue(rfcAddress.HasValidMailAddress);
            Assert.AreEqual(expectedAddress, rfcAddress.Address);
            Assert.AreEqual(expectedAddress, rfcAddress.MailAddress.Address);
            Assert.IsEmpty(rfcAddress.MailAddress.DisplayName);
        }
Пример #6
0
        public void LoginForm_PasswordRestoreWithValidEmail()
        {
            using (IWebDriver driver = new FirefoxDriver())
            {
                driver.Navigate().GoToUrl(gg);

                //Открытие формы
                IWebElement formLink = driver.FindElement(By.XPath(@"//*[@id=""top_back""]/div[3]/a[1]"));
                formLink.Click();

                WebDriverWait wait        = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
                IWebElement   overlay     = driver.FindElement(By.Id("cboxOverlay"));
                IWebElement   colorbox    = driver.FindElement(By.Id("colorbox"));
                IWebElement   messageBox  = driver.FindElement(By.ClassName("status-error"));
                IWebElement   emailField  = wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("Email")));
                IWebElement   restoreLink = wait.Until(ExpectedConditions.ElementToBeClickable(By.LinkText("Я не помню пароль")));

                Assert.IsTrue(colorbox.Displayed, "Форма не открылась");

                emailField.SendKeys(validEmail);
                restoreLink.Click();
                try { wait.Until(ExpectedConditions.TextToBePresentInElementLocated(By.ClassName("status-message"), "Инструкция по восстановлению отправлена")); }
                catch (Exception e) { Assert.Fail("Не появилось сообщение об отправке письма"); }
            }
            using (Pop3Client client = new Pop3Client())
            {
                client.Connect(hostname, port, useSsl);
                client.Authenticate(validEmail, emailPass);

                int messageNumber = client.GetMessageCount();
                int i             = 0;
                while (messageNumber == 0 && i < 60)
                {
                    client.Disconnect();
                    System.Threading.Thread.Sleep(5000);
                    client.Connect(hostname, port, useSsl);
                    client.Authenticate(validEmail, emailPass);
                    messageNumber = client.GetMessageCount();
                    i             = i++;
                }

                Assert.IsTrue(messageNumber > 0, "Письмо не пришло");

                MessageHeader  headers = client.GetMessageHeaders(messageNumber);
                RfcMailAddress from    = headers.From;
                string         subject = headers.Subject;
                client.DeleteAllMessages();

                Assert.IsFalse(from.HasValidMailAddress && from.Address.Equals("*****@*****.**") && "Восстановление пароля на Gama - Gama".Equals(subject), "Письмо не пришло");
            }
        }
Пример #7
0
        public void ParsingMailAddressListDisplayNameHasComma()
        {
            const string          address             = "\"McDaniel, John\" <*****@*****.**>";
            const string          expectedRaw         = address;
            const string          expectedMailAddress = "*****@*****.**";
            const string          expectedMailName    = "McDaniel, John";
            List <RfcMailAddress> list = RfcMailAddress.ParseMailAddresses(address);

            Assert.AreEqual(1, list.Count, "Number of items parsed");
            Assert.IsTrue(list[0].HasValidMailAddress);
            Assert.AreEqual(expectedRaw, list[0].Raw, "Raw input");
            Assert.AreEqual(expectedMailAddress, list[0].MailAddress.Address, "MailAddress");
            Assert.AreEqual(expectedMailName, list[0].MailAddress.DisplayName, "MailAddress Display Name");
        }
Пример #8
0
        public void ParsingMailAddressNameOnly()
        {
            const string address             = "Ralph Wiggins";
            const string expectedDisplayName = address;
            const string expectedRaw         = address;

            RfcMailAddress rfcAddress = RfcMailAddress.ParseMailAddress(address);

            Assert.AreEqual(expectedRaw, rfcAddress.Raw);
            Assert.AreEqual(expectedDisplayName, rfcAddress.DisplayName);
            Assert.IsEmpty(rfcAddress.Address);

            // We should not be able to parse this into a MailAddress object
            Assert.IsFalse(rfcAddress.HasValidMailAddress);
            Assert.IsNull(rfcAddress.MailAddress);
        }
        public static void HeadersFromAndSubject(string hostname, int port, bool useSsl, string username, string password)
        {
            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                log.Info("Try to connect server...");
                client.Connect(hostname, port, useSsl);  // Connect to the server
                client.Authenticate(username, password); // Authenticate ourselves towards the server
                log.Info("Server connected.");
                // We want to check the headers of the message before we download the full message
                int messageCount = client.GetMessageCount();
                log.Info($"You have {messageCount} messages.");
                int messageNumber;
                for (messageNumber = 1; messageNumber <= messageCount; messageNumber++)
                {
                    MessageHeader  headers = client.GetMessageHeaders(messageNumber);
                    RfcMailAddress from    = headers.From;
                    string         subject = headers.Subject;

                    // Only want to download message if: is from [email protected] and has subject "Some subject"
                    if (from.HasValidMailAddress && from.Address.Equals("*****@*****.**") && ("a".Equals(subject) || "b".Equals(subject)))
                    {
                        log.Info($"The subject you are looking for is: {subject}");
                        // Download the full message
                        Message message = client.GetMessage(messageNumber);
                        log.Info($"The message sent date is: {message.Headers.DateSent}");
                        if (message.Headers.DateSent >= DateTime.Today)
                        {
                            log.Info("Try to get the mail...");
                            foreach (MessagePart attachment in message.FindAllAttachments())
                            {
                                if (attachment.FileName.Equals("c.zip"))
                                {
                                    // Save the raw bytes to a file
                                    var oldfilename = attachment.FileName;
                                    var newfilename = oldfilename.Substring(0, oldfilename.Length - 4) + "_" + DateTime.Now.ToString("yyyyMMdd") + ".zip";
                                    File.WriteAllBytes(newfilename, attachment.Body);
                                }
                            }
                            log.Info("Done.");
                        }
                    }
                }
            }
        }
Пример #10
0
        public void ParsingMailAddressFull()
        {
            const string address             = "\"John McDaniel\" <*****@*****.**>";
            const string expectedRaw         = address;
            const string expectedMailAddress = "*****@*****.**";
            const string expectedDisplayName = "John McDaniel";

            RfcMailAddress rfcAddress = RfcMailAddress.ParseMailAddress(address);

            Assert.AreEqual(expectedRaw, rfcAddress.Raw);
            Assert.IsTrue(rfcAddress.HasValidMailAddress);
            Assert.AreEqual(expectedMailAddress, rfcAddress.MailAddress.Address);
            Assert.AreEqual(expectedDisplayName, rfcAddress.MailAddress.DisplayName);

            // The address and displayname should be equal
            Assert.IsTrue(rfcAddress.Address.Equals(rfcAddress.MailAddress.Address));
            Assert.IsTrue(rfcAddress.DisplayName.Equals(rfcAddress.MailAddress.DisplayName));
        }
Пример #11
0
        public Dictionary <int, string> Pop3(int messageNr)
        {
            Dictionary <int, string> headers = new Dictionary <int, string>();

            using (Pop3Client client = new Pop3Client())
            {
                client.Connect("pop.gmail.com", 995, true);
                client.Authenticate(MailAddress, Password);
                for (int i = 1; i <= messageNr; i++)
                {
                    var            header  = client.GetMessageHeaders(i);
                    RfcMailAddress from    = header.From;
                    string         subject = header.Subject;
                    headers.Add(i, " Subject: " + header.Subject + "\n From: " + header.From + "\n DateSent: " + header.DateSent);
                }
            }

            return(headers);
        }
Пример #12
0
        /// <summary>
        /// Example showing:
        ///  - how to fetch only headers from a POP3 server
        ///  - how to examine some of the headers
        ///  - how to fetch a full message
        ///  - how to find a specific attachment and save it to a file
        /// </summary>
        /// <param name="hostname">Hostname of the server. For example: pop3.live.com</param>
        /// <param name="port">Host port to connect to. Normally: 110 for plain POP3, 995 for SSL POP3</param>
        /// <param name="useSsl">Whether or not to use SSL to connect to server</param>
        /// <param name="username">Username of the user on the server</param>
        /// <param name="password">Password of the user on the server</param>
        /// <param name="messageNumber">
        /// The number of the message to examine.
        /// Must be in range [1, messageCount] where messageCount is the number of messages on the server.
        /// </param>
        public static void HeadersFromAndSubject(string hostname, int port, bool useSsl, string username, string password, int messageNumber)
        {
            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client()) {
                // Connect to the server
                client.Connect(hostname, port, useSsl);

                // Authenticate ourselves towards the server
                client.Authenticate(username, password);

                // We want to check the headers of the message before we download
                // the full message
                MessageHeader headers = client.GetMessageHeaders(messageNumber);

                RfcMailAddress from    = headers.From;
                string         subject = headers.Subject;

                // Only want to download message if:
                //  - is from [email protected]
                //  - has subject "Some subject"
                if (from.HasValidMailAddress && from.Address.Equals("*****@*****.**") && "Some subject".Equals(subject))
                {
                    // Download the full message
                    Message message = client.GetMessage(messageNumber);

                    // We know the message contains an attachment with the name "useful.pdf".
                    // We want to save this to a file with the same name
                    foreach (MessagePart attachment in message.FindAllAttachments())
                    {
                        if (attachment.FileName.Equals("useful.pdf"))
                        {
                            //TODO: gelen dosyanın boyutuna göre, task oluşturduktan sonra o task'a ait tabloya güncelleme yap.
                            //long byteSize = attachment.Body.Length;

                            // Save the raw bytes to a file
                            File.WriteAllBytes(attachment.FileName, attachment.Body);
                        }
                    }
                }
            }
        }
Пример #13
0
        /// <summary>
        /// ищет письмо с нужной темой
        /// </summary>
        /// <param name="userEmail">email на который стучимся</param>
        /// <param name="Subject">Тема письма, которое нужно прочитать</param>
        /// <param name="Password">Пароль</param>
        /// <returns></returns>
        public static bool GetYandexTextTheme(string userEmail, string Subject, string Password)
        {
            Pop3Client client = new Pop3Client();

            client.Connect("pop.yandex.ru", 995, true);
            client.Authenticate(userEmail.Substring(0, userEmail.IndexOf("@")), Password);

            int messageCount = client.GetMessageCount();

            for (Int32 i = 1; i <= messageCount; i++)
            {
                MessageHeader  headers = client.GetMessageHeaders(i);
                RfcMailAddress from    = headers.From;
                string         subject = headers.Subject;
                //проверяем тему письма, если та что нам надо, добавляем письмо в список писем
                if (subject == Subject)
                {
                    return(true);
                }
            }
            return(false);
        }
Пример #14
0
        /// <summary>
        /// POP3 monitoring processing of returns from filter check.
        /// </summary>
        /// <param name="from">From.</param>
        /// <param name="messageText">The message text.</param>
        /// <returns></returns>
        private bool POP3MonitoringProcessingOfReturnsFromFilterCheck(RfcMailAddress from, string messageText)
        {
            var criteria            = Settings.POP3MonitoringProcessingOfReturnsFromFilter.Split(',').Select(p => p.Trim()).ToList();
            var messageTextCriteria = Settings.POP3MonitoringProcessingOfReturnsBodyFilter.Split(',').Select(p => p.Trim()).ToList();

            if (criteria.Where(p => from.Address.ToLower().Contains(p.ToLower())).FirstOrDefault() != null)
            {
                return(true);
            }

            if (criteria.Where(p => from.DisplayName.ToLower().Contains(p.ToLower())).FirstOrDefault() != null)
            {
                return(true);
            }

            if (messageTextCriteria.Where(p => messageText.ToLower().Contains(p.ToLower())).FirstOrDefault() != null)
            {
                return(true);
            }

            return(false);
        }
Пример #15
0
 /// <summary>
 /// Load every mail from client in MailItems
 /// </summary>
 /// <returns>A list off MailItems</returns>
 public string[][] Load_Mail_List()
 {
     if (IsConnected)
     {
         dispatcherTimer.Stop();
         Thread.Sleep(0500);
         try{
             int        messageCount = client.GetMessageCount();
             string[][] All_Mails    = new string[messageCount][];
             for (int i = messageCount; i > 0; i--)
             {
                 MessageHeader  headers = client.GetMessageHeaders(i);
                 RfcMailAddress from    = headers.From;
                 string[]       Mail    = new string[4];
                 Mail[0] = headers.MessageId;
                 if (!String.IsNullOrEmpty(from.DisplayName))
                 {
                     Mail[1] = from.DisplayName;
                 }
                 else
                 {
                     Mail[1] = from.Address;
                 }
                 Mail[2] = headers.DateSent.Day.ToString("D2") + "/" + headers.DateSent.Month.ToString("D2") + " " + headers.DateSent.Year.ToString("D4") + " " + headers.DateSent.Hour.ToString("D2") + ":" + headers.DateSent.Minute.ToString("D2") + ":" + headers.DateSent.Second.ToString("D2");
                 Mail[3] = headers.Subject;
                 All_Mails[messageCount - i] = Mail;
             }
             return(All_Mails);
         }
         catch {
             // mail receiving error
             MessageBox.Show("Mail receiving error.", "error");
         }
         dispatcherTimer.Start();
     }
     return(null);
 }
Пример #16
0
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            string[] words = login.Split(new char[] { '@' });
            string   pop3  = "pop." + words[1];

            using (Pop3Client client = new Pop3Client())
            {
                client.Connect(pop3, 995, true);
                client.Authenticate(login, pass);
                int messageCount = client.GetMessageCount();

                MaxCountMeail = messageCount;

                for (int i = messageCount; i > 0; i--)
                {
                    NowCountMails = (messageCount - i) + 1;
                    System.Threading.Thread.Sleep(10);
                    if (worker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }
                    int            z       = (messageCount - i) / messageCount * 100;
                    MessageHeader  headers = client.GetMessageHeaders(i);
                    RfcMailAddress from    = headers.From;
                    string[]       buf     = new string[3];
                    buf[1] = headers.Subject;
                    buf[0] = from.Address;
                    buf[2] = headers.Date;
                    listEmal.Add(buf);
                    // frr.listBox1.Items.Add("Отправитель: " + from.Address + " Тема: " + HeadersFromAndSubject(pop3, 995, true, login, pass, i));
                    //    myDelegat deli = new myDelegat(progressLoad);
                    //  PBarr.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, deli, z);
                }
            }
        }
Пример #17
0
        public void TestSpaceInBase64HeaderValue()
        {
            string base64Header = "Disposition-Notification-To: =?windows-1251?B?ZWFzdXJlLg\r\n"
                                  + " ==?=\r\n"
                                  + "\t<*****@*****.**>\r\n"
            ;

            string expectedName    = "easure.";
            string expectedAddress = "*****@*****.**";

            NameValueCollection col = HeaderExtractor.ExtractHeaders(base64Header);

            Assert.AreEqual(1, col.Count);

            MessageHeader header = new MessageHeader(col);

            Assert.AreEqual(1, header.DispositionNotificationTo.Count);

            RfcMailAddress address = header.DispositionNotificationTo[0];

            Assert.IsNotNull(address.MailAddress);
            Assert.AreEqual(expectedName, address.MailAddress.DisplayName);
            Assert.AreEqual(expectedAddress, address.MailAddress.Address);
        }
Пример #18
0
        /// <summary>
        /// 获取发件人
        /// </summary>
        /// <param name="mailIndex"></param>
        /// <returns></returns>
        public override String GetSendMialAddress(Int32 mailIndex)
        {
            RfcMailAddress address = pop3Client.GetMessageHeaders(mailIndex).From;

            return(address.Address);
        }
Пример #19
0
        public void FetchBalanceMessage()
        {
            while (true)
            {
                int messageCount = 0;

                List <BalanceMessage> listBalanceMessage = new List <BalanceMessage>();
                Pop3Client            client             = new Pop3Client();
                try
                {
                    client.Connect(hostname, port, useSsl);
                    client.Authenticate(username, password);

                    messageCount = client.GetMessageCount();

                    for (int i = 1; i <= messageCount; i++)
                    {
                        MessageHeader  headers = client.GetMessageHeaders(i);
                        RfcMailAddress from    = headers.From;
                        if (from.HasValidMailAddress && from.Address.Contains("*****@*****.**"))
                        {
                            DateTime date    = Convert.ToDateTime(headers.Date);
                            Message  message = client.GetMessage(i);
                            //MessagePart plainText = message.FindFirstPlainTextVersion();

                            BalanceMessage bMessage = new BalanceMessage();
                            bMessage.date = date;
                            bMessage.text = message.MessagePart.GetBodyAsText();

                            Regex           regex   = new Regex(@"\d\.\d+");
                            MatchCollection matches = regex.Matches(bMessage.text);

                            try
                            {
                                NumberFormatInfo provider = new NumberFormatInfo();
                                provider.NumberDecimalSeparator = ".";
                                double amount = Convert.ToDouble(matches[0].Value, provider);
                                bMessage.amount = amount;

                                //Console.WriteLine(bMessage.date + " : " + bMessage.amount);
                                listBalanceMessage.Add(bMessage);
                                client.DeleteMessage(i);
                            }
                            catch (Exception ex)
                            {
                                //Console.WriteLine(ex.Message);
                                if (_del != null)
                                {
                                    _del(this.GetType().ToString() + " : " + System.Reflection.MethodBase.GetCurrentMethod().Name + ex.Message);
                                }
                                break;
                            }
                        }
                    }
                    client.Disconnect();
                }
                catch (Exception ex)
                {
                    //Console.WriteLine(ex.Message);
                    if (_del != null)
                    {
                        _del(this.GetType().ToString() + " : " + System.Reflection.MethodBase.GetCurrentMethod().Name + ex.Message);
                    }
                }
                client.Dispose();

                SaveTxt(listBalanceMessage);

                Thread.Sleep(1000 * 60 * 60);
            }
        }
Пример #20
0
        private void LoadMassagesInDb(Message message, Pop3Client client, int i_msg)
        {
            string[] separator = new string[] { "\r\n", "\n" };

            MessageHeader  headers = client.GetMessageHeaders(i_msg);
            RfcMailAddress from    = headers.From;


            if (from.HasValidMailAddress && from.Address.Equals(this.mail_ppu))
            {
                if (message.Headers.Subject.Contains("_TEST"))
                {
                    Debug.WriteLine("MAIL_TS");
                    var mail_strings =
                        message.FindFirstPlainTextVersion()
                        .GetBodyAsText()
                        .Split(separator, StringSplitOptions.RemoveEmptyEntries)
                        .Select(s => s.Split(new[] { '=' }));

                    Dictionary <string, string> dict = new Dictionary <string, string>();
                    foreach (var item in mail_strings)
                    {
                        dict.Add(item[0], item[1]);
                    }

                    using (var context = new db_sqlceEntities())
                    {
                        try
                        {
                            var package_ts = new package_ts()
                            {
                                pt            = "/home/ts",
                                na            = dict["na"],
                                r1            = Convert.ToInt32(dict["r1"]),
                                r2            = Convert.ToInt32(dict["r2"]),
                                pw1           = Convert.ToInt32(dict["pw1"]),
                                pw2           = Convert.ToInt32(dict["pw2"]),
                                gp            = Convert.ToInt32(dict["gp"]),
                                te            = Convert.ToInt32(dict["te"]),
                                vc            = Convert.ToInt32(dict["vc"]),
                                vg            = Convert.ToInt32(dict["vg"]),
                                ti            = Convert.ToInt32(dict["ti"]),
                                sn1           = dict["sn1"],
                                sn2           = dict["sn2"],
                                mail_uid      = client.GetMessageUid(i_msg),
                                ismail        = true,
                                da            = DateTime.ParseExact(dict["da"], "yyMMdd", null).Date,
                                date_time_inc = DateTime.Now
                            };
                            context.package_ts.Add(package_ts);
                            context.SaveChanges();
                        }

                        catch (DbEntityValidationException ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                    log.Write(message.FindFirstPlainTextVersion()
                              .GetBodyAsText());
                }

                if (message.Headers.Subject.Contains("_TM"))
                {
                    Debug.WriteLine("MAIL_TM");
                    var mail_strings =
                        message.FindFirstPlainTextVersion()
                        .GetBodyAsText()
                        .Split(separator, StringSplitOptions.RemoveEmptyEntries)
                        .Select(s => s.Split(new[] { '=' }));

                    Dictionary <string, string> dict = new Dictionary <string, string>();
                    foreach (var item in mail_strings)
                    {
                        dict.Add(item[0], item[1]);
                    }

                    using (var context = new db_sqlceEntities())
                    {
                        try
                        {
                            var package_tm = new package_tm()
                            {
                                pt       = "/home/tm",
                                na       = dict["na"],
                                ismail   = true,
                                mail_uid = client.GetMessageUid(i_msg),
                                date_inc = DateTime.Now
                            };
                            context.package_tm.Add(package_tm);
                            context.SaveChanges();
                        }

                        catch (DbEntityValidationException ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                }

                if (message.Headers.Subject.Contains("_ON"))
                {
                    Debug.WriteLine("MAIL_ON");

                    var mail_strings =
                        message.FindFirstPlainTextVersion()
                        .GetBodyAsText()
                        .Trim()
                        .Split(separator, StringSplitOptions.RemoveEmptyEntries)
                        .Select(s => s.Split(new[] { '=' }));

                    Dictionary <string, string> dict = new Dictionary <string, string>();
                    foreach (var item in mail_strings)
                    {
                        dict.Add(item[0], item[1]);
                    }

                    using (var context = new db_sqlceEntities())
                    {
                        try
                        {
                            var package_on = new package_on()
                            {
                                pt            = "/home/on",
                                na            = dict["na"],
                                r1            = Convert.ToInt32(dict["r1"]),
                                r2            = Convert.ToInt32(dict["r2"]),
                                pw1           = Convert.ToInt32(dict["pw1"]),
                                pw2           = Convert.ToInt32(dict["pw2"]),
                                gp            = Convert.ToInt32(dict["gp"]),
                                te            = Convert.ToInt32(dict["te"]),
                                vc            = Convert.ToInt32(dict["vc"]),
                                vg            = Convert.ToInt32(dict["vg"]),
                                ti            = Convert.ToInt32(dict["ti"]),
                                sn1           = dict["sn1"],
                                sn2           = dict["sn2"],
                                mail_uid      = client.GetMessageUid(i_msg),
                                ismail        = true,
                                da            = DateTime.ParseExact(dict["da"], "yyMMdd", null).Date,
                                date_time_inc = DateTime.Now
                            };
                            context.package_on.Add(package_on);
                            context.SaveChanges();
                        }

                        catch (DbEntityValidationException ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                    log.Write(message.FindFirstPlainTextVersion()
                              .GetBodyAsText());
                }

                if (message.Headers.Subject.Contains("_AL"))
                {
                    Debug.WriteLine("MAIL_AL");
                    var mail_strings =
                        message.FindFirstPlainTextVersion()
                        .GetBodyAsText()
                        .Split(separator, StringSplitOptions.RemoveEmptyEntries)
                        .Select(s => s.Split(new[] { '=' }));

                    Dictionary <string, string> dict = new Dictionary <string, string>();
                    foreach (var item in mail_strings)
                    {
                        dict.Add(item[0], item[1]);
                    }

                    var wr_txt = "";
                    var war    = Convert.ToInt32(dict["w"]);
                    switch (war)
                    {
                    case (0):
                        wr_txt = "Вскрыте крышки!";
                        break;

                    case (1):
                        wr_txt = "Расход за час для первого счетчика больше предельного!";
                        break;

                    case (2):
                        wr_txt = "Расход за час для второго счетчика больше предельного!";
                        break;
                    }

                    using (var context = new db_sqlceEntities())
                    {
                        try
                        {
                            var package_al = new package_al()
                            {
                                pt       = "/home/wr",
                                na       = dict["na"],
                                wr       = war,
                                date_inc = DateTime.Now,
                                ismail   = true,
                                mail_uid = client.GetMessageUid(i_msg),
                                wr_txt   = wr_txt
                            };
                            context.package_al.Add(package_al);
                            context.SaveChanges();
                        }

                        catch (DbEntityValidationException ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                }

                if (message.Headers.Subject.Contains("_Data"))
                {
                    Debug.WriteLine("MAIL_IZ");
                    var mail_strings =
                        message.FindFirstPlainTextVersion()
                        .GetBodyAsText()
                        .Trim()
                        .Split(separator, StringSplitOptions.RemoveEmptyEntries)
                        .Select(s => s.Split(new[] { '=' }));
                    Dictionary <string, string> dict = mail_strings.ToDictionary(item => item[0], item => item[1]);



                    using (var context = new db_sqlceEntities())
                    {
                        try
                        {
                            string rw_1 = dict["r1"].Substring(0, 8);
                            string rw_2 = dict["r2"].Substring(0, 8);

                            string r1 = dict["r1"].Substring(8, 96);
                            string r2 = dict["r2"].Substring(8, 96);

                            // r1 = r1.Replace('g', '0');
                            // r2 = r2.Replace('g', '0');



                            r1 = Regex.Replace(r1, @"([^0-9])(\d){3}", "0000");
                            r2 = Regex.Replace(r2, @"([^0-9])(\d){3}", "0000");
                            IEnumerable <string> groups1 = Enumerable.Range(0, r1.Length / 4)
                                                           .Select(i => r1.Substring(i * 4, 4));
                            List <int> rw1 = new List <int>();
                            foreach (var grp in groups1)
                            {
                                rw1.Add(Convert.ToInt32(grp));
                            }

                            IEnumerable <string> groups2 = Enumerable.Range(0, r2.Length / 4)
                                                           .Select(i => r2.Substring(i * 4, 4));
                            List <int> rw2 = new List <int>();
                            foreach (var grp in groups2)
                            {
                                rw2.Add(Convert.ToInt32(grp));
                            }

                            string ppu_na = null;
                            if (!string.IsNullOrEmpty(dict["na"]))
                            {
                                ppu_na = dict["na"];
                            }
                            var package_iz = new package_iz()
                            {
                                pt    = "/home/iz",
                                na    = dict["na"],
                                r1    = Convert.ToInt32(rw_1),
                                r1_0  = Convert.ToInt32(groups1.ElementAt(0)),
                                r1_1  = Convert.ToInt32(groups1.ElementAt(1)),
                                r1_2  = Convert.ToInt32(groups1.ElementAt(2)),
                                r1_3  = Convert.ToInt32(groups1.ElementAt(3)),
                                r1_4  = Convert.ToInt32(groups1.ElementAt(4)),
                                r1_5  = Convert.ToInt32(groups1.ElementAt(5)),
                                r1_6  = Convert.ToInt32(groups1.ElementAt(6)),
                                r1_7  = Convert.ToInt32(groups1.ElementAt(7)),
                                r1_8  = Convert.ToInt32(groups1.ElementAt(8)),
                                r1_9  = Convert.ToInt32(groups1.ElementAt(9)),
                                r1_10 = Convert.ToInt32(groups1.ElementAt(10)),
                                r1_11 = Convert.ToInt32(groups1.ElementAt(11)),
                                r1_12 = Convert.ToInt32(groups1.ElementAt(12)),
                                r1_13 = Convert.ToInt32(groups1.ElementAt(13)),
                                r1_14 = Convert.ToInt32(groups1.ElementAt(14)),
                                r1_15 = Convert.ToInt32(groups1.ElementAt(15)),
                                r1_16 = Convert.ToInt32(groups1.ElementAt(16)),
                                r1_17 = Convert.ToInt32(groups1.ElementAt(17)),
                                r1_18 = Convert.ToInt32(groups1.ElementAt(18)),
                                r1_19 = Convert.ToInt32(groups1.ElementAt(19)),
                                r1_20 = Convert.ToInt32(groups1.ElementAt(20)),
                                r1_21 = Convert.ToInt32(groups1.ElementAt(21)),
                                r1_22 = Convert.ToInt32(groups1.ElementAt(22)),
                                r1_23 = Convert.ToInt32(groups1.ElementAt(23)),
                                // r1_24 = Convert.ToInt32(groups1.ElementAt(24)),

                                r2    = Convert.ToInt32(rw_2),
                                r2_0  = Convert.ToInt32(groups2.ElementAt(0)),
                                r2_1  = Convert.ToInt32(groups2.ElementAt(1)),
                                r2_2  = Convert.ToInt32(groups2.ElementAt(2)),
                                r2_3  = Convert.ToInt32(groups2.ElementAt(3)),
                                r2_4  = Convert.ToInt32(groups2.ElementAt(4)),
                                r2_5  = Convert.ToInt32(groups2.ElementAt(5)),
                                r2_6  = Convert.ToInt32(groups2.ElementAt(6)),
                                r2_7  = Convert.ToInt32(groups2.ElementAt(7)),
                                r2_8  = Convert.ToInt32(groups2.ElementAt(8)),
                                r2_9  = Convert.ToInt32(groups2.ElementAt(9)),
                                r2_10 = Convert.ToInt32(groups2.ElementAt(10)),
                                r2_11 = Convert.ToInt32(groups2.ElementAt(11)),
                                r2_12 = Convert.ToInt32(groups2.ElementAt(12)),
                                r2_13 = Convert.ToInt32(groups2.ElementAt(13)),
                                r2_14 = Convert.ToInt32(groups2.ElementAt(14)),
                                r2_15 = Convert.ToInt32(groups2.ElementAt(15)),
                                r2_16 = Convert.ToInt32(groups2.ElementAt(16)),
                                r2_17 = Convert.ToInt32(groups2.ElementAt(17)),
                                r2_18 = Convert.ToInt32(groups2.ElementAt(18)),
                                r2_19 = Convert.ToInt32(groups2.ElementAt(19)),
                                r2_20 = Convert.ToInt32(groups2.ElementAt(20)),
                                r2_21 = Convert.ToInt32(groups2.ElementAt(21)),
                                r2_22 = Convert.ToInt32(groups2.ElementAt(22)),
                                r2_23 = Convert.ToInt32(groups2.ElementAt(23)),
                                //r2_24 = Convert.ToInt32(groups2.ElementAt(24)),

                                pw1      = Convert.ToInt32(dict["pw1"]),
                                pw2      = Convert.ToInt32(dict["pw2"]),
                                gp       = Convert.ToInt32(dict["gp"]),
                                te       = dict["te"],
                                vc       = Convert.ToInt32(dict["vc"]),
                                vg       = Convert.ToInt32(dict["vg"]),
                                ti       = Convert.ToInt32(dict["ti"]),
                                sn1      = dict["sn1"],
                                sn2      = dict["sn2"],
                                da       = DateTime.ParseExact(dict["da"], "yyMMdd", null).Date,
                                ismail   = true,
                                mail_uid = client.GetMessageUid(i_msg),
                                date_inc = DateTime.Now
                            };
                            context.package_iz.Add(package_iz);
                            context.SaveChanges();

                            var qu = context.counters.FirstOrDefault(c => c.serial_amspi == ppu_na);

                            if (qu != null)
                            {
                                qu.serial_r1 = dict["sn1"];
                                qu.serial_r2 = dict["sn2"];
                                context.SaveChanges();
                            }
                        }

                        catch (DbEntityValidationException ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                    log.Write(message.FindFirstPlainTextVersion()
                              .GetBodyAsText());
                }
            }
        }