Пример #1
0
        public void TestArgumentExceptions()
        {
            using (var client = new Pop3Client()) {
                var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);

                // Connect
                Assert.Throws <ArgumentNullException> (() => client.Connect((Uri)null));
                Assert.Throws <ArgumentNullException> (async() => await client.ConnectAsync((Uri)null));
                Assert.Throws <ArgumentNullException> (() => client.Connect(null, 110, false));
                Assert.Throws <ArgumentNullException> (async() => await client.ConnectAsync(null, 110, false));
                Assert.Throws <ArgumentException> (() => client.Connect(string.Empty, 110, false));
                Assert.Throws <ArgumentException> (async() => await client.ConnectAsync(string.Empty, 110, false));
                Assert.Throws <ArgumentOutOfRangeException> (() => client.Connect("host", -1, false));
                Assert.Throws <ArgumentOutOfRangeException> (async() => await client.ConnectAsync("host", -1, false));
                Assert.Throws <ArgumentNullException> (() => client.Connect(null, 110, SecureSocketOptions.None));
                Assert.Throws <ArgumentNullException> (async() => await client.ConnectAsync(null, 110, SecureSocketOptions.None));
                Assert.Throws <ArgumentException> (() => client.Connect(string.Empty, 110, SecureSocketOptions.None));
                Assert.Throws <ArgumentException> (async() => await client.ConnectAsync(string.Empty, 110, SecureSocketOptions.None));
                Assert.Throws <ArgumentOutOfRangeException> (() => client.Connect("host", -1, SecureSocketOptions.None));
                Assert.Throws <ArgumentOutOfRangeException> (async() => await client.ConnectAsync("host", -1, SecureSocketOptions.None));

                Assert.Throws <ArgumentNullException> (() => client.Connect(null, "host", 110, SecureSocketOptions.None));
                Assert.Throws <ArgumentException> (() => client.Connect(socket, "host", 110, SecureSocketOptions.None));

                // Authenticate
                Assert.Throws <ArgumentNullException> (() => client.Authenticate(null));
                Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(null));
                Assert.Throws <ArgumentNullException> (() => client.Authenticate(null, "password"));
                Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync(null, "password"));
                Assert.Throws <ArgumentNullException> (() => client.Authenticate("username", null));
                Assert.Throws <ArgumentNullException> (async() => await client.AuthenticateAsync("username", null));
            }
        }
Пример #2
0
        /// <summary>
        /// Let the <see cref="Pop3Client"/> authenticate.
        /// </summary>
        /// <param name="extraReaderInput">Extra input that the server may read off the reader.  String is convert to bytes using ASCII encoding</param>
        private void Authenticate(string extraReaderInput = "")
        {
            // Always allow connect, which is the first ok
            // And always allow authenticate
            string readerInput  = "+OK\r\n+OK\r\n+OK\r\n" + extraReaderInput;
            Stream inputStream  = new MemoryStream(Encoding.ASCII.GetBytes(readerInput));
            Stream outputStream = new MemoryStream();

            // Authenticate with the client
            Client.Connect(new CombinedStream(inputStream, outputStream));
            Client.Authenticate(RandomString, RandomString);
        }
Пример #3
0
        public void LoginForm_PasswordRestoreWithValidEmail()
        {
            using (IWebDriver driver = new FirefoxDriver())
            {
                driver.Navigate().GoToUrl(gg);

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

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

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

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

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

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

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

                Assert.IsFalse(from.HasValidMailAddress && from.Address.Equals("*****@*****.**") && "Восстановление пароля на Gama - Gama".Equals(subject), "Письмо не пришло");
            }
        }
Пример #4
0
        /// <summary>
        /// POP3接收邮件
        /// </summary>
        /// <param name="FromAccount">邮箱账户</param>
        /// <param name="FromPassword">邮箱密码</param>
        /// <returns></returns>
        public static IList <ReceiveEmailModel> ReceivePop3Email(string FromAccount, string FromPassword)
        {
            List <ReceiveEmailModel> receiveEmailList = new List <ReceiveEmailModel>();

            using (var client = new Pop3Client())
            {
                // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect(PopServer, PopPort, false);

                client.Authenticate(FromAccount, FromPassword);

                for (int i = 0; i < client.Count; i++)
                {
                    var message = client.GetMessage(i);

                    ReceiveEmailModel receiveEmailModel = new ReceiveEmailModel();

                    receiveEmailModel.FromAddress = message.From[0].Name;

                    receiveEmailModel.Date = message.Date.DateTime;

                    receiveEmailModel.Subject = message.Subject;

                    receiveEmailModel.Body = message.TextBody;

                    receiveEmailList.Add(receiveEmailModel);
                }
                client.Disconnect(true);
            }
            return(receiveEmailList);
        }
Пример #5
0
        public IEnumerable <MailMessage> Retrieve(string pMailAddress, string pPassword, int pOffset = 0, int pWindow = 0)
        {
            try
            {
                if (pWindow == 0)
                {
                    return(new List <MailMessage>());
                }

                Pop3Client mPop3Client = new Pop3Client();
                mPop3Client.Connect(this.iProtocol.Host, this.iProtocol.Port, this.iProtocol.SSL);
                mPop3Client.Authenticate(pMailAddress, pPassword);

                if (pWindow > mPop3Client.GetMessageCount() || pWindow == -1)
                {
                    pWindow = mPop3Client.GetMessageCount();
                }

                return(mPop3Client.GetMessageCount() > 0 ?
                       Enumerable.Range(pOffset + 1, pWindow)
                       .Select(bIndex => this.ProjectToMailMessage(mPop3Client.GetMessage(bIndex)))
                       .ToList()
                    : new List <MailMessage>());
            }
            catch (Exception bException)
            {
                throw new FailOnRetrieve("Error en Pop3, posible problema con la conexión, autenticación o recupero de correos. Vea excepción interna.", bException);
            }
        }
        private static void FetchMessages(string host, int port, bool ssl, string username, string password)
        {
            //3rd party Pop3 library
            using (Pop3Client client = new Pop3Client())
            {
                //Connect and authenticate to Pop3 specifying our own certificate validator function to bypass self signed certificate
                client.Connect(host, port, ssl, 5000, 5000, certificateValidator: certificateValidator);
                client.Authenticate(username, password);

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

                //Create List of type Message to hold the messages
                List <Message> allMessages = new List <Message>(messageCount);
                if (messageCount == 0)
                {
                    //If there are no messages
                    Console.WriteLine("No messages in inbox");
                }
                for (int i = messageCount; i > 0; i--)
                {
                    //For every message add it to our List
                    allMessages.Add(client.GetMessage(i));
                }

                foreach (Message message in allMessages)
                {
                    //For every message in our list convert it to a .NET MailMessage and print the Subject
                    Console.WriteLine("Found Message:" + message.ToMailMessage().Subject);
                }
            }
        }
Пример #7
0
        public bool DeleteMessageByMessageId(string messageId)
        {
            // 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);// Get the number of messages on the POP3 server
                int messageCount = client.GetMessageCount();

                // Run trough each of these messages and download the headers
                for (int messageItem = messageCount; messageItem > 0; messageItem--)
                {
                    // If the Message ID of the current message is the same as the parameter given, delete that message
                    if (client.GetMessageHeaders(messageItem).MessageId == messageId)
                    {
                        // Delete
                        client.DeleteMessage(messageItem);
                        return(true);
                    }
                }

                // We did not find any message with the given messageId, report this back
                return(false);
            }
        }
Пример #8
0
        /// <summary>
        /// Default Constructor
        /// </summary>
        public EmailTicketGeneration()
        {
            //Instance creation of calls object
            _email = new Emails();
            //Instance of Pop client
            _client = new Pop3Client();

            //Connect to the server
            _client.Connect(CommonProperty.MIMEHost, CommonProperty.MIMEPort, true);

            //Authenticate ourselves towards the server
            _client.Authenticate(CommonProperty.SupportEMailAddress, CommonProperty.Password);

            //Number of mail in inbox
            CommonProperty.GlobalEmailCount = _client.GetMessageCount();

            //If service stopped in between last email count takes care of missed emails
            if (File.Exists(CommonProperty.LastEmailCountPath))
            {
                StreamReader sr        = new StreamReader(CommonProperty.LastEmailCountPath);
                int          testCount = Convert.ToInt32(sr.ReadLine());
                if (testCount != CommonProperty.GlobalEmailCount)
                {
                    CommonProperty.GlobalEmailCount = testCount;
                }
            }

            InitializeComponent();
        }
Пример #9
0
        private static void fetchAllMessages(object sender, DoWorkEventArgs e)
        {
            int percentComplete;


            using (Pop3Client client = new Pop3Client())
            {
                client.Connect("pop.gmail.com", 995, true);


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


                int messageCount = client.GetMessageCount();


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


                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);
                }

                e.Result = allMessages;
            }
        }
Пример #10
0
        private static List <OpenPop.Mime.Message> FetchAllMessages()
        {
            using (Pop3Client client = new Pop3Client())
            {
                // 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 <OpenPop.Mime.Message> allMessages = new List <OpenPop.Mime.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
                for (int i = messageCount; i > 0; i--)
                {
                    allMessages.Add(client.GetMessage(i));
                    //client.GetMessage(i).Headers.Subject - так получаем тему письма
                }

                // Now return the fetched messages
                return(allMessages);
            }
        }
Пример #11
0
        public static List <MessageModel> GetEmails()
        {
            Pop3Client          objPop3Client = new Pop3Client();
            MessageModel        message       = new MessageModel();
            List <MessageModel> lMessageModel = new List <MessageModel>();

            string host     = "";
            string user     = "";
            string password = "";
            int    port     = 110;
            bool   useSsl   = false;

            try
            {
                objPop3Client.Connect(host, port, useSsl);
                objPop3Client.Authenticate(user, password);

                for (int i = 1; i <= objPop3Client.GetMessageCount(); i++)
                {
                    message = GetEmailContent(i, ref objPop3Client);
                    if (message != null)
                    {
                        lMessageModel.Add(message);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                objPop3Client.Disconnect();
            }
            return(lMessageModel);
        }
Пример #12
0
        public string GetLastMail(AccountData account)
        {
            for (int i = 0; i < 30; i++)
            {
                Pop3Client pop3 = new Pop3Client("localhost", 110, account.Name, account.Password, false);
                pop3.Connect();
                pop3.Authenticate();

                if (pop3.GetMessageCount() > 0)
                {
                    MailMessage message = pop3.GetMessage(1);

                    string body = message.Body;
                    pop3.DeleteMessage(1);
                    pop3.LogOut();
                    return(message.Body);
                }
                else
                {
                    System.Threading.Thread.Sleep(3000);
                }
            }

            return(null);
        }
Пример #13
0
        public JsonResult GetMail()
        {
            Pop3Client client = new Pop3Client();

            client.Connect("pop.asia.secureserver.net", 110, false);
            client.Authenticate("*****@*****.**", "passward");
            var             count    = client.GetMessageCount();
            List <MailData> maildata = new List <MailData>();
            MailData        mail     = null;

            //var datamail1 = client.GetMessage(1);
            //var datamail2= client.GetMessage(2);
            //var datamail3 = client.GetMessage(3);
            //var datamail4 = client.GetMessage(4);
            for (int i = 2; i <= count; i++)
            {
                mail             = new MailData();
                mail.MailHeading = client.GetMessage(i).Headers.Subject.ToString();
                //mail.MailBody = (client.GetMessage(i)).MessagePart.GetBodyAsText().ToString();
                maildata.Add(mail);
            }
            if (count > 0)
            {
                for (int i = 1; i < count; i++)
                {
                    mail = new MailData();
                    //var datamail  =  client.GetMessage(i);
                    // mail.MailHeading = datamail.RawMessage.ToString();
                }
            }

            var message = client.GetMessage(count);

            return(Json(message, JsonRequestBehavior.AllowGet));
        }
Пример #14
0
        public List <MensagemEmail> ReceiveEmail(int maxCount = 10)
        {
            using (var emailClient = new Pop3Client())
            {
                emailClient.Connect(_emailConfiguracao.PopServer, _emailConfiguracao.PopPort, true);

                emailClient.AuthenticationMechanisms.Remove("XOAUTH2");

                emailClient.Authenticate(_emailConfiguracao.PopUsername, _emailConfiguracao.PopPassword);

                List <MensagemEmail> emails = new List <MensagemEmail>();
                for (int i = 0; i < emailClient.Count && i < maxCount; i++)
                {
                    var message      = emailClient.GetMessage(i);
                    var emailMessage = new MensagemEmail
                    {
                        Conteudo = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody,
                        Assunto  = message.Subject
                    };
                    emailMessage.ParaEndereco.AddRange(message.To.Select(x => (MailboxAddress)x).Select(x => new EnderecoEmail {
                        Endereco = x.Address, Nome = x.Name
                    }));
                    emailMessage.DeEndereco.AddRange(message.From.Select(x => (MailboxAddress)x).Select(x => new EnderecoEmail {
                        Endereco = x.Address, Nome = x.Name
                    }));
                }

                return(emails);
            }
        }
        /// <summary>
        /// The receive mess.
        /// </summary>
        public static void ReceiveMess(IReceivingManager receivingManager, ILogger logger)
        {
            string mailServer   = ConfigurationManager.AppSettings["MailServer"];
            int    mailPort     = Convert.ToInt32(ConfigurationManager.AppSettings["MailPort"]);
            string mailLogin    = ConfigurationManager.AppSettings["MailLogin"];
            string mailPassword = Encoding.Unicode.GetString(Convert.FromBase64String(ConfigurationManager.AppSettings["MailPassword"]));

            var client = new Pop3Client();

            try
            {
                client.Connect(mailServer, mailPort, false);
                client.Authenticate(mailLogin, mailPassword);

                List <Header> msgs = GetMsgsForSB(client);
                foreach (Header header in msgs)
                {
                    if (!header.stored)
                    {
                        if (header.msg.Headers.Subject.Contains("OUT_OF"))
                        {
                            Header        tmpHeader = header;
                            List <Header> curMsgs   =
                                msgs.Where(
                                    msg => msg.msg.Headers.Subject.Contains(tmpHeader.msg.Headers.Subject.Split('_')[4]))
                                .ToList();

                            if (curMsgs.Count() == Convert.ToInt32(header.msg.Headers.Subject.Split('_')[8]))
                            {
                                SaveMsgToDBFromManyAttachs(curMsgs, receivingManager);

                                foreach (Header msg in curMsgs)
                                {
                                    msg.stored = true;
                                }
                            }
                        }
                        else
                        {
                            SaveMsgToDB(header.msg, header.msg.Headers.Subject.Split('_')[4], receivingManager);

                            header.stored = true;
                        }
                    }
                }

                DeleteStoredMessages(client, msgs);
            }
            catch (Exception e)
            {
                logger.LogUnhandledException(e);
            }
            finally
            {
                if (client.Connected)
                {
                    client.Disconnect();
                }
            }
        }
Пример #16
0
        public List <EmailMessage> ReceiveEmail(int maxCount = 10)
        {
            using (var emailClient = new Pop3Client())
            {
                emailClient.Connect(_emailConfiguration.PopServer, _emailConfiguration.PopPort, true);

                emailClient.AuthenticationMechanisms.Remove("XOAUTH2");

                emailClient.Authenticate(_emailConfiguration.PopUsername, _emailConfiguration.PopPassword);

                List <EmailMessage> emails = new List <EmailMessage>();
                for (int i = 0; i < emailClient.Count && i < maxCount; i++)
                {
                    var message      = emailClient.GetMessage(i);
                    var emailMessage = new EmailMessage
                    {
                        Content = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody,
                        Subject = message.Subject
                    };
                    emailMessage.ToAddresses.AddRange(message.To.Select(x => (MailboxAddress)x).Select(x => new EmailAddress {
                        Address = x.Address, Name = x.Name
                    }));
                    emailMessage.FromAddresses.AddRange(message.From.Select(x => (MailboxAddress)x).Select(x => new EmailAddress {
                        Address = x.Address, Name = x.Name
                    }));
                }

                return(emails);
            }
        }
Пример #17
0
 public bool TestConnection(string server, int port, bool use_ssl, string username, string password)
 {
     try
     {
         if (pop3Client.Connected)
         {
             pop3Client.Disconnect();
         }
         pop3Client.Connect(server, port, use_ssl);
         pop3Client.Authenticate(username, password);
         return(true);
     }
     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 e)
     {
         MessageBox.Show(this, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval");
     }
     return(false);
 }
Пример #18
0
        /// <summary>
        /// gets all unread email from Gmail and returns a List of System.Net.Email.MailMessage Objects
        /// </summary>
        /// <param name="username">Gmail Login</param>
        /// <param name="password">mail Password</param>
        public static List <MailMessage> FetchAllUnreadMessages(string username, string password)
        {
            List <MailMessage> mlist = new List <MailMessage>();

            // The client disconnects from the server when being disposed

            try
            {
                using (Pop3Client client = new Pop3Client())
                {
                    // Connect to the server
                    client.Connect("pop.gmail.com", 995, true);

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

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



                    for (int x = messageCount; x > 0; x--)
                    {
                        Message m = new Message(client.GetMessage(x).RawMessage);
                        System.Net.Mail.MailMessage mm = m.ToMailMessage();

                        mlist.Add(mm);
                    }
                    return(mlist);
                }
            }
            catch { return(mlist); }
        }
Пример #19
0
        public void TestMethod1()
        {
            /*AccountData account = new AccountData()
             * {
             *  Name = "user",
             *  Password = "******"
             * };
             * Assert.IsFalse(app.James.Verify(account));
             * app.James.Add(account);
             * Assert.IsTrue(app.James.Verify(account));
             * app.James.Delete(account);
             * Assert.False(app.James.Verify(account));*/

            for (int i = 0; i < 20; i++)
            {
                Pop3Client pop3 = new Pop3Client("localhost", 110, "user1", "password", false);
                pop3.Connect();
                pop3.Authenticate();
                if (pop3.GetMessageCount() > 0)
                {
                    ReadOnlyMailMessage message = pop3.GetMessage(1);
                    string body = message.Body;
                    pop3.DeleteMessage(1);
                    System.Console.Out.WriteLine(body);
                }
                else
                {
                    System.Threading.Thread.Sleep(3000);
                }
            }
        }
Пример #20
0
        public List <EmailMessage> ReceiveEmail(int maxCount = 10)
        {
            using (var emailClient = new Pop3Client())
            {
                emailClient.Connect("pop.gmail.com", 995, true);

                emailClient.AuthenticationMechanisms.Remove("XOAUTH2");

                emailClient.Authenticate("*****@*****.**", "");

                var emails = new List <EmailMessage>();
                for (var i = 0; i < emailClient.Count && i < maxCount; i++)
                {
                    var message      = emailClient.GetMessage(i);
                    var emailMessage = new EmailMessage
                    {
                        Content = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody,
                        Subject = message.Subject
                    };
                    emailMessage.ToAddresses.AddRange(message.To.Select(x => (MailboxAddress)x).Select(x => new EmailAddress {
                        Address = x.Address, Name = x.Name
                    }));
                    emailMessage.FromAddresses.AddRange(message.From.Select(x => (MailboxAddress)x).Select(x => new EmailAddress {
                        Address = x.Address, Name = x.Name
                    }));
                }

                return(emails);
            }
        }
Пример #21
0
        // -----------------------------------------------------------   / fim xml   ------------------------------------------------

        // deletar por id
        public bool DeleteMessageByMessageId(string messageId)
        {
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect(hostname, port, useSsl);

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

                // Get the number of messages on the POP3 server
                int messageCount = client.GetMessageCount();

                // Run trough each of these messages and download the headers
                for (int messageItem = messageCount; messageItem > 0; messageItem--)
                {
                    // If the Message ID of the current message is the same as the parameter given, delete that message
                    if (client.GetMessageHeaders(messageItem).MessageId == messageId)
                    {
                        // Delete
                        client.DeleteMessage(messageItem);
                        return(true);
                    }
                }
            }
            // We did not find any message with the given messageId, report this back
            return(false);
        }
Пример #22
0
        public static List<MailMessageEx> Receive(string hostname, int port, bool useSsl, string username, string password)
        {
            using (Pop3Client client = new Pop3Client(hostname, port, useSsl, username, password))
            {
                client.Trace += new Action<string>(Console.WriteLine);
                client.Authenticate();
                client.Stat();
                List<MailMessageEx> maillist = new List<MailMessageEx>();
                MailMessageEx message = null;
                foreach (Pop3ListItem item in client.List())
                {
                    message = client.RetrMailMessageEx(item);
                    if (message != null)
                    {
                        client.Dele(item);
                        maillist.Add(message);
                    }

                }
                client.Noop();
                client.Rset();
                client.Quit();
                return maillist;
            }
        }
Пример #23
0
 /// <summary>
 /// Used to connect client to server.
 /// </summary>
 private bool Connect()
 {
     client = new Pop3Client();
     try
     {
         client.Connect(Pop3, Port, UseSsl);
         try
         {
             client.Authenticate(Client_Mail.ToString(), Password.ToString(), AuthenticationMethod.Auto);
             client.NoOperation();
             ThreadStart processTaskThread = delegate
             {
                 dispatcherTimer.Tick    += new EventHandler(dispatcherTimer_Tick);
                 dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 100);
                 dispatcherTimer.Start();
             };
             Thread thread = new Thread(processTaskThread);
             thread.Start();
             return(true);
         }
         catch {
             // user authentication error
             MessageBox.Show("User authentication error.", "error");
         }
     }
     catch {
         // POP3 connection error
         MessageBox.Show("POP3 connection error.", "error");
     }
     return(false);
 }
Пример #24
0
        /// <summary>
        /// 下载邮件附件
        /// </summary>
        /// <param name="path">下载路径</param>
        /// <param name="messageId">邮件编号</param>
        public (bool, string) DownAttachmentsById(string path, int messageId)
        {
            var zipFilePath = "";

            using (Pop3Client client = new Pop3Client())
            {
                try
                {
                    if (client.Connected)
                    {
                        client.Disconnect();
                    }
                    client.Connect(popServer, popPort, isUseSSL);
                    client.Authenticate(accout, pass);
                    Message  message  = client.GetMessage(messageId);
                    string   senders  = message.Headers.From.DisplayName;
                    string   from     = message.Headers.From.Address;
                    string   subject  = message.Headers.Subject;
                    DateTime Datesent = message.Headers.DateSent;


                    List <MessagePart> messageParts = message.FindAllAttachments();

                    if (messageParts.Count == 0)
                    {
                        return(false, zipFilePath);
                    }


                    foreach (var item in messageParts)
                    {
                        if (item.IsAttachment)
                        {
                            if (item.FileName.Contains(".z"))
                            {
                                if (!Directory.Exists(path))
                                {
                                    Directory.CreateDirectory(path);
                                }
                                var filePath = System.IO.Path.Combine(path, item.FileName);

                                File.WriteAllBytes(filePath, item.Body);

                                if (item.FileName.Contains(".zip"))
                                {
                                    zipFilePath = filePath;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("获取附件出错:" + ex.Message);
                    return(false, zipFilePath);
                }
            }

            return(true, zipFilePath);
        }
Пример #25
0
        /// <summary>
        /// Example showing:
        ///  - how to fetch all messages from a POP3 server
        /// </summary>
        /// <param name="hostname">Hostname of the server. For example: pop3.live.com</param>
        /// <param name="port">Host port to connect to. Normally: 110 for plain POP3, 995 for SSL POP3</param>
        /// <param name="useSsl">Whether or not to use SSL to connect to server</param>
        /// <param name="username">Username of the user on the server</param>
        /// <param name="password">Password of the user on the server</param>
        /// <returns>All Messages on the POP3 server</returns>
        public static List <OPMessage> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password)
        {
            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect(hostname, port, useSsl);

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

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

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

                // Messages are numbered in the interval: [1, messageCount]
                // Ergo: message numbers are 1-based.
                for (int i = 1; i <= messageCount; i++)
                {
                    allMessages.Add(client.GetMessage(i));
                }

                // Now return the fetched messages
                return(allMessages);
            }
        }
Пример #26
0
        //public List<Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password)
        public List <Message> FetchAllMessages()
        {
            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect(PopServerHost, port, true);

                // 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 <OpenPop.Mime.Message> allMessages = new List <OpenPop.Mime.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
                for (int i = messageCount; i > 0; i--)
                {
                    allMessages.Add(client.GetMessage(i));
                }

                client.Disconnect();

                // Now return the fetched messages
                return(allMessages);
            }
        }
Пример #27
0
        public string GetLastMail(AccountData account)//читаем последнее письмо и возвращаем текст
        {
            for (int i = 0; i < 30; i++)
            {
                Pop3Client pop3 = new Pop3Client("localhost", 110, account.Name, account.Password, false);
                pop3.Connect();
                pop3.Authenticate();

                if (pop3.GetMessageCount() > 0)
                {
                    MailMessage message = pop3.GetMessage(1);
                    //ReadOnlyMailMessage message = pop3.GetMessage(1); //устарело!!

                    string body = message.Body;
                    pop3.DeleteMessage(1);
                    pop3.LogOut();
                    return(message.Body);
                }
                else
                {
                    System.Threading.Thread.Sleep(3000);
                }
            }

            return(null); //Если цикл завершился возвращаем ничего - письмо так и не пришло
        }
Пример #28
0
        public static void DownloadNewMessages(HashSet <string> previouslyDownloadedUids)
        {
            using (var client = new Pop3Client()) {
                client.Connect("pop.gmail.com", 995, SecureSocketOptions.SslOnConnect);

                client.Authenticate("username", "password");

                if (!client.Capabilities.HasFlag(Pop3Capabilities.UIDL))
                {
                    throw new Exception("The POP3 server does not support UIDs!");
                }

                var uids = client.GetMessageUids();

                for (int i = 0; i < client.Count; i++)
                {
                    // check that we haven't already downloaded this message
                    // in a previous session
                    if (previouslyDownloadedUids.Contains(uids[i]))
                    {
                        continue;
                    }

                    var message = client.GetMessage(i);

                    // write the message to a file
                    message.WriteTo(string.Format("{0}.msg", uids[i]));

                    // add the message uid to our list of downloaded uids
                    previouslyDownloadedUids.Add(uids[i]);
                }

                client.Disconnect(true);
            }
        }
Пример #29
0
        public void FetchMessages(string hostname, int port, bool useSsl, string username, string password, int lim = 0)
        {
            using (Pop3Client client = new Pop3Client())
            {
                client.Connect(hostname, port, useSsl);
                client.Authenticate(username, password, AuthenticationMethod.UsernameAndPassword);
                int messageCount = client.GetMessageCount();
                using (localDBEntities context = new localDBEntities())
                {
                    OpenPop.Mime.Message m;
                    for (int i = messageCount; i > 0; i--)
                    {
                        if (i <= messageCount - lim)
                        {
                            break;
                        }

                        //--------------------->
                        m = client.GetMessage(i);
                        var t = new message()
                        {
                            messageID    = m.Headers.MessageId,
                            sender       = m.Headers.From.DisplayName + " - <" + m.Headers.From.Address + ">",
                            subject      = m.Headers.Subject,
                            content_view = m.Headers.ContentDescription,
                            date         = m.Headers.DateSent.ToShortDateString(),
                            read         = false,
                            attachment   = m.FindAllAttachments().Count > 0 ? true : false
                        };
                        context.messages.Add(t);
                    }
                    context.SaveChanges();
                }
            }
        }
Пример #30
0
        public List <EmailMessage> ReceiveEmail(int maxCount = 10)
        {
            using (var emailClient = new Pop3Client())
            {
                // 995 is for POP3 server port, this might change from one server to another.
                // SecureSocketOptions.Auto for SSL.
                emailClient.Connect("POP3 server name", 995, SecureSocketOptions.Auto);

                //Remove any OAuth functionality as we won't be using it.
                emailClient.AuthenticationMechanisms.Remove("XOAUTH2");

                emailClient.Authenticate("POP3 server username", "POP3 server password");
                List <EmailMessage> emails = new List <EmailMessage>();
                for (int i = 0; i < emailClient.Count && i < maxCount; i++)
                {
                    // i variable is for maximum number of messages to retrieve
                    var message      = emailClient.GetMessage(i);
                    var emailMessage = new EmailMessage
                    {
                        Content     = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody,
                        Subject     = message.Subject,
                        SenderName  = message.Sender.Name,
                        SenderEmail = message.Sender.Address
                    };
                }

                return(emails);
            }
        }
Пример #31
0
        public List <Message> GetMessages(string password)
        {
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect(SMTPServer, 110, false);

                // 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);

                // 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);
            }
        }
        public void StartEmailIndexing()
        {
            if (!Directory.Exists(GlobalData.EmailIndexPath))
                Directory.CreateDirectory(GlobalData.EmailIndexPath);

            IndexWriter index;

            PerFieldAnalyzerWrapper pfaw = new PerFieldAnalyzerWrapper(new KeywordAnalyzer());
            pfaw.AddAnalyzer("body", new StopAnalyzer());
            try
            {
                index = new IndexWriter(GlobalData.EmailIndexPath, pfaw, false);
            }
            catch
            {
                index = new IndexWriter(GlobalData.EmailIndexPath, pfaw, true);
            }

            const string PopServer = "pop.google.in";
            const int PopPort = 995;
            const string User = "******";
            const string Pass = "******";
            using (Pop3Client client = new Pop3Client(PopServer, PopPort, true, User, Pass))
            {
                client.Trace += new Action<string>(Console.WriteLine);
                //connects to Pop3 Server, Executes POP3 USER and PASS
                client.Authenticate();
                client.Stat();
                foreach (Pop3ListItem item in client.List())
                {
                    Document doc = new Document();
                    MailMessageEx message = client.RetrMailMessageEx(item);

                    doc.Add(new Field("subject", message.Subject.ToLower(), Field.Store.YES, Field.Index.NO_NORMS));
                    doc.Add(new Field("from", message.From.ToString().ToLower(), Field.Store.YES, Field.Index.NO_NORMS));
                    doc.Add(new Field("to", message.To.ToString().ToLower(), Field.Store.YES, Field.Index.NO_NORMS));
                    //doc.Add(new Field("date", message.DeliveryDate.ToLower(), Field.Store.YES, Field.Index.NO_NORMS));

                    string code = message.Body;
                    code = Regex.Replace(code, @"<\s*head\s*>(.|\n|\r)*?<\s*/\s*head\s*>", " ", RegexOptions.Compiled); //repalce <head> section with single whitespace
                    code = Regex.Replace(code, @"<\s*script (.|\n|\r)*?<\s*/\s*script\s*>", " ", RegexOptions.Compiled);//repalce remaining <script> tags from body with single whitespace
                    code = Regex.Replace(code, @"<!--(.|\n|\r)*?-->", " ", RegexOptions.Compiled);                      //repalce comments
                    code = Regex.Replace(code, @"<(.|\n|\r)*?>", " ", RegexOptions.Compiled);                           //repalce all tags with single whitespace
                    code = Regex.Replace(code, @"&.*?;", " ", RegexOptions.Compiled);                                   //replace &gt; e.t.c
                    code = Regex.Replace(code, @"\s+", " ", RegexOptions.Compiled);                                     //replace multiple whitespaces characters by single whitespace
                    code = Regex.Replace(code, @"\ufffd", " ", RegexOptions.Compiled);

                    doc.Add(new Field("body", code.ToLower(), Field.Store.YES, Field.Index.NO_NORMS));

                    index.AddDocument(doc);
                }
                client.Noop();
                client.Rset();
                client.Quit();
                index.Optimize();
                index.Close();
            }
        }