public static void Run()
        {
            //ExStart:SaveToDiskWithoutParsing
            // The path to the File directory.
            string dataDir = RunExamples.GetDataDir_POP3();
            string dstEmail = dataDir + "InsertHeaders.eml";

            // Create an instance of the Pop3Client class
            Pop3Client client = new Pop3Client();

            // Specify host, username, password, Port and SecurityOptions for your client
            client.Host = "pop.gmail.com";
            client.Username = "******";
            client.Password = "******";
            client.Port = 995;
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                // Save message to disk by message sequence number
                client.SaveMessage(1, dstEmail);
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine(Environment.NewLine + "Retrieved email messages using POP3 ");
            //ExEnd:SaveToDiskWithoutParsing
        }
        public static void Run()
        {
            // ExStart:ParseMessageAndSave
            // The path to the File directory.
            string dataDir = RunExamples.GetDataDir_POP3();

            // Create an instance of the Pop3Client class
            Pop3Client client = new Pop3Client();

            // Specify host, username and password, Port and SecurityOptions for your client
            client.Host            = "pop.gmail.com";
            client.Username        = "******";
            client.Password        = "******";
            client.Port            = 995;
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                // Fetch the message by its sequence number and Save the message using its subject as the file name
                MailMessage msg = client.FetchMessage(1);
                msg.Save(dataDir + "first-message_out.eml", SaveOptions.DefaultEml);
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(Environment.NewLine + ex.Message);
            }
            finally
            {
                client.Dispose();
            }
            // ExEnd:ParseMessageAndSave
            Console.WriteLine(Environment.NewLine + "Downloaded email using POP3. Message saved at " + dataDir + "first-message_out.eml");
        }
        public static void Run()
        {
            // ExStart:ParseMessageAndSave
            // The path to the File directory.
            string dataDir = RunExamples.GetDataDir_POP3();

            // Create an instance of the Pop3Client class
            Pop3Client client = new Pop3Client();

            // Specify host, username and password, Port and SecurityOptions for your client
            client.Host = "pop.gmail.com";
            client.Username = "******";
            client.Password = "******";
            client.Port = 995;
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                // Fetch the message by its sequence number and Save the message using its subject as the file name
                MailMessage msg = client.FetchMessage(1);
                msg.Save(dataDir + "first-message_out.eml", SaveOptions.DefaultEml);
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(Environment.NewLine + ex.Message);
            }
            finally
            {
                client.Dispose();
            }
            // ExEnd:ParseMessageAndSave
            Console.WriteLine(Environment.NewLine + "Downloaded email using POP3. Message saved at " + dataDir + "first-message_out.eml");
        }
Пример #4
0
        public static void ParseMailData(object data)
        {
            ParseData  d      = (ParseData)data;
            Pop3Client client = new Pop3Client();

            client.Connect("pop.mail.ru", 995, true);
            client.Authenticate(d.AccountLogin, d.AccountPass);
            Utils.WriteLog($"Клиент {d.ThreadID} подключился к {d.AccountLogin}", Form1.LogControl);

            for (int i = d.ThreadID; i < d.MessageCount; i += THREADS_COUNT)
            {
                try
                {
                    var msg = client.GetMessage(i + 1);
                    d.Messages.Add(msg);

                    Utils.WriteLog($"Parsing message # {++MessagesParsed} of {d.MessageCount} ...", Form1.LogControl);
                }
                catch (Exception ex)
                {
                    Utils.WriteLog($"Couldn't download message №{i + 1}", Form1.LogControl);
                    Utils.WriteLog($"[Error] {ex.Message}", Form1.LogControl);
                }
            }

            client.Disconnect();
            client.Dispose();
            Utils.WriteLog($"Клиент {d.ThreadID} отключился от {d.AccountLogin}", Form1.LogControl);
            Threads[d.ThreadID].Abort();
        }
Пример #5
0
        public static void DeleteMessage(int messageNumber)
        {
            try
            {
                using (Pop3Client client = new Pop3Client())
                {
                    // Connect to the server
                    client.Connect(hostname, port, useSsl);

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

                    // Mark the message as deleted
                    // Notice that it is only MARKED as deleted
                    // POP3 requires you to "commit" the changes
                    // which is done by sending a QUIT command to the server
                    // You can also reset all marked messages, by sending a RSET command.
                    client.DeleteMessage(messageNumber);

                    // When a QUIT command is sent to the server, the connection between them are closed.
                    // When the client is disposed, the QUIT command will be sent to the server
                    // just as if you had called the Disconnect method yourself.
                    client.Dispose();
                }
                return;
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                throw;
            }
        }
        public static void Run()
        {
            //ExStart:SaveToDiskWithoutParsing
            // The path to the File directory.
            string dataDir  = RunExamples.GetDataDir_POP3();
            string dstEmail = dataDir + "InsertHeaders.eml";

            // Create an instance of the Pop3Client class
            Pop3Client client = new Pop3Client();

            // Specify host, username, password, Port and SecurityOptions for your client
            client.Host            = "pop.gmail.com";
            client.Username        = "******";
            client.Password        = "******";
            client.Port            = 995;
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                // Save message to disk by message sequence number
                client.SaveMessage(1, dstEmail);
                client.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine(Environment.NewLine + "Retrieved email messages using POP3 ");
            //ExEnd:SaveToDiskWithoutParsing
        }
Пример #7
0
        public List <PopMessage> FetchMessages(int count)
        {
            List <PopMessage> result = new List <PopMessage>();

            for (int i = 1; i <= count; i++)
            {
                // The client disconnects from the server when being disposed
                using (Pop3Client client = new Pop3Client())
                {
                    try
                    {
                        // Connect to the server
                        client.Connect(_hostname, _port, _useSsl);

                        // Authenticate ourselves towards the server
                        client.Authenticate(_username, _password, AuthenticationMethod.UsernameAndPassword);

                        result.Add(new PopMessage(client.GetMessage(i)));
                    }
                    catch
                    {
                    }
                    finally
                    {
                        client.Dispose();
                    }
                }
            }

            return(result);
        }
        public static void Run()
        {
            // ExStart:RetrievingEmailHeaders
            // Create an instance of the Pop3Client class
            Pop3Client client = new Pop3Client();

            // Specify host, username. password, Port and SecurityOptions for your client
            client.Host            = "pop.gmail.com";
            client.Username        = "******";
            client.Password        = "******";
            client.Port            = 995;
            client.SecurityOptions = SecurityOptions.Auto;
            try
            {
                HeaderCollection headers = client.GetMessageHeaders(1);
                for (int i = 0; i < headers.Count; i++)
                {
                    // Display key and value in the header collection
                    Console.Write(headers.Keys[i]);
                    Console.Write(" : ");
                    Console.WriteLine(headers.Get(i));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                client.Dispose();
            }
            // ExEnd:RetrievingEmailHeaders
            Console.WriteLine(Environment.NewLine + "Displayed header information from emails using POP3 ");
        }
Пример #9
0
    public static List <string> ReceiveMailSubject()
    {
        var RFIDStrings = new List <string>();
        var pop         = new Pop3Client
        {
            Host      = ConfigurationManager.AppSettings["host"],
            Username  = ConfigurationManager.AppSettings["Username"],
            Password  = ConfigurationManager.AppSettings["Password"],
            Port      = Int32.Parse(ConfigurationManager.AppSettings["Port"]),
            EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSSL"])
        };

        try
        {
            pop.Connect();
            int messageCount = pop.GetMessageCount();
            Console.WriteLine("Subject added to list:");
            for (int i = 1; i <= messageCount; i++)
            {
                MailMessage message = pop.GetMessage(i);
                Console.WriteLine($"{i}. { message.Subject}");
                RFIDStrings.Add(message.Subject);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            pop.Disconnect();
            pop.Dispose();
        }
        return(RFIDStrings);
    }
        public static void Run()
        {
            // ExStart:RetrievingEmailHeaders
            // Create an instance of the Pop3Client class
            Pop3Client client = new Pop3Client();

            // Specify host, username. password, Port and SecurityOptions for your client
            client.Host = "pop.gmail.com";
            client.Username = "******";
            client.Password = "******";
            client.Port = 995;
            client.SecurityOptions = SecurityOptions.Auto;
            try
            {
                HeaderCollection headers = client.GetMessageHeaders(1);
                for (int i = 0; i < headers.Count; i++)
                {
                    // Display key and value in the header collection
                    Console.Write(headers.Keys[i]);
                    Console.Write(" : ");
                    Console.WriteLine(headers.Get(i));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                client.Dispose();
            }
            // ExEnd:RetrievingEmailHeaders
            Console.WriteLine(Environment.NewLine + "Displayed header information from emails using POP3 ");
        }
Пример #11
0
        public void downloadAttachment(String mail, String selectedMailContent)
        {
            String mailContent = selectedMailContent;
            var    client      = new Pop3Client();

            try
            {
                System.IO.Directory.CreateDirectory(@"C:\Attachment");
                client.Connect("pop.gmail.com", 995, true); //UseSSL true or false
                client.Authenticate(mail, "DCDC2018");

                var messageCount = client.GetMessageCount();
                var Messages     = new List <Message>(messageCount);

                Console.WriteLine("nieodczytanych wiadomosci: " + messageCount);

                for (int i = 0; i < messageCount; i++)
                {
                    Message getMessage = client.GetMessage(i + 1);
                    Messages.Add(getMessage);
                }

                foreach (Message msg in Messages)
                {
                    StringBuilder builder   = new StringBuilder();
                    MessagePart   plainText = msg.FindFirstPlainTextVersion();
                    builder.Append(plainText.GetBodyAsText());
                    //MessageBox.Show(builder.ToString());
                    string s           = builder.ToString();
                    string sFromMail   = s.Substring(0, 12);
                    string sFromSelect = selectedMailContent.Substring(0, 12);

                    //if (sFromMail.Equals(sFromSelect))
                    //{
                    foreach (var attachment in msg.FindAllAttachments())
                    {
                        string filePath = Path.Combine(@"C:\Attachment", attachment.FileName);

                        FileStream   Stream       = new FileStream(filePath, FileMode.Create);
                        BinaryWriter BinaryStream = new BinaryWriter(Stream);
                        BinaryStream.Write(attachment.Body);
                        BinaryStream.Close();
                        Console.WriteLine("zapisano zalacznik: " + attachment.FileName);
                        //}
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("", ex.Message);
            }
            finally
            {
                if (client.Connected)
                {
                    client.Dispose();
                }
            }
        }
Пример #12
0
        public void Dispose()
        {
            //pop.Dispose();
            //imap.Dispose();

            imap_Client.Dispose();
            pop_Client.Dispose();
        }
Пример #13
0
 private void close_button_Click(object sender, EventArgs e)
 {
     incoming.Logout();
     incoming.Disconnect();
     incoming.Dispose();
     this.Visible = false;
     this.Dispose();
     this.Close();
 }
Пример #14
0
 public void Logout(GXPOP3Session sessionInfo)
 {
     if (client != null)
     {
         client.Disconnect();
         client.Dispose();
         client = null;
     }
 }
Пример #15
0
        //public List<Message> FetchUnseenMessages(string hostname, int port, bool useSsl, string username, string password, List<string> seenUids)
        public List <Message> FetchUnseenMessages(List <string> seenUids)
        {
            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                string PopServerHost = ConfigurationManager.AppSettings.Get("PopServerHost");
                int    port          = int.Parse(ConfigurationManager.AppSettings.Get("PopServerPort"));
                string username      = ConfigurationManager.AppSettings.Get("UserName");
                string password      = ConfigurationManager.AppSettings.Get("Password");

                // Connect to the server
                client.Connect(PopServerHost, port, true);

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

                // Fetch all the current uids seen
                List <string> uids = client.GetMessageUids();

                // Create a list we can return with all new messages
                List <Message> newMessages = new List <Message>();

                // All the new messages not seen by the POP3 client
                for (int i = 0; i < uids.Count; i++)
                {
                    //string currentUidOnServer = uids[i];
                    //if (!seenUids.Contains(currentUidOnServer))
                    //{
                    // We have not seen this message before.
                    // Download it and add this new uid to seen uids

                    // the uids list is in messageNumber order - meaning that the first
                    // uid in the list has messageNumber of 1, and the second has
                    // messageNumber 2. Therefore we can fetch the message using
                    // i + 1 since messageNumber should be in range [1, messageCount]
                    Message unseenMessage = client.GetMessage(i + 1);

                    // Add the message to the new messages
                    newMessages.Add(unseenMessage);

                    // Add the uid to the seen uids, as it has now been seen
                    //seenUids.Add(currentUidOnServer);
                    //}
                }

                client.Disconnect();
                client.Dispose();
                // Return our new found messages
                return(newMessages);
            }
        }
Пример #16
0
 protected virtual void Dispose(bool disposing)
 {
     if (!disposed)
     {
         if (disposing)
         {
             if (client != null)
             {
                 client.Dispose();
             }
         }
         // освобождаем неуправляемые объекты
         disposed = true;
     }
 }
Пример #17
0
        public void ManageMail()
        {
            MessageHeader messageHeader;
            string        mailAddress;

            foreach (MailBox mailbox in ListMailBox)
            {
                Pop3Client client = new Pop3Client();

                try
                {
                    client.Connect(mailbox.hostname, mailbox.port, mailbox.usessl);
                    client.Authenticate(mailbox.address, mailbox.password);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error in connection! " + ex.Message);
                }

                int countMail = client.GetMessageCount();
                Console.WriteLine("In mailbox {0}, Count letters = {1}, date = {2}", mailbox.address, countMail, DateTime.Now.ToString());

                int i = 1;

                while (i <= countMail)
                {
                    messageHeader = client.GetMessageHeaders(i);
                    mailAddress   = messageHeader.From.ToString();

                    if (IsBlackAddress(mailAddress) & IsMorePeriod(messageHeader.DateSent, hours: 1))
                    {
                        client.DeleteMessage(i);
                    }

                    if (IsMorePeriod(messageHeader.DateSent, days:period) && !IsWhiteAddress(mailAddress))
                    {
                        client.DeleteMessage(i);
                        Console.WriteLine("N mail = {0}, from = {1} - delete", i, mailAddress);
                    }

                    i++;
                }

                client.Disconnect();
                client.Dispose();
            }
        }
        public string FetchEmailPassword()
        {
            string     Password = null;
            Pop3Client client   = new Pop3Client();

            try
            {
                // The client disconnects from the server when being disposed

                // Connect to the server
                client.Connect("pop.gmail.com", 995, true);

                // Authenticate ourselves towards the server
                client.Authenticate("*****@*****.**", "Dataworld@123");

                // Get the number of messages in the inbox
                int messageCount = client.GetMessageCount();


                // We want to download all messages
                List <Message> allMessages = new List <Message>(messageCount);

                // Messages are numbered in the interval: [1, messageCount]
                // Ergo: message numbers are 1-based.
                // Most servers give the latest message the highest number

                allMessages.Add(client.GetMessage(messageCount));
                Message Mymsg = allMessages[0];

                Password = FindPlainTextInMessage(allMessages[0]);
                // Now return the fetched messages

                return(Password);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                //client.Disconnect();
                client.Dispose();
            }
        }
Пример #19
0
        public void TestMethod1()
        {
            Pop3Client pc = new Pop3Client("mail.jacobgudbjerg.dk", "*****@*****.**", "jacobgud");

            var pi = pc.GetMessageCount();

//      var mes = pc.GetMessage(0);

            //mes.Attachments.First().Save(@"c:\temp\foto.jpg");

            pc.Dispose();

            ImapClient IC = new ImapClient("imap.gmail.com", "*****@*****.**", "", ImapClient.AuthMethods.Login, 993, true);
            var        i  = IC.GetMessageCount("Inbox");

            var mes = IC.GetMessage(IC.GetMessageCount() - 1);

            mes.Attachments.First().Save(@"c:\temp\foto.jpg");
            IC.Dispose();
        }
Пример #20
0
        public static List <MatterEmail> GetEmails(string email, string password, string pop3_address, int pop3_port, bool use_ssl, string end_uid, int count = 20)
        {
            Pop3Client client = new Pop3Client();

            client.Connect(pop3_address, pop3_port, use_ssl);
            client.Authenticate(email, password);
            int messageCount = client.GetMessageCount();
            var ret          = new List <MatterEmail>();

            for (int i = 0; i < count && i < messageCount; i++)
            {
                try
                {
                    var tmp = client.GetMessage(messageCount - i);
                    var uid = client.GetMessageUid(messageCount - i);
                    if (uid == end_uid)
                    {
                        break;
                    }
                    var matter_email = new MatterEmail();
                    var mail         = tmp.ToMailMessage();
                    matter_email.matter_name = mail.Subject;
                    var to_email = mail.To[0].Address ?? "";
                    var body     = ReplaceHtmlTag(mail.Body, mail.Body.Length);
                    if (body.Length >= 200)
                    {
                        body = body.Substring(0, 200);
                    }
                    matter_email.matter_desc = "From: " + mail.From + "\n To: " + to_email + "\n" + body;

                    matter_email.matter_end_time         = DateTime.Parse(tmp.Headers.Date);
                    matter_email.matter_next_effect_time = matter_email.matter_start_time = matter_email.matter_end_time;
                    matter_email.email_uid = uid;
                    ret.Add(matter_email);
                }
                catch {  }
            }
            client.Disconnect();
            client.Dispose();
            return(ret);
        }
        public static void Run()
        {
            //ExStart:RetrievingEmailMessages
            // Create an instance of the Pop3Client class
            Pop3Client client = new Pop3Client();

            // Specify host, username, password, Port and SecurityOptions for your client
            client.Host = "pop.gmail.com";
            client.Username = "******";
            client.Password = "******";
            client.Port = 995;
            client.SecurityOptions = SecurityOptions.Auto;
            try
            {
                int messageCount = client.GetMessageCount();
                // Create an instance of the MailMessage class and Retrieve message
                MailMessage message;
                for (int i = 1; i <= messageCount; i++)
                {
                    message = client.FetchMessage(i);
                    Console.WriteLine("From:" + message.From);
                    Console.WriteLine("Subject:" + message.Subject);
                    Console.WriteLine(message.HtmlBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                client.Dispose();
            }
            //ExEnd:RetrievingEmailMessages
            Console.WriteLine(Environment.NewLine + "Retrieved email messages using POP3 ");
        }
        public static void Run()
        {
            //ExStart:RetrievingEmailMessages
            // Create an instance of the Pop3Client class
            Pop3Client client = new Pop3Client();

            // Specify host, username, password, Port and SecurityOptions for your client
            client.Host            = "pop.gmail.com";
            client.Username        = "******";
            client.Password        = "******";
            client.Port            = 995;
            client.SecurityOptions = SecurityOptions.Auto;
            try
            {
                int messageCount = client.GetMessageCount();
                // Create an instance of the MailMessage class and Retrieve message
                MailMessage message;
                for (int i = 1; i <= messageCount; i++)
                {
                    message = client.FetchMessage(i);
                    Console.WriteLine("From:" + message.From);
                    Console.WriteLine("Subject:" + message.Subject);
                    Console.WriteLine(message.HtmlBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                client.Dispose();
            }
            //ExEnd:RetrievingEmailMessages
            Console.WriteLine(Environment.NewLine + "Retrieved email messages using POP3 ");
        }
Пример #23
0
        public void StartCheck()
        {
            if (Thread.CurrentThread.Name == "ThreadCheckForWrongEmails")
            {
                int waitTimeInMinutes = 2;
                if (resultContext.ListKvParams.Where(w => w.Key == "WaitCheckMailDeliveryInMinutes").Count() == 1)
                {
                    waitTimeInMinutes = Int32.Parse(resultContext.ListKvParams.Where(w => w.Key == "WaitCheckMailDeliveryInMinutes").First().Value.ToString());
                }

                Thread.Sleep((waitTimeInMinutes * 60 * 1000));
            }

            Pop3Client pop3Client = null;

            try
            {
                pop3Client = new Pop3Client();

                string mailServerPop3             = string.Empty;
                int    mailServerPop3Port         = 0;
                string mailFromPassword           = string.Empty;
                string mailDeliverySubsystemEmail = string.Empty;

                string mailFrom = string.Empty;
                string mailTo   = string.Empty;

                if (resultContext.ListKvParams.Where(w => w.Key == "DefaultEmail").Count() == 1)
                {
                    mailFrom = resultContext.ListKvParams.Where(w => w.Key == "DefaultEmail").First().Value.ToString();
                    mailTo   = resultContext.ListKvParams.Where(w => w.Key == "DefaultEmail").First().Value.ToString();
                }
                if (resultContext.ListKvParams.Where(w => w.Key == "MailServerPop3").Count() == 1)
                {
                    mailServerPop3 = resultContext.ListKvParams.Where(w => w.Key == "MailServerPop3").First().Value.ToString();
                }
                if (resultContext.ListKvParams.Where(w => w.Key == "MailServerPop3Port").Count() == 1)
                {
                    mailServerPop3Port = Int32.Parse(resultContext.ListKvParams.Where(w => w.Key == "MailServerPop3Port").First().Value.ToString());
                }
                if (resultContext.ListKvParams.Where(w => w.Key == "MailFromPassword").Count() == 1)
                {
                    mailFromPassword = resultContext.ListKvParams.Where(w => w.Key == "MailFromPassword").First().Value.ToString();
                }
                if (resultContext.ListKvParams.Where(w => w.Key == "MailDeliverySubsystemEmail").Count() == 1)
                {
                    mailDeliverySubsystemEmail = resultContext.ListKvParams.Where(w => w.Key == "MailDeliverySubsystemEmail").First().Value.ToString();
                }

                List <string> listWrongEmails = new List <string>();

                DateTime dtCurrDateSent = DateTime.Now;

                pop3Client.Connect(mailServerPop3, mailServerPop3Port, true);
                pop3Client.Authenticate(mailFrom, mailFromPassword);

                Message message       = null;
                int     countMessages = pop3Client.GetMessageCount();
                for (int i = 1; i <= countMessages; i++)
                {
                    message = pop3Client.GetMessage(i);
                    if (message != null && message.Headers != null && message.Headers.DateSent != null &&
                        message.Headers.From.Address == mailDeliverySubsystemEmail)
                    {
                        dtCurrDateSent = message.Headers.DateSent;
                        if (message.Headers.DateSent.Kind == DateTimeKind.Utc)
                        {
                            dtCurrDateSent = message.Headers.DateSent.ToLocalTime();
                        }

                        if (this.dtStartDateSend <= dtCurrDateSent && dtCurrDateSent <= DateTime.Now)
                        {
                            if (message.MessagePart != null && message.MessagePart.GetBodyAsText().Split('\r', '\n').Where(w => w.Contains("@")).Count() > 0)
                            {
                                string wrongEmail = message.MessagePart.GetBodyAsText().Split('\r', '\n').Where(w => w.Contains("@")).First().Trim();

                                listWrongEmails.Add(wrongEmail);
                            }
                        }
                    }
                }

                List <Person> listPersonsWithWrongEmails = new List <Person>();

                ETEMDataModelEntities dbContext = new ETEMDataModelEntities();

                listPersonsWithWrongEmails = (from p in dbContext.Persons
                                              where listWrongEmails.Contains(p.EMail)
                                              orderby p.FirstName ascending, p.SecondName ascending, p.LastName ascending
                                              select p).ToList <Person>();

                if (listPersonsWithWrongEmails.Count > 0)
                {
                    string subject = (from kv in dbContext.KeyValues
                                      join kt in dbContext.KeyTypes on kv.idKeyValue equals kt.idKeyType
                                      where kt.KeyTypeIntCode == ETEMEnums.KeyTypeEnum.EmailSubject.ToString() &&
                                      kv.KeyValueIntCode == ETEMEnums.EmailSubjectEnum.WrongSentEmails.ToString()
                                      select kv.Description).FirstOrDefault();

                    string body = (from kv in dbContext.KeyValues
                                   join kt in dbContext.KeyTypes on kv.idKeyValue equals kt.idKeyType
                                   where kt.KeyTypeIntCode == ETEMEnums.KeyTypeEnum.EmailSubject.ToString() &&
                                   kv.KeyValueIntCode == ETEMEnums.EmailBodyEnum.WrongSentEmails.ToString()
                                   select kv.Description).FirstOrDefault();

                    if (!string.IsNullOrEmpty(subject) && !string.IsNullOrEmpty(body))
                    {
                        string bodyInnerText = string.Empty;
                        foreach (Models.Person person in listPersonsWithWrongEmails)
                        {
                            if (string.IsNullOrEmpty(bodyInnerText))
                            {
                                bodyInnerText += BaseHelper.GetCaptionString("Email_WrongSentEmail_Email") + " " + person.EMail + "\n";
                                bodyInnerText += BaseHelper.GetCaptionString("Email_WrongSentEmail_PersonName") + " " + person.FullName;
                            }
                            else
                            {
                                bodyInnerText += "\n" + BaseHelper.GetNumberOfCharAsString('-', 100) + "\n";

                                bodyInnerText += BaseHelper.GetCaptionString("Email_WrongSentEmail_Email") + " " + person.EMail + "\n";
                                bodyInnerText += BaseHelper.GetCaptionString("Email_WrongSentEmail_PersonName") + " " + person.FullName;
                            }
                        }

                        body = string.Format(body, bodyInnerText);

                        SendMailAction(mailFrom, mailTo, subject, body);
                    }
                }
            }
            catch (Exception ex)
            {
                BaseHelper.Log("Грешка при проверка за неуспешно изпратени имейли - (ThreadCheckForWrongEmails.StartCheck)!");
                BaseHelper.Log(ex.Message);
                BaseHelper.Log(ex.StackTrace);
            }
            finally
            {
                if (pop3Client != null)
                {
                    if (pop3Client.Connected)
                    {
                        pop3Client.Disconnect();
                    }
                    pop3Client.Dispose();
                }
            }
        }
Пример #24
0
 public override void Pop3Close()
 {
     pop3Client.Disconnect();
     pop3Client.Dispose();
 }
Пример #25
0
        private void FetchAllMessages(string hostname, int port, bool useSsl, string username,
                                      string password, string mail_ppu)
        {
            List <Message> newMessages = new List <Message>();

/*
 *          var test = FetchAllMessages("pop.mail.ru", 995, true, "*****@*****.**", "dontask_mewhy");
 *          //var ttt = test.First().MessagePart.Body.ToString();
 *          var ttt1 = test.First().FindFirstPlainTextVersion().GetBodyAsText();
 *          var ttt2 = test.First().Headers.Subject;
 */
            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                try
                {
                    // Connect to the server
                    client.Connect(hostname, port, useSsl);

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

                    // Get the number of messages in the inbox
                    int messageCount = client.GetMessageCount();

                    // We want to download all messages
                    List <Message> allMessages = new List <Message>(messageCount);
                    var            mUID        = getMessagesUIDFromBase(messageCount, client);
                    List <string>  uids        = client.GetMessageUids();



                    for (int i = 0; i < uids.Count; i++)
                    {
                        string currentUidOnServer = uids[i];
                        if (!mUID.Contains(currentUidOnServer))
                        {
                            // We have not seen this message before.
                            // Download it and add this new uid to seen uids

                            // the uids list is in messageNumber order - meaning that the first
                            // uid in the list has messageNumber of 1, and the second has
                            // messageNumber 2. Therefore we can fetch the message using
                            // i + 1 since messageNumber should be in range [1, messageCount]
                            Message unseenMessage = client.GetMessage(i + 1);

                            // Add the message to the new messages
                            //newMessages.Add(unseenMessage);
                            LoadMassagesInDb(unseenMessage, client, i + 1);
                            // Add the uid to the seen uids, as it has now been seen
                            //seenUids.Add(currentUidOnServer);
                        }
                    }
                    //return allMessages;
                    // Only want to download message if:
                    //  - is from [email protected]
                    //  - has subject "Some subject"

                    /*if (from.HasValidMailAddress && from.Address.Equals("*****@*****.**"))
                     *  //&& "Some subject".Equals(subject)
                     * {
                     *  // Messages are numbered in the interval: [1, messageCount]
                     *  // Ergo: message numbers are 1-based.
                     *  // Most servers give the latest message the highest number
                     *  for (int i = messageCount; i > 0; i--)
                     *  {
                     *      allMessages.Add(client.GetMessage(i));
                     *  }
                     *
                     *  // Now return the fetched messages
                     *  return allMessages;
                     * }*/
                }
                catch (PopServerNotFoundException exception)
                {
                    StopMailService();
                    MessageBox.Show("Невозможно подключиться к серверу электронной почты, проверьте настройки.");
                }
                catch (InvalidLoginException exception)
                {
                    MessageBox.Show("Неправильный логин или пароль для почты");
                }

                client.Disconnect();
                client.Dispose();
            }
        }
Пример #26
0
        public static List <Message> DownloadAllMail()
        {
            SetMailprovider(login);
            updt = DateTime.Now;
            Console.WriteLine("{0:HH:mm:ss tt}", updt);
            bool       loginsuccess = true;
            Pop3Client client       = new Pop3Client();

            client.Connect(hostname, port, usessl);
            Console.Write("login: "******"\nPassword: "******"Wrong login/password");
                loginsuccess = false;
            }
            if (loginsuccess)
            {
                int totalamount = client.GetMessageCount();

                Console.WriteLine("Number of emails: " + totalamount);
                Console.WriteLine("Please wait...");
                List <Message> allMail = new List <Message>();
                for (int i = totalamount; i > 0; i--)
                {
                    try {
                        allMail.Add(client.GetMessage(i));
                    }
                    catch (Exception e)
                    {
                        // Console.WriteLine(i + " ==--== " + e.Message);
                        client.Dispose();
                        client = new Pop3Client();
                        client.Connect("pop.gmail.com", 995, true);
                        client.Authenticate(login, pass, AuthenticationMethod.UsernameAndPassword);
                        i++;
                    }
                }
                Console.SetCursorPosition(0, Console.CursorTop - 1);
                Console.WriteLine("Emails dowloaded: " + allMail.Count());
                // Message msgtest = client.GetMessage(totalamount);
                // Console.WriteLine(msgtest.Headers.From + " " + msgtest.Headers.Subject);

                // Console.WriteLine(msgtest.ToMailMessage().Body);

                // msgtest = client.GetMessage(1);
                // Console.WriteLine(msgtest.Headers.From + " " + msgtest.Headers.Subject);
                // ////Console.WriteLine(msgtest.ToMailMessage().Body);
                // //msgtest = client.GetMessage(totalamount-2);
                // //Console.WriteLine(msgtest.Headers.From + " " + msgtest.Headers.Subject);
                // //try {
                // //   // Console.WriteLine(msgtest.ToMailMessage().IsBodyHtml);
                // //}
                // //catch(Exception ex)
                // //{
                // //   Console.WriteLine(ex.Message);
                // //}
                // //msgtest = client.GetMessage(totalamount-3);
                // //Console.WriteLine(msgtest.Headers.From + " " + msgtest.Headers.Subject);
                // //Console.WriteLine(msgtest.ToMailMessage().Body);
                //client.Disconnect();
                Console.WriteLine("Press any key to continue");
                Console.ReadKey();
                return(allMail);
            }
            else
            {
                return(null);
            }
        }
Пример #27
0
 private void BkWorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     _pop3Client.Dispose();
     btnClose.Text  = "关闭(&C)";
     lblStatus.Text = _result;
 }
 public void TestCapabilityDiposed()
 {
     Client.Dispose();
     Assert.Throws(typeof(ObjectDisposedException), delegate { Client.Capabilities(); });
 }
Пример #29
0
 public void Dispose()
 {
     imap?.Dispose();
     pop3?.Dispose();
 }
Пример #30
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);
            }
        }
Пример #31
0
        private void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e)
        {
            //####################### Get Attachment from Email ###########################################

            ListBox listBox1 = new ListBox();
            var client = new Pop3Client();
            int Port_Number = 995;
            Boolean UseSSL = true;
            string sendBack = string.Empty;
            string returnSubject = string.Empty;

            try
            {
                client.Connect("pop.gmail.com", Port_Number, UseSSL);
                client.Authenticate("*****@*****.**", "XXXXXXX");

                var messageCount = client.GetMessageCount();
                var header = client.GetMessageInfos();

                var Messages = new List<OpenPop.Mime.Message>(messageCount);
                var Headers = new List<MessageHeader>(messageCount);

                for (int i = 0; i < messageCount; i++)
                {
                    OpenPop.Mime.Message getMessage = client.GetMessage(i + 1);
                    Messages.Add(getMessage);
                }

                for (int i = 0; i < messageCount; i++)
                {
                    OpenPop.Mime.Header.MessageHeader getHeader = client.GetMessageHeaders(i + 1);
                    Headers.Add(getHeader);
                }

                foreach (OpenPop.Mime.Message msg in Messages)
                {
                    foreach (var attachment in msg.FindAllAttachments())
                    {
                        string filePath = Path.Combine(@"C:\Users\colin\Desktop\File.txt");

                        if (attachment.FileName.Equals("EditCode.txt"))
                        {
                            FileStream Stream = new FileStream(filePath, FileMode.Create);
                            BinaryWriter BinaryStream = new BinaryWriter(Stream);
                            BinaryStream.Write(attachment.Body);
                            BinaryStream.Close();


                            foreach (var s in Headers)
                            {
                                string Reply = s.ReturnPath.ToString();
                                sendBack = Reply.ToString();

                                string Subby = s.Subject.ToString();
                                returnSubject = Subby.ToString();
                            }

                            if (client.Connected)
                                client.Dispose();
                        }

                        else
                        {
                            if (client.Connected)
                                client.Dispose();

                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("", ex.Message);
            }

            //####################### Edit File ###########################################

            if (System.IO.File.Exists(@"C:\Users\colin\Desktop\File.txt"))
            {
                using (StreamReader sr = new StreamReader(@"C:\Users\colin\Desktop\File.txt"))
                {
                    {
                        string line;

                        while ((line = sr.ReadLine()) != null)
                        {
                            if (line.Contains("<div"))
                            {
                                string s = "<div{value here}>";
                                int start = s.IndexOf("<div");
                                int end = s.IndexOf(">");

                                line = line.Remove(start);
                            }

                            if (line.Contains("</div>"))
                            { line = line.Replace("</div>", ""); }

                            if (line.Contains("h1"))
                            { line = line.Replace("h1", "h4"); }

                            if (line.Contains("h2"))
                            { line = line.Replace("h2", "h4"); }

                            if (line.Contains("h3"))
                            { line = line.Replace("h3", "h4"); }

                            if (line.Contains("&#160;"))
                            { line = line.Replace("&#160;", ""); }

                            if (line.Contains("’"))
                            { line = line.Replace("’", "'"); }

                            if (line.Contains(" –"))
                            { line = line.Replace(" –", "."); }

                            if (line.Contains("â€"))
                            { line = line.Replace("â€", ""); }

                            if (line.Contains("“"))
                            { line = line.Replace("“", ""); }

                            if (line.Contains("œ"))
                            { line = line.Replace("œ", ""); }

                            if (line.Contains("&#34;"))
                            { line = line.Replace("&#34;", ""); }

                            if (line.Contains("&#38;"))
                            { line = line.Replace("&#38;", ""); }

                            if (line.Contains("&#39;"))
                            { line = line.Replace("&#39;", "'"); }

                            if (line.Contains("class=\"note\""))
                            { line = line.Replace("class=\"note\"", ""); }

                            if (line.Contains("class=\"first\""))
                            { line = line.Replace("class=\"first\"", ""); }

                            if (line.Contains("class=\"last\""))
                            { line = line.Replace("class=\"last\"", ""); }

                            if (line.Contains("class=\"odd\""))
                            { line = line.Replace("class=\"odd\"", ""); }

                            if (line.Contains("class=\"even\""))
                            { line = line.Replace("class=\"even\"", ""); }

                            if (line.Contains("class=\"bot\""))
                            { line = line.Replace("class=\"bot\"", ""); }

                            if (line.Contains("class=\"data-table data-table-simple\""))
                            { line = line.Replace("class=\"data-table data-table-simple\"", "class=\"content-table\""); }

                            if (line.Contains("class=\"data-table data-table-advanced\""))
                            { line = line.Replace("class=\"data-table data-table-advanced\"", "class=\"content-table\""); }

                            if (line.Contains("<tr style=\"height:"))
                            {
                                line = line.Replace("<tr style=\"height: 10px;\">", "<tr>"); line = line.Replace("<tr style=\"height:10px;\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 20px;\">", "<tr>"); line = line.Replace("<tr style=\"height:20px;\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 30px;\">", "<tr>"); line = line.Replace("<tr style=\"height:30px;\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 40px;\">", "<tr>"); line = line.Replace("<tr style=\"height:40px;\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 50px;\">", "<tr>"); line = line.Replace("<tr style=\"height:50px;\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 60px;\">", "<tr>"); line = line.Replace("<tr style=\"height:60px;\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 70px;\">", "<tr>"); line = line.Replace("<tr style=\"height:70px;\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 80px;\">", "<tr>"); line = line.Replace("<tr style=\"height:80px;\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 90px;\">", "<tr>"); line = line.Replace("<tr style=\"height:90px;\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 100px;\">", "<tr>"); line = line.Replace("<tr style=\"height:100px;\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 110px;\">", "<tr>"); line = line.Replace("<tr style=\"height:110px;\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 120px;\">", "<tr>"); line = line.Replace("<tr style=\"height:120px;\">", "<tr>");

                                line = line.Replace("<tr style=\"height: 10px\">", "<tr>"); line = line.Replace("<tr style=\"height:10px\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 20px\">", "<tr>"); line = line.Replace("<tr style=\"height:20px\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 30px\">", "<tr>"); line = line.Replace("<tr style=\"height:30px\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 40px\">", "<tr>"); line = line.Replace("<tr style=\"height:40px\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 50px\">", "<tr>"); line = line.Replace("<tr style=\"height:50px\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 60px\">", "<tr>"); line = line.Replace("<tr style=\"height:60px\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 70px\">", "<tr>"); line = line.Replace("<tr style=\"height:70px\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 80px\">", "<tr>"); line = line.Replace("<tr style=\"height:80px\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 90px\">", "<tr>"); line = line.Replace("<tr style=\"height:90px\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 100px\">", "<tr>"); line = line.Replace("<tr style=\"height:100px\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 110px\">", "<tr>"); line = line.Replace("<tr style=\"height:110px\">", "<tr>");
                                line = line.Replace("<tr style=\"height: 120px\">", "<tr>"); line = line.Replace("<tr style=\"height:120px\">", "<tr>");
                            }

                            if (line.Contains("<th style=\"height:"))
                            {
                                line = line.Replace("<th style=\"height: 10px;\">", "<th>"); line = line.Replace("<th style=\"height:10px;\">", "<th>");
                                line = line.Replace("<th style=\"height: 20px;\">", "<th>"); line = line.Replace("<th style=\"height:20px;\">", "<th>");
                                line = line.Replace("<th style=\"height: 30px;\">", "<th>"); line = line.Replace("<th style=\"height:30px;\">", "<th>");
                                line = line.Replace("<th style=\"height: 40px;\">", "<th>"); line = line.Replace("<th style=\"height:40px;\">", "<th>");
                                line = line.Replace("<th style=\"height: 50px;\">", "<th>"); line = line.Replace("<th style=\"height:50px;\">", "<th>");
                                line = line.Replace("<th style=\"height: 60px;\">", "<th>"); line = line.Replace("<th style=\"height:60px;\">", "<th>");
                                line = line.Replace("<th style=\"height: 70px;\">", "<th>"); line = line.Replace("<th style=\"height:70px;\">", "<th>");
                                line = line.Replace("<th style=\"height: 80px;\">", "<th>"); line = line.Replace("<th style=\"height:80px;\">", "<th>");
                                line = line.Replace("<th style=\"height: 90px;\">", "<th>"); line = line.Replace("<th style=\"height:90px;\">", "<th>");
                                line = line.Replace("<th style=\"height: 100px;\">", "<th>"); line = line.Replace("<th style=\"height:100px;\">", "<th>");
                                line = line.Replace("<th style=\"height: 110px;\">", "<th>"); line = line.Replace("<th style=\"height:110px;\">", "<th>");
                                line = line.Replace("<th style=\"height: 120px;\">", "<th>"); line = line.Replace("<th style=\"height:120px;\">", "<th>");

                                line = line.Replace("<th style=\"height: 10px\">", "<th>"); line = line.Replace("<th style=\"height:10px\">", "<th>");
                                line = line.Replace("<th style=\"height: 20px\">", "<th>"); line = line.Replace("<th style=\"height:20px\">", "<th>");
                                line = line.Replace("<th style=\"height: 30px\">", "<th>"); line = line.Replace("<th style=\"height:30px\">", "<th>");
                                line = line.Replace("<th style=\"height: 40px\">", "<th>"); line = line.Replace("<th style=\"height:40px\">", "<th>");
                                line = line.Replace("<th style=\"height: 50px\">", "<th>"); line = line.Replace("<th style=\"height:50px\">", "<th>");
                                line = line.Replace("<th style=\"height: 60px\">", "<th>"); line = line.Replace("<th style=\"height:60px\">", "<th>");
                                line = line.Replace("<th style=\"height: 70px\">", "<th>"); line = line.Replace("<th style=\"height:70px\">", "<th>");
                                line = line.Replace("<th style=\"height: 80px\">", "<th>"); line = line.Replace("<th style=\"height:80px\">", "<th>");
                                line = line.Replace("<th style=\"height: 90px\">", "<th>"); line = line.Replace("<th style=\"height:90px\">", "<th>");
                                line = line.Replace("<th style=\"height: 100px\">", "<th>"); line = line.Replace("<th style=\"height:100px\">", "<th>");
                                line = line.Replace("<th style=\"height: 110px\">", "<th>"); line = line.Replace("<th style=\"height:110px\">", "<th>");
                                line = line.Replace("<th style=\"height: 120px\">", "<th>"); line = line.Replace("<th style=\"height:120px\">", "<th>");
                            }

                            if (line.Contains("<td style=\"height:"))
                            {
                                line = line.Replace("<td style=\"height: 10px;\">", "<td>"); line = line.Replace("<td style=\"height:10px;\">", "<td>");
                                line = line.Replace("<td style=\"height: 20px;\">", "<td>"); line = line.Replace("<td style=\"height:20px;\">", "<td>");
                                line = line.Replace("<td style=\"height: 30px;\">", "<td>"); line = line.Replace("<td style=\"height:30px;\">", "<td>");
                                line = line.Replace("<td style=\"height: 40px;\">", "<td>"); line = line.Replace("<td style=\"height:40px;\">", "<td>");
                                line = line.Replace("<td style=\"height: 50px;\">", "<td>"); line = line.Replace("<td style=\"height:50px;\">", "<td>");
                                line = line.Replace("<td style=\"height: 60px;\">", "<td>"); line = line.Replace("<td style=\"height:60px;\">", "<td>");
                                line = line.Replace("<td style=\"height: 70px;\">", "<td>"); line = line.Replace("<td style=\"height:70px;\">", "<td>");
                                line = line.Replace("<td style=\"height: 80px;\">", "<td>"); line = line.Replace("<td style=\"height:80px;\">", "<td>");
                                line = line.Replace("<td style=\"height: 90px;\">", "<td>"); line = line.Replace("<td style=\"height:90px;\">", "<td>");
                                line = line.Replace("<td style=\"height: 100px;\">", "<td>"); line = line.Replace("<td style=\"height:100px;\">", "<td>");
                                line = line.Replace("<td style=\"height: 110px;\">", "<td>"); line = line.Replace("<td style=\"height:110px;\">", "<td>");
                                line = line.Replace("<td style=\"height: 120px;\">", "<td>"); line = line.Replace("<td style=\"height:120px;\">", "<td>");

                                line = line.Replace("<td style=\"height: 10px\">", "<td>"); line = line.Replace("<td style=\"height:10px\">", "<td>");
                                line = line.Replace("<td style=\"height: 20px\">", "<td>"); line = line.Replace("<td style=\"height:20px\">", "<td>");
                                line = line.Replace("<td style=\"height: 30px\">", "<td>"); line = line.Replace("<td style=\"height:30px\">", "<td>");
                                line = line.Replace("<td style=\"height: 40px\">", "<td>"); line = line.Replace("<td style=\"height:40px\">", "<td>");
                                line = line.Replace("<td style=\"height: 50px\">", "<td>"); line = line.Replace("<td style=\"height:50px\">", "<td>");
                                line = line.Replace("<td style=\"height: 60px\">", "<td>"); line = line.Replace("<td style=\"height:60px\">", "<td>");
                                line = line.Replace("<td style=\"height: 70px\">", "<td>"); line = line.Replace("<td style=\"height:70px\">", "<td>");
                                line = line.Replace("<td style=\"height: 80px\">", "<td>"); line = line.Replace("<td style=\"height:80px\">", "<td>");
                                line = line.Replace("<td style=\"height: 90px\">", "<td>"); line = line.Replace("<td style=\"height:90px\">", "<td>");
                                line = line.Replace("<td style=\"height: 100px\">", "<td>"); line = line.Replace("<td style=\"height:100px\">", "<td>");
                                line = line.Replace("<td style=\"height: 110px\">", "<td>"); line = line.Replace("<td style=\"height:110px\">", "<td>");
                                line = line.Replace("<td style=\"height: 120px\">", "<td>"); line = line.Replace("<td style=\"height:120px\">", "<td>");
                            }

                            if (line.Contains("style=\"text-align:left") || line.Contains("style=\"text-align: left")
                                || line.Contains("style= \"text-align:left") || line.Contains("style=\" text-align: left"))
                            {
                                line = line.Replace("style=\"text-align:left\"", "");
                                line = line.Replace("style=\"text-align: left\"", "");
                                line = line.Replace("style=\"text-align:left;\"", "");
                                line = line.Replace("style=\"text-align: left;\"", "");
                                line = line.Replace("style=\" text-align:left\"", "");
                                line = line.Replace("style=\" text-align: left\"", "");
                                line = line.Replace("style=\" text-align:left;\"", "");
                                line = line.Replace("style=\" text-align: left;\"", "");
                                line = line.Replace("style= \"text-align:left\"", "");
                                line = line.Replace("style= \"text-align: left\"", "");
                                line = line.Replace("style= \"text-align:left;\"", "");
                                line = line.Replace("style= \"text-align: left;\"", "");
                            }

                            if (line.Contains("<td>") || line.Contains("<td >") || line.Contains("<td  >"))
                            {
                                line = line.Replace("<td>", "<td style=\"text-align:center\">");
                                line = line.Replace("<td >", "<td style=\"text-align:center\">");
                                line = line.Replace("<td  >", "<td style=\"text-align:center\">");
                            }

                            if (line.Contains("<th>") || line.Contains("<th >") || line.Contains("<th  >"))
                            {
                                line = line.Replace("<th>", "<th style=\"text-align:center\">");
                                line = line.Replace("<th >", "<th style=\"text-align:center\">");
                                line = line.Replace("<th  >", "<th style=\"text-align:center\">");
                            }

                            if (line.Contains("<h4") || line.Contains("< h4")
                                && line.Contains("<br") || line.Contains("< br"))
                            {
                                line = line.Replace("<br/>", ""); line = line.Replace("< br/>", "");
                                line = line.Replace("<br/ >", ""); line = line.Replace("< br/ >", "");
                                line = line.Replace("<br />", ""); line = line.Replace("< br />", "");
                                line = line.Replace("<br / >", ""); line = line.Replace("< br / >", "");
                                line = line.Replace("< br/ >", ""); line = line.Replace("< br/  >", "");
                            }

                            if (line.Contains("<table"))
                            {
                                line = line.Replace("<table", "<table border=\"1\"");
                            }

                            if (line.Contains("<ol>"))
                            {
                                line = line.Replace("<ol>", "<ol style=\"list-style-type:lower-alpha\">");
                            }

                            if (line.Contains("<strong>note") || line.Contains("<strong>Note"))
                            {
                                listBox1.Items.Add("<br/><br/>");
                            }

                            if (line.Contains("<strong>important") || line.Contains("<strong>Important"))
                            {
                                listBox1.Items.Add("<br/><br/>");
                            }

                            if (line.Contains("<strong>result") || line.Contains("<strong>Result"))
                            {
                                listBox1.Items.Add("<br/><br/>");
                            }

                            if (line.Contains("<h4>") || line.Contains("<h4 >"))
                            {
                                listBox1.Items.Add("</div>");
                                listBox1.Items.Add("<div class=\"content-box\">");
                                listBox1.Items.Add("<div class=\"information-box\">");
                                listBox1.Items.Add("<div class=\"meatball\"></div>");
                            }

                            listBox1.Items.Add(line);

                            if (line.Contains("</h4>") || line.Contains("</h4 >"))
                            {
                                string p = "</h4>";
                                int start = p.IndexOf("</h4>");

                                listBox1.Items.Add("</div>");
                            }
                        }

                        string look = listBox1.Items[0].ToString();

                        if (look.Contains("</div>") == false)
                        {
                            listBox1.Items.Insert(0, "</div>");
                            listBox1.Items.Insert(0, "<p>SUMMARY</p>");
                            listBox1.Items.Insert(0, "<div class=\"meatball\"></div>");
                            listBox1.Items.Insert(0, "<div class=\"information-box\">");
                            listBox1.Items.Insert(0, "<div class=\"content-box\">");
                            listBox1.Items.Insert(0, "<div id=\"general\">");
                        }

                        if (look.Contains("</div>"))
                        {
                            listBox1.Items.Remove("</div>");
                            listBox1.Items.Insert(0, "<div id=\"general\">");
                        }

                        listBox1.Items.Add("</div> </div>");

                    }
                }
            }
            else
            {
                Application.Restart();
            }

            //####################### Save Attachment ###########################################

            string sPath = @"C:\Users\colin\Desktop\EditFile.txt";

            System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath);
            foreach (var item in listBox1.Items)
            {
                SaveFile.WriteLine(item);
            }

            SaveFile.Close();

            if (System.IO.File.Exists(@"C:\Users\colin\Desktop\File.txt"))
            { System.IO.File.Delete(@"C:\Users\colin\Desktop\File.txt"); }

            else
            {
                Application.Restart();
            }

            //####################### Send Back Edited File ###########################################

            try
            {

                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
                mail.From = new MailAddress("*****@*****.**");
                mail.To.Add(sendBack);
                mail.Subject = returnSubject;
                mail.Body = "Have a Nice Day!!";

                System.Net.Mail.Attachment newAttachment;
                newAttachment = new System.Net.Mail.Attachment(@"C:\Users\colin\Desktop\EditFile.txt");
                mail.Attachments.Add(newAttachment);

                SmtpServer.Port = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "caiken121");
                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Пример #32
0
 public void Dispose()
 {
     fClient.Dispose();
 }
Пример #33
0
        public static void 查看气象台163pop3()
        {
            var util = new XmlConfig(Environment.CurrentDirectory + @"\config\智能网格设置.xml");
            // Connect and log in to POP3
            const string host     = "pop.163.com";
            const int    port     = 995;
            var          username = util.Read("emailConfig", "emailFrom", "address");
            var          password = util.Read("emailConfig", "emailFrom", "password");
            var          yjjl     = util.Read("emailConfig", "空气邮件查收记录");
            var          client   = new Pop3Client(host, port, username, password);

            try
            {
                var jlLists   = new List <string>();
                var dateLists = new List <DateTime>();
                var szls      = yjjl.Split(',');
                if (szls.Length > 0)
                {
                    foreach (var item in szls)
                    {
                        if (item.Trim() != "")
                        {
                            try
                            {
                                var strDate = item.Trim();
                                jlLists.Add(strDate);
                                dateLists.Add(Convert.ToDateTime(strDate.Substring(0, 4) + "-" +
                                                                 strDate.Substring(4, 2) + "-" +
                                                                 strDate.Substring(6, 2)));
                            }
                            catch
                            {
                            }
                        }
                    }
                }

                var builder1 = new MailQueryBuilder();
                builder1.From.Contains("yewu_zzy", true);
                builder1.InternalDate.Before(DateTime.Now.AddDays(1));
                builder1.InternalDate.Since(DateTime.Now.AddDays(-7));
                var query1          = builder1.GetQuery();
                var messageInfoCol1 = client.ListMessages(query1);
                var changeBS        = false;
                for (var i = 0; i < messageInfoCol1.Count; i++)
                {
                    if (!jlLists.Exists(y => messageInfoCol1[i].Subject.Contains(y)))
                    {
                        changeBS = true;
                        var msg = client.FetchMessage(messageInfoCol1[i].UniqueId);
                        try
                        {
                            var regex = new Regex("\\d{10}");
                            var m     = regex.Match(messageInfoCol1[i].Subject);
                            if (m.Success)
                            {
                                var strDate    = m.Groups[0].Value;
                                var dateTimels = Convert.ToDateTime(strDate.Substring(0, 4) + "-" +
                                                                    strDate.Substring(4, 2) + "-" +
                                                                    strDate.Substring(6, 2));
                                var dataDir = util.Read("路径", "Path空气质量中长期预报") +
                                              $@"{dateTimels:yyyy}\{dateTimels:MM}\{dateTimels:dd}\\";
                                if (!File.Exists(dataDir))
                                {
                                    Directory.CreateDirectory(dataDir);
                                }

                                foreach (var item in msg.Attachments)
                                {
                                    item.Save(dataDir + item.Name);
                                }
                                dateLists.Add(dateTimels);
                            }
                        }
                        catch
                        {
                        }
                    }
                }

                try
                {
                    if (changeBS)
                    {
                        if (dateLists.Count > 0)
                        {
                            var saveDate = new List <DateTime>();
                            foreach (var item in dateLists)
                            {
                                if (item.CompareTo(DateTime.Now.Date.AddDays(-8)) >= 0)
                                {
                                    saveDate.Add(item);
                                }
                            }

                            var saveStr = "";
                            foreach (var item in saveDate)
                            {
                                saveStr += $"{item:yyyyMMdd},";
                            }
                            if (saveStr.Length > 0)
                            {
                                saveStr = saveStr.Substring(0, saveStr.Length - 1);
                            }
                            util.Write(saveStr, "emailConfig", "空气邮件查收记录");
                        }
                    }
                }
                catch
                {
                }

                client.Dispose();
            }
            catch (Exception ex)
            {
            }
        }