예제 #1
0
        //Connect to gmail, get emails and ad it to a MessageList
        public static List<OpenPop.Mime.Message> GetAllMessages(string hostname, int port, bool ssl, string username, string password)
        {
            try
            {
                Pop3Client client = new Pop3Client();

                    if (client.Connected)
                    {
                        client.Disconnect();
                    }

                    client.Connect(hostname, port, ssl);
                    client.Authenticate(username, password);

                    int messageCount = client.GetMessageCount();

                    List<OpenPop.Mime.Message> allMessages = new List<OpenPop.Mime.Message>(messageCount);

                    for (int i = messageCount; i > messageCount - 5; i--)
                    {
                        allMessages.Add(client.GetMessage(i));
                    }

                    return allMessages;
                }

            catch(Exception ex)
            {
                MessageBox.Show("You have written username or password wrong or something else has happened! Program will not keep going, please open it again, thank you : " + ex.Message);
                Thread.CurrentThread.Abort();
                //EmailClient.
            }

            return null;
        }
예제 #2
0
        private static void DownloadMailsAndPushToIssueTracker()
        {
            var host = Settings.Get("Pop3Host", "");
            var port = Settings.Get("Pop3Port", 110);
            var useSsl = Settings.Get("Pop3UseSsl", false);
            var username = Settings.Get("Pop3Username", "");
            var password = Settings.Get("Pop3Password", "");

            if (host.IsNoE())
            {
                Console.WriteLine("\tNo Pop3Host specified.");
                LogOwnError(new ApplicationException("No Pop3Host specified."));
                return;
            }

            try
            {
                Console.WriteLine("\tConnecting to POP3 server {0}:{1} ({4}) using {2} / {3} ...", host, port, username, password, useSsl ? "SSL" : "no SSL");

                using (var pop3Client = new Pop3Client())
                {
                    pop3Client.Connect(host, port, useSsl);
                    if (username.HasValue())
                        pop3Client.Authenticate(username, password);

                    Console.WriteLine("\tFetching message count ...");
                    var messageCount = pop3Client.GetMessageCount();

                    for (var i = 1; i <= messageCount; i++)
                    {
                        try
                        {
                            Console.WriteLine("\tFetching message {0} / {1} ...", i, messageCount);
                            var message = pop3Client.GetMessage(i);

                            if (PushToIssueTracker(message))
                                pop3Client.DeleteMessage(i);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("\tUnable to fetch or push message: " + ex);
                            LogOwnError(new ApplicationException("Unable to fetch or push message: " + ex.Message, ex));
                        }
                    }

                    pop3Client.Disconnect();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("\tUnable to download mails: " + ex);
                LogOwnError(new ApplicationException("Unable to download mails: " + ex.Message, ex));
            }
        }
        public void button1_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.UserName = textBox1.Text.ToString();
            Properties.Settings.Default.Password = textBox2.Text.ToString();

            lbAuth.Text = "";
            pbxAuthOk.Visible = false;
            pbxAuthFail.Visible = false;

            try
            {
                using (Pop3Client client = new Pop3Client())
                {

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

                    // Authenticate ourselves towards the server /HejHej
                    client.Authenticate(Properties.Settings.Default.UserName, Properties.Settings.Default.Password);

                    if (client.Connected == true)
                    {
                        pbxAuthOk.Visible = true;
                        lbAuth.Text = "Authentication OK!";
                        Properties.Settings.Default.Save();
                    }

                    client.Disconnect();
                }
            }
            catch (Exception)
            {
                pbxAuthFail.Visible = true;
                lbAuth.Text = "Something's wrong! \nMaybe bad username or password..";
                Properties.Settings.Default.UserName = null;
                Properties.Settings.Default.Save();

               if (Properties.Settings.Default.UserName != null)
                {

                    lbCurrentUsr.Text = Properties.Settings.Default.UserName;
                }
                else
                {
                    lbCurrentUsr.Text = "No Current user is saved.";
                }
            }
        }
예제 #4
0
        public bool FindAndDownloadBudget(BackgroundWorker bw)
        {
            bool attachmentFound = false;
            try
            {
                Log.n("Kobler til e-post server \"" + main.appConfig.epostPOP3server + "\"..");
                using (Pop3Client client = new Pop3Client())
                {
                    client.Connect(main.appConfig.epostPOP3server, main.appConfig.epostPOP3port, main.appConfig.epostPOP3ssl);

                    if (bw != null) {
                        if (bw.CancellationPending) {
                            if (client.Connected)
                                client.Disconnect();
                            return false;
                        }
                    }

                    Log.d("Logger inn med brukernavn \"" + main.appConfig.epostBrukernavn + "\"..");
                    SimpleAES aes = new SimpleAES();
                    client.Authenticate(main.appConfig.epostPOP3username, aes.DecryptString(main.appConfig.epostPOP3password));
                    int count = client.GetMessageCount();

                    Log.d("Innlogging fullført. Antall meldinger i innboks: " + count);
                    if (count == 0)
                    {
                        Log.n("Innboks for \"" + main.appConfig.epostPOP3username + "\" er tom. "
                            + "Endre innstillinger i ditt e-post program til å la e-post ligge igjen på server", Color.Red);
                        client.Disconnect();
                        return false;
                    }

                    main.processing.SetText = "Søker i innboks.. (totalt " + count + " meldinger)";
                    Log.n("Søker i innboks.. (totalt " + count + " meldinger)");
                    for (int i = count + 1; i-- > 1;)
                    {
                        if (attachmentFound || maxEmailAttemptsReached)
                            break;

                        if (bw != null)
                            if (bw.CancellationPending)
                                break;

                        Log.d("Sjekker meldingshode " + (count - i + 1) + "..");
                        MessageHeader header = client.GetMessageHeaders(i);
                        if (HeaderMatch(header))
                        {
                            if (header.DateSent.Date != selectedDate.Date)
                            {
                                Log.d("Fant C810 e-post med annen dato: " + header.DateSent.ToShortDateString()
                                    + " ser etter: " + selectedDate.ToShortDateString() + " Emne: \"" + header.Subject
                                    + "\" Fra: \"" + header.From.MailAddress + "\"");
                                continue;
                            }

                            Log.d("--------- Fant C810 e-post kandidat: Fra: \""
                                + header.From.MailAddress.Address + "\" Emne: \"" + header.Subject
                                + "\" Sendt: " + header.DateSent.ToShortDateString() + " (" + header.DateSent.ToShortTimeString() + ")");

                            Log.d("Laster ned e-post # " + i + "..");
                            Message message = client.GetMessage(i);

                            foreach (MessagePart attachment in message.FindAllAttachments())
                            {
                                if (attachmentFound)
                                    break;

                                Log.d("Vedlegg: " + attachment.FileName);
                                if (AttachmentMatch(attachment))
                                    attachmentFound = ParseAndSaveDailyBudget(attachment,
                                        message.Headers.DateSent,
                                        message.Headers.Subject,
                                        message.Headers.From.MailAddress.Address);
                            }
                        }

                        if (!attachmentFound)
                            Log.d("Fant ingen C810 vedlegg i e-post # " + i);
                    }
                    client.Disconnect();
                }

                if (attachmentFound)
                    return true;
                else if (!attachmentFound && maxEmailAttemptsReached)
                    Log.n("Maksimum antall e-post nedlastninger er overgått. Innboks søk er avsluttet", Color.Red);
                else
                    Log.n("Fant ingen C810 e-post med budsjett for dato " + selectedDate.ToShortDateString() + ". Innboks søk er avsluttet", Color.Red);
            }
            catch (PopServerNotFoundException)
            {
                Log.n("E-post server finnes ikke eller DNS problem ved tilkobling til " + main.appConfig.epostPOP3server, Color.Red);
            }
            catch (PopServerNotAvailableException ex)
            {
                Log.n("E-post server \"" + main.appConfig.epostPOP3server + "\" svarer ikke. Feilmelding: " + ex.Message, Color.Red);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Authentication failed") || ex.Message.Contains("credentials"))
                    Log.n("Feil brukernavn eller passord angitt for " + main.appConfig.epostPOP3username + ". Sjekk e-post innstillinger!", Color.Red);
                else
                {
                    Log.Unhandled(ex);
                    Log.n("Feil ved henting av epost. Beskjed: " + ex.Message);
                }
            }
            return false;
        }
 private void segundoplano_DoWork(object sender, DoWorkEventArgs e)
 {
     Pop3Client emaiClient = new Pop3Client();
     try
     {
         emaiClient.Connect(servidordeemail.Text, Convert.ToInt32(porta.Value), SSL);
         emaiClient.Authenticate(usuario.Text, senha.Text);
         if (!emaiClient.Connected) return;
         var messages = new List<OpenPop.Mime.Message>();
         Total_de_Emails = emaiClient.GetMessageCount();
         for (var i = 1; i < Total_de_Emails; i++)
         {
             messages.Add(emaiClient.GetMessage(i));
             segundoplano.ReportProgress(i);
         }
         Total_de_Emails = messages.Count;
         int x = 0;
         foreach (var msg in messages.Where(y => DateTime.Parse(y.Headers.Date) >= DataInicial && DateTime.Parse(y.Headers.Date) <= DataFinal && y.FindAllAttachments() != null))
         {
             x++;
             var anexo = msg.FindAllAttachments();
             foreach (var ado in anexo.Where(c => c.FileName.EndsWith(".xml")))
             {
                 ado.Save(new FileInfo(Path.Combine(Caminho, ado.FileName)));
             }
             segundoplano.ReportProgress(x);
         }
     }
     catch (Exception exception)
     {
         MessageBox.Show(exception.Message);
     }
     finally
     {
         if (emaiClient.Connected)
         {
             emaiClient.Disconnect();
             emaiClient.Dispose();
         }
     }
 }
예제 #6
0
    ///////////////////////////////////////////////////////////////////////
    protected void fetch_messages(string user, string password, int projectid)
    {

        List<string> messages = null;
        Regex regex = new Regex("\r\n");
        using (Pop3Client client = new Pop3Client())
        {
            try
            {
                write_line("****connecting to server:");
                int port = 110;
                if (Pop3Port != "")
                {
                    port = Convert.ToInt32(Pop3Port);
                }

                bool use_ssl = false;
                if (Pop3UseSSL != "")
                {
                    use_ssl = Pop3UseSSL == "1" ? true : false;
                }

                write_line("Connecting to pop3 server");
                client.Connect(Pop3Server, port, use_ssl);
                write_line("Autenticating");
                client.Authenticate(user, password);


                write_line("Getting list of documents");
                messages = client.GetMessageUids();
            }
            catch (Exception e)
            {
                write_line("Exception trying to talk to pop3 server");
                write_line(e);
                return;
            }


            int message_number = 0;


            // loop through the messages
            for (int i = 0; i < messages.Count; i++)
            {
                heartbeat_datetime = DateTime.Now; // because the watchdog is watching

                if (state != service_state.STARTED)
                {
                    break;
                }

                // fetch the message

                write_line("Getting Message:" + messages[i]);
                message_number = Convert.ToInt32(messages[i]);
                Message mimeMessage = null;

                try
                {
                    mimeMessage = client.GetMessage(message_number);
                }
                catch (Exception exception)
                {
                    write_to_log("Error getting message" );
                    write_to_log(exception.ToString());
                    continue;
                }
                    

                // for diagnosing problems
                if (MessageOutputFile != "")
                {
                    File.WriteAllBytes(MessageOutputFile, mimeMessage.RawMessage);
                }

                // break the message up into lines

                string from = mimeMessage.Headers.From.Address;
                string subject = mimeMessage.Headers.Subject;




                write_line("\nFrom: " + from);

                write_line("Subject: " + subject);

                if (!string.IsNullOrEmpty(SubjectMustContain) && subject.IndexOf(SubjectMustContain, StringComparison.OrdinalIgnoreCase) < 0)
                {
                    write_line("skipping because subject does not contain: " + SubjectMustContain);
                    continue;
                }

                bool bSkip = false;
                foreach (string subjectCannotContainString in SubjectCannotContainStrings)
                {
                    if (!string.IsNullOrEmpty(subjectCannotContainString))
                    {
                        if (subject.IndexOf(subjectCannotContainString, StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            write_line("skipping because subject cannot contain: " + subjectCannotContainString);
                            bSkip = true;
                            break;  // done checking, skip this message
                        }
                    }
                }

                if (bSkip)
                {
                    continue;
                }

                if (!string.IsNullOrEmpty(FromMustContain) && from.IndexOf(FromMustContain, StringComparison.OrdinalIgnoreCase) < 0)
                {
                    write_line("skipping because from does not contain: " + FromMustContain);
                    continue; // that is, skip to next message
                }

                foreach (string fromCannotContainStrings in FromCannotContainStrings)
                {
                    if (!string.IsNullOrEmpty(fromCannotContainStrings))
                    {
                        if (from.IndexOf(fromCannotContainStrings, StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            write_line("skipping because from cannot contain: " + fromCannotContainStrings);
                            bSkip = true;
                            break; // done checking, skip this message
                        }
                    }
                }

                if (bSkip)
                {
                    continue;
                }

                write_line("calling insert_bug.aspx");
                string Url = InsertBugUrl;

                // Try to parse out the bugid from the subject line
                string bugidString = TrackingIdString;
                if (string.IsNullOrEmpty(TrackingIdString))
                {
                    bugidString = "DO NOT EDIT THIS:";
                }

                int pos = subject.IndexOf(bugidString, StringComparison.OrdinalIgnoreCase);

                if (pos >= 0)
                {
                    // position of colon
                    pos = subject.IndexOf(":", pos);
                    pos++;
                    // position of close paren
                    int pos2 = subject.IndexOf(")", pos);
                    if (pos2 > pos)
                    {
                        string bugid_string = subject.Substring(pos, pos2 - pos);
                        write_line("BUGID=" + bugid_string);
                        try
                        {
                            int bugid = Int32.Parse(bugid_string);
                            Url += "?bugid=" + Convert.ToString(bugid);
                            write_line("updating existing bug " + Convert.ToString(bugid));
                        }
                        catch (Exception e)
                        {
                            write_line("bugid not numeric " + e.Message);
                        }
                    }
                }

                string rawMessage = Encoding.Default.GetString(mimeMessage.RawMessage);
                string post_data = "username="******"&password="******"&projectid=" + Convert.ToString(projectid)
                                   + "&from=" + HttpUtility.UrlEncode(from)
                                   + "&short_desc=" + HttpUtility.UrlEncode(subject)
                                   + "&message=" + HttpUtility.UrlEncode(rawMessage);

                byte[] bytes = Encoding.UTF8.GetBytes(post_data);


                // send request to web server
                HttpWebResponse res = null;
                try
                {
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url);


                    req.Credentials = CredentialCache.DefaultCredentials;
                    req.PreAuthenticate = true;

                    //req.Timeout = 200; // maybe?
                    //req.KeepAlive = false; // maybe?

                    req.Method = "POST";
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.ContentLength = bytes.Length;
                    Stream request_stream = req.GetRequestStream();
                    request_stream.Write(bytes, 0, bytes.Length);
                    request_stream.Close();
                    res = (HttpWebResponse)req.GetResponse();
                }
                catch (Exception e)
                {
                    write_line("HttpWebRequest error url=" + Url);
                    write_line(e);
                }

                // examine response

                if (res != null)
                {

                    int http_status = (int)res.StatusCode;
                    write_line(Convert.ToString(http_status));

                    string http_response_header = res.Headers["BTNET"];
                    res.Close();

                    if (http_response_header != null)
                    {
                        write_line(http_response_header);

                        // only delete message from pop3 server if we
                        // know we stored in on the web server ok
                        if (MessageInputFile == ""
                            && http_status == 200
                            && DeleteMessagesOnServer == "1"
                            && http_response_header.IndexOf("OK") == 0)
                        {
                            write_line("sending POP3 command DELE");
                            client.DeleteMessage(message_number);
                        }
                    }
                    else
                    {
                        write_line("BTNET HTTP header not found.  Skipping the delete of the email from the server.");
                        write_line("Incrementing total error count");
                        total_error_count++;
                    }
                }
                else
                {
                    write_line("No response from web server.  Skipping the delete of the email from the server.");
                    write_line("Incrementing total error count");
                    total_error_count++;
                }

                if (total_error_count > TotalErrorsAllowed)
                {
                    write_line("Stopping because total error count > TotalErrorsAllowed");
                    stop();
                }


            }  // end for each message


            if (MessageInputFile == "")
            {
                write_line("\nsending POP3 command QUIT");
                client.Disconnect();
            }
            else
            {
                write_line("\nclosing input file " + MessageInputFile);
            }
        }
    }
예제 #7
0
        private void ReceivingLoop()
        {
            using (Pop3Client client = new Pop3Client())
            {
                for (; ; )
                {
                    try
                    {
                        if (!client.Connected)
                        {
                            client.Connect("pop.gmail.com", 995, true);
                            client.Authenticate(mail_username, mail_password);
                            List<string> uids = client.GetMessageUids();
                            List<Message> newMessages = new List<Message>();

                            for (int i = 0; i < uids.Count; i++)
                            {
                                string currentUidOnServer = uids[i];
                                Message unseenMessage = client.GetMessage(i + 1);
                                newMessages.Add(unseenMessage);
                            }

                            for (int i = 0; i < newMessages.Count; i++)
                            {
                                Console.WriteLine("Message: " + newMessages.ElementAt(i).ToMailMessage().Body);
                                ConvertReceivedToOrder(newMessages.ElementAt(i).Headers.Subject, newMessages.ElementAt(i).ToMailMessage().Body);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Cannot connect: " + e.Message);
                        Thread.Sleep(2000);
                    }
                    finally
                    {
                        try
                        {
                            if (client.Connected) client.Disconnect();
                            do Thread.Sleep(500); while (client.Connected);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Cannot disconnect - reset connection: " + e.Message);
                            client.Reset();
                            Thread.Sleep(2000);
                        }
                    }
                }
            }
        }
		public void TestDeleteAllMessages()
		{
			const string welcomeMessage = "+OK";
			const string okUsername = "******";
			const string okPassword = "******";
			const string messageCountResponse = "+OK 2 5"; // 2 messages with total size of 5 octets
			const string deleteResponse = "+OK"; // Message was deleted
			const string quitAccepted = "+OK";
			const string serverResponses = welcomeMessage + "\r\n" + okUsername + "\r\n" + okPassword + "\r\n" + messageCountResponse  + "\r\n" + deleteResponse + "\r\n" + deleteResponse + "\r\n" + quitAccepted + "\r\n";

			Stream inputStream = new MemoryStream(Encoding.ASCII.GetBytes(serverResponses));
			MemoryStream outputStream = new MemoryStream();

			Pop3Client client = new Pop3Client();
			client.Connect(new CombinedStream(inputStream, outputStream));
			client.Authenticate("test", "test");

			// Delete all the messages
			client.DeleteAllMessages();

			// Check that message 1 and message 2 was deleted
			string[] commandsFired = GetCommands(new StreamReader(new MemoryStream(outputStream.ToArray())).ReadToEnd());

			bool message1Deleted = false;
			bool message2Deleted = false;
			foreach (string commandFired in commandsFired)
			{
				if (commandFired.Equals("DELE 1"))
					message1Deleted = true;

				if (commandFired.Equals("DELE 2"))
					message2Deleted = true;
			}

			// We expect message 1 to be deleted
			Assert.IsTrue(message1Deleted);

			// We expect message 2 to be deleted
			Assert.IsTrue(message2Deleted);

			// Quit and commit
			client.Disconnect();

			const string expectedOutputAfterQuit = "QUIT";
			string outputAfterQuit = GetLastCommand(new StreamReader(new MemoryStream(outputStream.ToArray())).ReadToEnd());

			// We now expect that the client has sent the QUIT command
			Assert.AreEqual(expectedOutputAfterQuit, outputAfterQuit);
		}
예제 #9
0
 public static List<Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password)
 {
     using (Pop3Client client = new Pop3Client())
     {
         client.Connect(hostname, port, useSsl);
         client.Authenticate(username, password);
         int messageCount = client.GetMessageCount();
         List<Message> allMessages = new List<Message>(messageCount);
         for (int i = messageCount; i > 0; i--)
         {
             allMessages.Add(client.GetMessage(i));
         }
         client.Disconnect();
         return allMessages;
     }
 }
예제 #10
0
        private void test(MailPwd mp)
        {
            Pop3Client pop3Client = new Pop3Client();
            data sev = m_dicPopServers[emailToDomain(mp.email)];

            pop3Client.Connect(sev.pop3,sev.port , sev.isSSL);
            pop3Client.Authenticate(mp.email, mp.pwd);
          //  int count = pop3Client.GetMessageCount();


            int messageCount = pop3Client.GetMessageCount();
            // init index list
            List<EmailMap> em = new List<EmailMap>();

            try
            {
                string dirPath = @"data\inbox\" + mp.email;
                //serilize index.xml
               /* if (File.Exists(dirPath+"\\index.xml"))
                {
                    string confPath = dirPath + "\\index.xml";
                    var serializer = new XmlSerializer(typeof(List<EmailMap>));
                    using (var stream = File.OpenRead(confPath))
                    {
                        var other = (List<EmailMap>)(serializer.Deserialize(stream));
                        em.AddRange(other);
                        stream.Close();
                    }
                }*/
                 List<EmailMap> emTmp = new List<EmailMap>();

               
               

               // string[] paths= Directory.GetFiles(dirPath, "*", SearchOption.AllDirectories);

                List<Message> allMessages = new List<Message>(messageCount);
                int nCurCount = m_dicEmails[mp.email].Count;
                // 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 = nCurCount + 1; i <= messageCount; i++)
                {
                   // allMessages.Add(pop3Client.GetMessage(i));
                    Message msg=pop3Client.GetMessage(i);
                    string strSubject=msg.Headers.Subject;
                    string filename=pop3Client.GetMessageHeaders(i).MessageId;
                    emTmp.Add(new EmailMap { title = strSubject,file=filename });

                    //write to htm file

                    // If the selected node is not a subnode and therefore does not
                    // have a MessagePart in it's Tag property, we genericly find some content to show

                    // Find the first text/plain version
                    MessagePart plainTextPart = msg.FindFirstPlainTextVersion();
                    string strContent;
                    if (plainTextPart != null)
                    {
                        // The message had a text/plain version - show that one
                        strContent = plainTextPart.GetBodyAsText();
                    }
                    else
                    {
                        // Try to find a body to show in some of the other text versions
                        List<MessagePart> textVersions = msg.FindAllTextVersions();
                        if (textVersions.Count >= 1)
                            strContent = textVersions[0].GetBodyAsText();
                        else
                            strContent = "<<KibodWapon>> Cannot find a text version body in this message to show <<contact me qq408079058>>";
                    }
                    string strMailPath = dirPath + "\\" + filename + ".htm";

                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(strMailPath))
                    {
                        file.WriteLine("<head><meta charset=\"UTF-8\"></head>");
                        file.WriteLine(strContent);
                        file.Close();

                    }
                    File.WriteAllText(dirPath + "\\" + filename + ".eml", Encoding.ASCII.GetString(msg.RawMessage));
                   
                }
                //serilize index.xml
                m_dicEmails[mp.email].AddRange(emTmp);
                try
                {
                    string confPath =@"data\inbox\" + mp.email+"\\index.xml";
                    File.Delete(confPath);
                    var serializer = new XmlSerializer(typeof(List<EmailMap>));
                    using (var stream = File.OpenWrite(confPath))
                    {
                        serializer.Serialize(stream, em);
                        stream.Close();
                    }

                }
                catch (Exception ee)
                {
                    Console.WriteLine(ee.Message);
                }


            }
            catch (Exception UAEx)
            {
                Console.WriteLine(UAEx.Message);
            }       
             pop3Client.Disconnect();

           
        }
예제 #11
0
 /// <summary>
 /// connect to the email server by the user
 /// </summary>
 /// <returns></returns>
 public bool SetConnection()
 {
     client = new Pop3Client();
     try
     {
         client.Connect(user.pop3, user.port, user.ssl);
         try
         {
             client.Authenticate(user.email, user.password);
             return true;
         }
         catch
         {
             client.Disconnect();
         }
     }
     catch
     {
     }
     return false;
 }
        static void Main(string[] args)
        {
            bool cnx = false;
            String logMail = "*****@*****.**", logPass = "******";
            int num = 0, band = 0;
            Message message;
            String subject;
            String notif;

            Console.WriteLine("Verificando conexión a internet...");

            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface nic in nics)
            {
                if (
                    (nic.NetworkInterfaceType != NetworkInterfaceType.Loopback && nic.NetworkInterfaceType != NetworkInterfaceType.Tunnel) &&
                    nic.OperationalStatus == OperationalStatus.Up)
                {
                    networkIsAvailable = true;
                }
            }
            Console.Write("Conexión a Internet: ");
            Console.WriteLine(networkIsAvailable);
            NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);

            if (networkIsAvailable)
            {

                Console.WriteLine("Subrutina -- Lectura de Eventos Ignorar");
                Console.WriteLine("Solicitando acceso a la cuenta de correo sist_segu_2015");

                Pop3Client pop3Client = new Pop3Client();
                pop3Client.Connect("pop3.live.com", 995, true);
                pop3Client.Authenticate(logMail, logPass);
                cnx = pop3Client.Connected;

                Console.WriteLine("Solicitud de conexión a las " + DateTime.Now);
                Console.WriteLine("Conectando...");

                if (cnx == true)
                {
                    Console.WriteLine("--- Conexión exitosa ---");
                    Console.WriteLine("Se realizó conexión exitosa a las " + DateTime.Now);
                }
                else
                {
                    Console.WriteLine("--- Conexión fallida ---");
                    Console.WriteLine("Fallo de conexión a las " + DateTime.Now);
                    Console.WriteLine("Presione una tecla para salir...");
                    Console.ReadKey();
                    System.Environment.Exit(0);
                }

                num = pop3Client.GetMessageCount();
                Console.WriteLine("Usted tiene {0} correos en su bandeja", num);
                Console.WriteLine("Leyendo correos, buscando notificación IGNORAR...");
                for (int i = 1; i <= num; i++)
                {
                    message = pop3Client.GetMessage(i);
                    subject = message.ToMailMessage().Subject;
                    if (subject == "IGNORAR")
                    {
                        notif = message.ToMailMessage().Body;
                        Console.WriteLine("Contenido del correo: " + notif);
                        pop3Client.DeleteMessage(i);
                        Console.WriteLine("Se ha notificado al programa la captura del evento IGNORAR enviada por el usuario");
                        band = 1;
                    }
                    else
                    {
                        Console.WriteLine("Leyendo {0} correos...", i);
                    }
                }
                if (band == 0)
                {
                    Console.WriteLine("No se han encontrado notificaciones...");
                }

                pop3Client.Disconnect();
                Console.WriteLine("La subrutina fue desconectada a las  " + DateTime.Now);
                Console.WriteLine("Presione una tecla para salir...");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("No hay conexión a Internet, por favor verificar el inconveniente");
                Console.ReadKey();
            }
        }
        // Run by Worker, gets messages into a list.
        private static void fetchAllMessages(object sender, DoWorkEventArgs e)
        {
            try
            {
            int percentComplete;
            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server  pop.myopera.com
                client.Connect("pop.myopera.com", 995, true);

                // Authenticate ourselves towards the server /HejHej
                client.Authenticate(Properties.Settings.Default.UserName, Properties.Settings.Default.Password);

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

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

                // 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));
                    percentComplete = Convert.ToInt16((Convert.ToDouble(allMessages.Count) / Convert.ToDouble(messageCount)) * 100);
                    (sender as BackgroundWorker).ReportProgress(percentComplete);
                }
                // Now return the fetched messages to e
                e.Result = allMessages;
                client.Disconnect();
            }
            }
            catch (Exception ex)
            {

                MessageBox.Show("Connection Failed, maybe you forgot to set a user in Settings?" + ex.Message);
            }
        }
예제 #14
0
 private void RefreshingThread()
 {
     Pop3Client client = new Pop3Client();
     client.Connect(config.host, config.port, config.ssl);
     client.Authenticate(config.login, config.password);
     List<string> uids;
     int length = 0;
     while(true)
     {
         uids = client.GetMessageUids();
         length = uids.Count;
         for (int i = 0; i < length; i++)
         {
             string currentUidOnServer = uids[i];
             if (!readMails.Contains(currentUidOnServer))
             {
                 unreadMails++;
                 // Add the message to the new messages
                 readMails.Add(uids[i]);
             }
         }
         //outLabel.Text = unreadMails.ToString();
         Thread.Sleep(config.msRefreshDelay);
     }
     client.Disconnect();
 }
예제 #15
0
        public  void crackProc()
        {
            Pop3Client pop3Client = new Pop3Client();
            do
            {

                string strPop3;
                int port;
                string strUser;
                string strPwd;
                bool isSLL;
                m_gM.WaitOne();
                if (m_nCreackingIndex > listCheckableEmails.Count - 1)//finished
                {
                    m_gM.ReleaseMutex();
                    return;
                }
                strUser = listCheckableEmails[m_nCreackingIndex].email;
                strPwd = listCheckableEmails[m_nCreackingIndex].pwd;
                //check form invalide emails
                string strDomain;
                try
                {
                    strDomain = strUser.Split('@')[1];
                }
                catch (Exception ex)
                {

                    m_nCreackingIndex++;
                    m_gM.ReleaseMutex();
                    return;
                }
                //try dic
                try
                {

                    strPop3 = m_dicPopServers[strDomain].pop3;
                    port = m_dicPopServers[strDomain].port;
                    isSLL = m_dicPopServers[strDomain].isSSL;
                }
                catch (Exception ex)
                {
                    m_nCreackingIndex++;
                    m_gM.ReleaseMutex();

                    return;
                }

                m_nCreackingIndex++;

                m_gM.ReleaseMutex();
                try
                {

                    if (pop3Client.Connected)
                        pop3Client.Disconnect();
                    pop3Client.Connect(strPop3, port, isSLL);
                    pop3Client.Authenticate(strUser, strPwd);
                    int count = pop3Client.GetMessageCount();
                    Console.WriteLine(count);
                    int i = m_nCreackingIndex - 1;
                    //update 
                    m_gM.WaitOne();
                    SetText(labelStatus, "成功登陆:" + strUser + "请等待!!!~");
                    //labelStatus.Text = "成功登陆:" + strUser + "请等待!!!~";
                    if (m_nFinished + 1 == listCheckableEmails.Count)//finished
                    {
                        SetText(labelStatus, "恭喜检测完成。。~");
                        MessageBox.Show("恭喜检测完成");
                        //labelStatus.Text = "恭喜检测完成。。~";
                        SetButton(buttonEnd, false);
                        SetButton(buttonStart, true);
                        SetButton(buttonPause, false);

                        SetButton(buttonAllTrans, true);
                        SetButton(buttonExpCracked, true);
                        SetButton(buttoneExpUnknown, true);
                       // buttonEnd.Enabled = false;
                        //buttonStart.Enabled = true;
                        //buttonPause.Enabled = false;
                    }
                    if (!listLogined.Exists(x => x.email == strUser)) //add
                    {
                        Console.WriteLine(strUser+" "+strPwd+" not exist");
                      //  Console.WriteLine(listCheckableEmails[i].email);
                        ListViewItem item1 = new ListViewItem(strUser, 0);
                        item1.SubItems.Add(strPwd);
                        AddItemToListView(listViewCreacked, item1);
                       // listViewCreacked.Items.Add(item1);
                        //listViewCreacked.Update();
                        listLogined.Add(new MailPwd() { email = strUser, pwd = strPwd });
                    }
                   
                    m_gM.ReleaseMutex();

                }
                /*catch (InvalidLoginException)
                {
                    MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication");
                }
                catch (PopServerNotFoundException)
                {
                    MessageBox.Show(this, "The server could not be found", "POP3 Retrieval");
                }
                catch (PopServerLockedException)
                {
                    MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked");
                }
                catch (LoginDelayException)
                {
                    MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay");
                }*/
                catch (Exception exxx)
                {
                    int i = m_nCreackingIndex - 1;
                    m_gM.WaitOne();
                    SetText(labelStatus, "Error occurred retrieving mail: " + exxx.Message);
                    //labelStatus.Text = "Error occurred retrieving mail: " + exxx.Message;
                    if (!listloginFailed.Exists(x => x.email == strUser)) //add
                      {
                          Console.WriteLine(strUser+" not exist");
                          listloginFailed.Add(new MailPwd() { email = strUser,pwd = strPwd });
                          ListViewItem item1 = new ListViewItem(strUser, 0);
                          item1.SubItems.Add(strPwd);
                          AddItemToListView(listViewUnknown, item1);
                         // listViewUnknown.Items.Add(item1);
                          //listViewUnknown.Update();
                      }

                      i = m_nCreackingIndex;
                       SetText(labelStatus,"已经完成" + i + "个,共计:" + listCheckableEmails.Count + "个,请耐心等待。。");
                      //labelStatus.Text = "已经完成" + i + "个,共计:" + listCheckableEmails.Count + "个,请耐心等待。。";

                      if (m_nFinished + 1 == listCheckableEmails.Count)//finished
                      {
                          SetText(labelStatus, "恭喜检测完成。~~~~~");
                          MessageBox.Show("恭喜检测完成");
                          //labelStatus.Text = "恭喜检测完成。~~~~~";
                          SetButton(buttonEnd, false);
                          SetButton(buttonStart, true);
                          SetButton(buttonPause, false);
                          SetButton(buttonAllTrans, true);
                          SetButton(buttonExpCracked, true);
                          SetButton(buttoneExpUnknown, true);

                          //buttonEnd.Enabled = false;
                         // buttonStart.Enabled = true;
                         // buttonPause.Enabled = false;
                      }
                      
                    m_gM.ReleaseMutex();

                }
                finally
                {
                    // update stuatus
                    m_gM.WaitOne();
                    m_nFinished++;

                    m_gM.ReleaseMutex();
                }
                Thread.Sleep(m_nDelay * 1000);
            } while (true);
        }
예제 #16
0
    ///////////////////////////////////////////////////////////////////////
    protected async void fetch_messages(string user, string password, int projectid)
    {

        List<string> messages = null;
        Regex regex = new Regex("\r\n");
        using (Pop3Client client = new Pop3Client())
        {
            try
            {
                write_line("****connecting to server:");
                int port = 110;
                if (Pop3Port != "")
                {
                    port = Convert.ToInt32(Pop3Port);
                }

                bool use_ssl = false;
                if (Pop3UseSSL != "")
                {
                    use_ssl = Pop3UseSSL == "1" ? true : false;
                }

                write_line("Connecting to pop3 server");
                client.Connect(Pop3Server, port, use_ssl);
                write_line("Autenticating");
                client.Authenticate(user, password);


                write_line("Getting list of documents");
                messages = client.GetMessageUids();
            }
            catch (Exception e)
            {
                write_line("Exception trying to talk to pop3 server");
                write_line(e);
                return;
            }


            int message_number = 0;


            // loop through the messages
            for (int i = 0; i < messages.Count; i++)
            {
                heartbeat_datetime = DateTime.Now; // because the watchdog is watching

                if (state != service_state.STARTED)
                {
                    break;
                }

                // fetch the message

                write_line("Getting Message:" + messages[i]);
                message_number = Convert.ToInt32(messages[i]);
                Message mimeMessage = null;

                try
                {
                    mimeMessage = client.GetMessage(message_number);
                }
                catch (Exception exception)
                {
                    write_to_log("Error getting message");
                    write_to_log(exception.ToString());
                    continue;
                }


                // for diagnosing problems
                if (MessageOutputFile != "")
                {
                    File.WriteAllBytes(MessageOutputFile, mimeMessage.RawMessage);
                }

                // break the message up into lines

                string from = mimeMessage.Headers.From.Address;
                string subject = mimeMessage.Headers.Subject;




                write_line("\nFrom: " + from);

                write_line("Subject: " + subject);

                if (!string.IsNullOrEmpty(SubjectMustContain) && subject.IndexOf(SubjectMustContain, StringComparison.OrdinalIgnoreCase) < 0)
                {
                    write_line("skipping because subject does not contain: " + SubjectMustContain);
                    continue;
                }

                bool bSkip = false;
                foreach (string subjectCannotContainString in SubjectCannotContainStrings)
                {
                    if (!string.IsNullOrEmpty(subjectCannotContainString))
                    {
                        if (subject.IndexOf(subjectCannotContainString, StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            write_line("skipping because subject cannot contain: " + subjectCannotContainString);
                            bSkip = true;
                            break;  // done checking, skip this message
                        }
                    }
                }

                if (bSkip)
                {
                    continue;
                }

                if (!string.IsNullOrEmpty(FromMustContain) && from.IndexOf(FromMustContain, StringComparison.OrdinalIgnoreCase) < 0)
                {
                    write_line("skipping because from does not contain: " + FromMustContain);
                    continue; // that is, skip to next message
                }

                foreach (string fromCannotContainStrings in FromCannotContainStrings)
                {
                    if (!string.IsNullOrEmpty(fromCannotContainStrings))
                    {
                        if (from.IndexOf(fromCannotContainStrings, StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            write_line("skipping because from cannot contain: " + fromCannotContainStrings);
                            bSkip = true;
                            break; // done checking, skip this message
                        }
                    }
                }

                if (bSkip)
                {
                    continue;
                }

                write_line("calling insert_bug.aspx");

                bool useBugId = false;

                // Try to parse out the bugid from the subject line
                string bugidString = TrackingIdString;
                if (string.IsNullOrEmpty(TrackingIdString))
                {
                    bugidString = "DO NOT EDIT THIS:";
                }

                int pos = subject.IndexOf(bugidString, StringComparison.OrdinalIgnoreCase);

                if (pos >= 0)
                {
                    // position of colon
                    pos = subject.IndexOf(":", pos);
                    pos++;
                    // position of close paren
                    int pos2 = subject.IndexOf(")", pos);
                    if (pos2 > pos)
                    {
                        string bugid_string = subject.Substring(pos, pos2 - pos);
                        write_line("BUGID=" + bugid_string);
                        try
                        {
                            int bugid = Int32.Parse(bugid_string);
                            useBugId = true;
                            write_line("updating existing bug " + Convert.ToString(bugid));
                        }
                        catch (Exception e)
                        {
                            write_line("bugid not numeric " + e.Message);
                        }
                    }
                }

                
                // send request to web server
                try
                {
                    HttpClientHandler handler = new HttpClientHandler
                    {
                        AllowAutoRedirect = true,
                        UseCookies = true,
                        CookieContainer = new CookieContainer()
                    };
                    using (var httpClient = new HttpClient(handler))
                    {
                        var loginParameters = new Dictionary<string, string>
                        {
                           { "user", ServiceUsername },
                           { "password", ServicePassword }
                        };

                        HttpContent loginContent = new FormUrlEncodedContent(loginParameters);
                        var loginResponse = await httpClient.PostAsync(LoginUrl, loginContent);
                        loginResponse.EnsureSuccessStatusCode();

                        string rawMessage = Encoding.Default.GetString(mimeMessage.RawMessage);
                        var postBugParameters = new Dictionary<string, string>
                        {
                           { "projectId", Convert.ToString(projectid) },
                           { "fromAddress", from },
                           { "shortDescription", subject},
                           { "message", rawMessage}
                           //Any other paramters go here
                        };
                        if (useBugId)
                        {
                            postBugParameters.Add("bugId", bugidString);
                        }

                        HttpContent bugContent = new FormUrlEncodedContent(postBugParameters);
                        var postBugResponse = await httpClient.PostAsync(InsertBugUrl, bugContent);

                        postBugResponse.EnsureSuccessStatusCode();
                    }
                    if (MessageInputFile == "" && DeleteMessagesOnServer == "1")
                    {
                        write_line("sending POP3 command DELE");
                        client.DeleteMessage(message_number);
                    }
                }
                catch (Exception e)
                {
                    write_line("HttpWebRequest error url=" + InsertBugUrl);
                    write_line(e);
                    write_line("Incrementing total error count");
                    total_error_count++;
                }

                // examine response
                if (total_error_count > TotalErrorsAllowed)
                {
                    write_line("Stopping because total error count > TotalErrorsAllowed");
                    stop();
                }


            }  // end for each message


            if (MessageInputFile == "")
            {
                write_line("\nsending POP3 command QUIT");
                client.Disconnect();
            }
            else
            {
                write_line("\nclosing input file " + MessageInputFile);
            }
        }
    }
        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();
                }
            }
        }
		public void TestDeleteMessage()
		{
			const string welcomeMessage = "+OK";
			const string okUsername = "******";
			const string okPassword = "******";
			const string deleteResponse = "+OK"; // Message was deleted
			const string quitAccepted = "+OK";
			const string serverResponses = welcomeMessage + "\r\n" + okUsername + "\r\n" + okPassword + "\r\n" + deleteResponse + "\r\n" + quitAccepted + "\r\n";

			Stream inputStream = new MemoryStream(Encoding.ASCII.GetBytes(serverResponses));
			MemoryStream outputStream = new MemoryStream();

			Pop3Client client = new Pop3Client();
			client.Connect(new CombinedStream(inputStream, outputStream));
			client.Authenticate("test", "test");

			client.DeleteMessage(5);

			const string expectedOutput = "DELE 5";
			string output = GetLastCommand(new StreamReader(new MemoryStream(outputStream.ToArray())).ReadToEnd());

			// We expected that the last command is the delete command
			Assert.AreEqual(expectedOutput, output);

			client.Disconnect();

			const string expectedOutputAfterQuit = "QUIT";
			string outputAfterQuit = GetLastCommand(new StreamReader(new MemoryStream(outputStream.ToArray())).ReadToEnd());

			// We now expect that the client has sent the QUIT command
			Assert.AreEqual(expectedOutputAfterQuit, outputAfterQuit);
		}
        private void button2_Click_1(object sender, EventArgs e)
        {
            try
            {
                Pop3Client pop3c = new Pop3Client();            //Starts the POP3 Client
                pop3c.Connect("pop.gmail.com", 995, true);      //Uses port 995 and enabled SSL to connect to pop.gmail.com
                richTextBox2.Text += "-Connected\n";            //Sends to console the confirmation
                pop3c.Authenticate(from, p);                    //Authenticates using private fields
                richTextBox2.Text += "--Authenticated\n";       //Sends to console the confirmation
                int msgCount = pop3c.GetMessageCount();         //msgCount = number of messages on POP3 server.
                richTextBox2.Text += "---There are " + msgCount.ToString() + " following messages in the inbox for " + from + "\n";
                //Shows the msgCount
                bool isThereMail = checkForMail(pop3c);         //Checks msgCount for the inbox
                if (isThereMail)    //If there's mail
                {
                    richTextBox2.Text += "----This is the email for message 1: \n" + pop3c.GetMessage(1).MessagePart.GetBodyAsText();
                    richTextBox2.Text += "---Now there are " + (msgCount - 1).ToString() + " messages.\n";
                }
                else
                {
                    label3.Text = "No Mail Yet.";           //Message to window
                }
                pop3c.Disconnect();
                richTextBox2.Text += "-Disconnected\n";     //Confirm to console

            }
            catch (Exception ex)
            {
                richTextBox2.Text += "-Error - See Message\n";  //Error to console
                label3.Text = ex.Message.ToString();        //Message to window
            }
        }
예제 #20
0
        public static List<MailParts> CheckInbox(ref string resultTopic, ref string resultMsg)
        {
            if (resultMsg == null) throw new ArgumentNullException("resultMsg");
            //Dictionary<int, Message> messages = new Dictionary<int, Message>();
            Pop3Client pop3Client = new Pop3Client();
            List<MailParts> querys = new List<MailParts>();

            try
            {
                if (pop3Client.Connected)
                {
                    pop3Client.Disconnect();
                }

                pop3Client.Connect(Settings.POPserver, Settings.POPport, true);
                pop3Client.Authenticate(Settings.EmailUser, Settings.EmailPass);

                int count = pop3Client.GetMessageCount();

                for (int i = count; i >= 1; i -= 1)
                {
                    try
                    {
                        Message message = pop3Client.GetMessage(i);
                        //messages.Add(i, message);

                        if (message.Headers.Subject.Equals("Aramis-IT: Sending query"))
                        {
                            if (message.MessagePart != null &&
                                message.MessagePart.IsText)
                            {
                                string[] parts = message.MessagePart.GetBodyAsText().Split(
                                    new[] { ParameterTag },
                                    StringSplitOptions.RemoveEmptyEntries);
                                MailParts mail = new MailParts { Parameter = new List<SQLiteParameter>() };
                                bool isFirst = true;

                                foreach (string part in parts)
                                {
                                    if (!isFirst)
                                    {
                                        string[] p = part.Split('=');
                                        mail.Parameter.Add(new SQLiteParameter(p[0], p[1].Replace("\r\n", "")));
                                    }
                                    else
                                    {
                                        isFirst = false;
                                        mail.Command = part;
                                    }
                                }

                                querys.Add(mail);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(
                            "TestForm: Message fetching failed: " + e.Message + "\r\n" +
                            "Stack trace:\r\n" +
                            e.StackTrace);
                    }
                }

            }
            catch (InvalidLoginException)
            {
                resultTopic = "POP3 Server Authentication";
                resultMsg = "The server did not accept the user credentials!";
                return null;
            }
            catch (PopServerNotFoundException)
            {
                resultTopic = "POP3 Retrieval";
                resultMsg = "The server could not be found";
                return null;
            }
            catch (PopServerLockedException)
            {
                resultTopic = "POP3 Account Locked";
                resultMsg = "The mailbox is locked. It might be in use or under maintenance.";
                return null;
            }
            catch (LoginDelayException)
            {
                resultTopic = "POP3 Account Login Delay";
                resultMsg = "Login not allowed. Server enforces delay between logins.";
                return null;
            }
            catch (Exception e)
            {
                resultTopic = "POP3 Retrieval";
                resultMsg = "Error occurred retrieving mail. " + e.Message;
                return null;
            }
            finally
            {
                if(pop3Client.Connected)
                {
                    pop3Client.Disconnect();
                }
            }

            //foreach (Message msg in messages.Values)
            //{
            //    if (msg.MessagePart != null &&
            //        msg.MessagePart.MessageParts != null &&
            //        msg.MessagePart.MessageParts.Count >= 1 &&
            //        msg.MessagePart.MessageParts[0].IsText)
            //    {
            //        string body = msg.MessagePart.MessageParts[0].GetBodyAsText();
            //        //querys.Add(body);
            //    }
            //}

            return querys;
        }
예제 #21
0
 private void получитьСообщение(object sender, EventArgs e)
 {
     Pop3Client клиентДляПолученияСообщения = new Pop3Client();
     клиентДляПолученияСообщения.Connect("pop." + аккаунт.Адрес.Host, 995, true);
     клиентДляПолученияСообщения.Authenticate(аккаунт.Адрес.Address, аккаунт.Пароль);
     if (клиентДляПолученияСообщения.Connected)
     {
         полученноеСообщение = клиентДляПолученияСообщения.GetMessage(клиентДляПолученияСообщения.GetMessageCount()).ToMailMessage();
         полеОтображенияСообщения.AppendText("От: " + полученноеСообщение.From.Address);
         полеОтображенияСообщения.AppendText("\nТема: " + полученноеСообщение.Subject);
         полеОтображенияСообщения.AppendText("\nСообщение: " + полученноеСообщение.Body);
         клиентДляПолученияСообщения.Disconnect();
         if (полученноеСообщение.Body.IndexOf("<!MSG_ENCRYPT!>") != -1)
             button4.Enabled = true;
     }
 }