protected void brnSendEmail_Click(object sender, EventArgs e)
    {
        lblMessage.Text = "";

        try
        {
            // initialize pop3 client
            Pop3Client client = new Pop3Client();
            client.Host = txtHost.Text;
            client.Port = int.Parse(txtPort.Text);
            client.Username = txtUsername.Text;
            client.Password = txtPassword.Text;

            // connect to pop3 server and login
            client.Connect(true);
            lblMessage.Text = "Successfully connected to POP3 Mail server.<br><hr>";

            client.Disconnect();
        }
        catch (Exception ex)
        {
            lblMessage.ForeColor = Color.Red;
            lblMessage.Text = "Error: " + ex.Message;
        }
    }
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_POP3();
            string dstEmail = dataDir + "first-message.eml";

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

            //Specify host, username and password for your client
            client.Host = "pop.gmail.com";

            // Set username
            client.Username = "******";

            // Set password
            client.Password = "******";

            // Set the port to 995. This is the SSL port of POP3 server
            client.Port = 995;

            // Enable SSL
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                //Fetch the message by its sequence number
                MailMessage msg = client.FetchMessage(1);

                //Save the message using its subject as the file name
                msg.Save(dstEmail, Aspose.Email.Mail.SaveOptions.DefaultEml);
                client.Disconnect();

            }
            catch (Exception ex)
            {
                Console.WriteLine(Environment.NewLine + ex.Message);
            }
            finally
            {
                client.Disconnect();
            } 

            Console.WriteLine(Environment.NewLine + "Downloaded email using POP3. Message saved at " + dstEmail);
        }
    protected void gvMessages_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DisplayMessage")
        {
            pnlMessage.Visible = true;
            string msgSequenceNumber = e.CommandArgument.ToString();

            try
            {
                // initialize pop3 client
                Pop3Client client = new Pop3Client();
                client.Host = txtHost.Text;
                client.Port = int.Parse(txtPort.Text);
                client.Username = txtUsername.Text;
                client.Password = Session["Password"].ToString();

                // SSL settings
                if (chSSL.Checked == true)
                {
                    client.EnableSsl = true;
                    client.SecurityMode = Pop3SslSecurityMode.Implicit;
                }

                // connect to pop3 server and login
                client.Connect(true);
                lblMessage.ForeColor = Color.Green;
                lblMessage.Text = "Successfully connected to POP3 Mail server.<br><hr>";

                // get the message
                MailMessage msg = client.FetchMessage(int.Parse(msgSequenceNumber));
                // sender name and address
                litFrom.Text = msg.From[0].DisplayName + " <" + msg.From[0].Address + ">";
                // to addresses
                litTo.Text = "";
                foreach (MailAddress address in msg.To)
                {
                    litTo.Text += address.DisplayName + " <" + address.Address + "> , ";
                }
                // cc addresses
                litCc.Text = "";
                foreach (MailAddress address in msg.CC)
                {
                    litCc.Text += address.DisplayName + " <" + address.Address + "> , ";
                }
                // subject
                litSubject.Text = msg.Subject;
                litBody.Text = msg.HtmlBody;

                client.Disconnect();
            }
            catch (Exception ex)
            {
                lblMessage.ForeColor = Color.Red;
                lblMessage.Text = "Error: " + ex.Message;
            }
        }
    }
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_POP3();
            string dstEmail = dataDir + "message.msg";

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

            //Specify host, username and password for your client
            client.Host = "pop.gmail.com";

            // Set username
            client.Username = "******";

            // Set password
            client.Password = "******";

            // Set the port to 995. This is the SSL port of POP3 server
            client.Port = 995;

            // Enable SSL
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                int messageCount = client.GetMessageCount();
                // Create an instance of the MailMessage class
                MailMessage msg;

                for (int i = 1; i <= messageCount; i++)
                {
                    //Retrieve the message in a MailMessage class
                    msg = client.FetchMessage(i);

                    Console.WriteLine("From:" + msg.From.ToString());
                    Console.WriteLine("Subject:" + msg.Subject);
                    Console.WriteLine(msg.HtmlBody);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                client.Disconnect();
            } 

            Console.WriteLine(Environment.NewLine + "Retrieved email messages using POP3 ");
        }
    private void DownloadFile(string msgSequenceNumber, string format)
    {
        try
        {
            // initialize pop3 client
            Pop3Client client = new Pop3Client();
            client.Host = txtHost.Text;
            client.Port = int.Parse(txtPort.Text);
            client.Username = txtUsername.Text;
            client.Password = Session["Password"].ToString();

            // SSL settings
            if (chSSL.Checked == true)
            {
                client.EnableSsl = true;
                client.SecurityMode = Pop3SslSecurityMode.Implicit;
            }

            // connect to pop3 server and login
            client.Connect(true);
            lblMessage.ForeColor = Color.Green;
            lblMessage.Text = "Successfully connected to POP3 Mail server.<br><hr>";

            // get the message
            MemoryStream stream = new MemoryStream();
            MailMessage msg = client.FetchMessage(int.Parse(msgSequenceNumber));
            if (format == "eml")
                msg.Save(stream, MessageFormat.Eml);
            else
                msg.Save(stream, MessageFormat.Msg);
            stream.Position = 0;
            byte[] msgBytes = new byte[stream.Length];
            stream.Read(msgBytes, 0, (int)stream.Length);

            client.Disconnect();

            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("Content-Length", msgBytes.Length.ToString());
            Response.AddHeader("Content-Disposition", "attachment; filename=Message." + format);
            Response.ContentType = "application/octet-stream";
            Response.BinaryWrite(msgBytes);
            Response.End();

        }
        catch (Exception ex)
        {
            lblMessage.ForeColor = Color.Red;
            lblMessage.Text = "Error: " + ex.Message;
        }
    }
示例#6
0
        private void btnClick_Click(object sender, EventArgs e)
        {
            ToggleMyStatus(this);//Enable
            try
            {
                Pop3Client client = new Pop3Client();
                if (chkAPOP.Checked)
                {
                    client.APOPConnect(txtHost.Text, txtUser.Text, txtPassword.Text);
                }
                else
                {
                    client.Connect(txtHost.Text, txtUser.Text, txtPassword.Text);
                }

                if (client.MessageCount == 0)
                {
                    client.Disconnect();
                    Sleep();
                    MessageBox.Show("You do not have any new messages");
                }
                else
                {
                    //Load up, POP3Result.
                    //Pass up Pop3Client, for further operations
                    Pop3Result result = new Pop3Result();
                    result.Pop = client;
                    result.ShowDialog();
                    client.Disconnect();
                    Sleep();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
            }
            ToggleMyStatus(this);//Disable
        }
示例#7
0
 public Pop3Client getClient()
 {
     using (Pop3Client client = new Pop3Client())
     {
         if (client.Connected)
         {
             client.Disconnect();
         }
         //连接263服务器
         client.Connect(host, 110, false);
         client.Authenticate(account, password);
         return(client);
     }
 }
示例#8
0
        // 退出登陆
        private void btnLogout_Click(object sender, EventArgs e)
        {
            // 断开与POP3服务器的TCP连接
            lsttbxStatus.Items.Add("结束会话,进入更新状态...");
            SendToServer("QUIT");
            lsttbxStatus.Items.Add("正在关闭连接...");
            streamReader.Close();
            streamWriter.Close();
            networkStream.Close();
            tcpClient.Close();

            // SmtpClient 对象销毁
            if (smtpClient != null)
            {
                smtpClient.Dispose();
            }
            if (popClient != null)
            {
                popClient.Disconnect();
            }

            lstViewMailList.Items.Clear();
            lsttbxStatus.Items.Add("退出登陆.");
            lsttbxStatus.TopIndex = lsttbxStatus.Items.Count - 1;
            tbxMailboxInfo.Text   = "";

            // 窗口控件控制
            tabControlMyMailbox.Enabled = false;
            tbxUserMail.Enabled         = true;
            txbPassword.Enabled         = true;
            btnLogin.Enabled            = true;
            btnLogout.Enabled           = false;
            tbxSmtpServer.Enabled       = true;
            tbxPOP3Server.Enabled       = true;
            tb_smtpPort.Enabled         = true;
            tb_popPort.Enabled          = true;
        }
示例#9
0
        public static void 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, AuthenticationMethod.Auto);
                // 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 = 1; i < messageCount + 1; i++)
                {
                    allMessages.Add(client.GetMessage(i));
                    //client.DeleteMessage(i);
                    CtlMsg tmp = new CtlMsg();
                    {
                        tmp.from = client.GetMessageHeaders(i).From.Address;
                        if (client.GetMessage(i).FindFirstPlainTextVersion() == null)
                        {
                            tmp.ctlmsg = client.GetMessage(i).FindFirstHtmlVersion().GetBodyAsText();
                        }
                        else
                        {
                            tmp.ctlmsg = client.GetMessage(i).FindFirstPlainTextVersion().GetBodyAsText();
                        }


                        foreach (IPAddress ipaddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
                        {
                            if (tmp.ctlmsg.Contains(ipaddress.ToString()))
                            {
                                client.DeleteMessage(i);
                                QueueCommand.Enqueue(tmp);
                            }
                        }
                    }
                    //catch { }
                }
                client.Disconnect();
                // Now return the fetched messages
                return;
            }
        }
    protected void brnSendEmail_Click(object sender, EventArgs e)
    {
        lblMessage.Text = "";

        try
        {
            // initialize pop3 client
            Pop3Client client = new Pop3Client();
            client.Host = txtHost.Text;
            client.Port = int.Parse(txtPort.Text);
            client.Username = txtUsername.Text;
            client.Password = txtPassword.Text;

            // SSL settings
            if (chSSL.Checked == true)
            {
                client.EnableSsl = true;
                client.SecurityMode = Pop3SslSecurityMode.Implicit;
            }

            // connect to pop3 server and login
            client.Connect(true);
            lblMessage.ForeColor = Color.Green;
            lblMessage.Text = "Successfully connected to SSL enabled POP3 Mail server.<br><hr>";

            // get mailbox information
            Pop3MailboxInfo mailboxInfo = client.GetMailboxInfo();
            long nMailboxSize = mailboxInfo.OccupiedSize;
            string strMailboxSize = "";

            // convert size in easy to read format
            if (nMailboxSize <= 1024)
                strMailboxSize = nMailboxSize.ToString() + " bytes";
            else if (nMailboxSize > 1024 && nMailboxSize <= (1024 * 1024))
                strMailboxSize = nMailboxSize.ToString() + " bytes (approx " + Math.Round((double)nMailboxSize / 1024, 2).ToString() + " KB)";
            else
                strMailboxSize = nMailboxSize.ToString() + " bytes (approx " + Math.Round((double)nMailboxSize / (1024 * 1024), 2).ToString() + " MB)";

            lblMailboxSize.Text = strMailboxSize;
            lblMessageCount.Text = mailboxInfo.MessageCount.ToString() + " messages found";

            client.Disconnect();
        }
        catch (Exception ex)
        {
            lblMessage.ForeColor = Color.Red;
            lblMessage.Text = "Error: " + ex.Message;
        }
    }
示例#11
0
        /// <summary>
        /// Test connection
        /// </summary>
        /// <returns>error message</returns>
        public string checkConnection()
        {
            string returnString = "";

            try
            {
                client.Connect(user.pop3, user.port, user.ssl);
                try
                {
                    client.Authenticate(user.email, user.password);
                }
                catch (Exception ex)
                {
                    returnString = ex.Message;
                    client.Disconnect();
                }
            }
            catch (Exception ex)
            {
                returnString = ex.Message;
            }
            client.Disconnect();
            return(returnString);
        }
示例#12
0
        internal IEnumerable <MimeMessage> DownloadMessages()
        {
            using (var client = new Pop3Client(new ProtocolLogger("pop3.log")))
            {
                client.Connect(_host, _port, SecureSocketOptions.SslOnConnect);
                client.Authenticate(_userName, _password);

                for (var i = 0; i < client.Count; i++)
                {
                    yield return(client.GetMessage(i));
                }

                client.Disconnect(true);
            }
        }
示例#13
0
        private void _bRetrieveMessage_Click(object sender, EventArgs e)
        {
            // We instantiate the pop3 client.
            Pop3Client pop = new Pop3Client();

            try
            {
                this.AddLogEntry(string.Format("Connection to the pop 3 server : {0}", _tbPop3Server.Text));

                // We connect to the pop3 client
                pop.Connect(_tbPop3Server.Text);

                // We authenticate securly
                pop.Authenticate(_tbUserName.Text, _tbPassword.Text, SaslMechanism.CramMd5);

                if (pop.MessageCount > 0)
                {
                    //Retrive a message at a particulat index (index 1 in this sample)
                    ActiveUp.Net.Mail.Message message = pop.RetrieveMessageObject(1);

                    this.AddLogEntry(string.Format("Subject: {0} From :{1} Message Body {2}"
                                                   , message.Subject, message.From.Email, message.BodyText));
                }

                else
                {
                    this.AddLogEntry("There is no message in this pop3 account");
                }
            }

            catch (Pop3Exception pexp)
            {
                this.AddLogEntry(string.Format("Pop3 Error: {0}", pexp.Message));
            }

            catch (Exception ex)
            {
                this.AddLogEntry(string.Format("Failed: {0}", ex.Message));
            }

            finally
            {
                if (pop.IsConnected)
                {
                    pop.Disconnect();
                }
            }
        }
示例#14
0
        public override void Aggregate()
        {
            Pop3Client pop = null;

            try
            {
                pop = (Pop3Client)Connect();

                UpdateTimeCheckedIfNeeded();

                log.Debug("UpdateStats()");

                pop.UpdateStats();

                log.Debug("GetCAPA()");

                GetCapa(pop);

                log.Info("Account: MessagesCount={0}, TotalSize={1}, UIDL={2}, LoginDelay={3}",
                         pop.MessageCount, pop.TotalSize, _isUidlSupported, Account.ServerLoginDelay);

                // Were we already canceled?
                cancelToken.ThrowIfCancellationRequested();

                if (!ProcessMessages(pop))
                {
                    return;
                }

                Account.MessagesCount = pop.MessageCount;
                Account.Size          = pop.TotalSize;
            }
            finally
            {
                try
                {
                    if (pop != null && pop.IsConnected)
                    {
                        pop.Disconnect();
                    }
                }
                catch (Exception ex)
                {
                    log.Warn("Aggregate() Pop3->Disconnect: {0} Port: {1} Account: '{2}' ErrorMessage:\r\n{3}\r\n",
                             Account.Server, Account.Port, Account.Account, ex.Message);
                }
            }
        }
示例#15
0
    public void DeleteMessagesOnServer(Message DefectEmail, string ProjectScope)
    {
        EmailSettings EmailSetting   = new EmailSettings();
        V1Logging     Logs           = new V1Logging();
        V1XMLHelper   V1XMLHelp      = new V1XMLHelper();
        string        ToEmailAddress = V1XMLHelp.GetEmailAddressFromProjectScope(ProjectScope);


        try
        {
            EmailSetting = EmailSetting.GetEmailSettings(ToEmailAddress);

            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect(EmailSetting.Pop3Server, EmailSetting.Pop3PortNumber, EmailSetting.UseSSLPop3);

                // Authenticate ourselves towards the server
                client.Authenticate(ToEmailAddress, EmailSetting.Password);
                if (client.Connected == true)
                {
                    // 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 == DefectEmail.Headers.MessageId)
                        {
                            // Delete
                            client.DeleteMessage(messageItem);
                        }
                    }
                    client.Disconnect();
                }
                else
                {
                    Logs.LogEvent("ERROR - Deleting Message - Can't connect to server to delete message.");
                }
            }
        }
        catch (Exception ex)
        {
            Logs.LogEvent("ERROR - Deleting Message - " + ex.ToString());
        }
    }
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_POP3();
            string dstEmail = dataDir + "message.msg";

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

            //Specify host, username and password for your client
            client.Host = "pop.gmail.com";

            // Set username
            client.Username = "******";

            // Set password
            client.Password = "******";

            // Set the port to 995. This is the SSL port of POP3 server
            client.Port = 995;

            // Enable SSL
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                HeaderCollection headers = client.GetMessageHeaders(1);

                for (int i = 0; i < headers.Count; i++)
                {
                    // Display key and value in the header collection
                    Console.Write(headers.Keys[i]);
                    Console.Write(" : ");
                    Console.WriteLine(headers.Get(i));
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                client.Disconnect();
            } 

            Console.WriteLine(Environment.NewLine + "Displayed header information from emails using POP3 ");
        }
示例#17
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);
     }
 }
        public void Refresh()
        {
            MessagesListBox.Items.Clear();
            messages.Clear();
            Pop3Client client = new Pop3Client();

            client.Connect("pop.yandex.ru", 995, true);
            client.Authenticate(_login, _password);
            count = client.GetMessageCount();
            for (int i = 1; i < 20; i++)
            {
                messages.Add(client.GetMessage(i));
                MessagesListBox.Items.Add(messages[i - 1].Headers.Subject);
            }
            client.Disconnect();
        }
示例#19
0
        public static bool TestConnect()
        {
            using (Pop3Client client = new Pop3Client()) {
                try {
                    client.Connect(HOSTNAME, PORT, false);
                    client.Authenticate(USERNAME, PASSWORD);

                    client.Disconnect();
                }
                catch (Exception) {
                    return(false);
                }

                return(true);
            }
        }
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir  = RunExamples.GetDataDir_POP3();
            string dstEmail = dataDir + "message.msg";

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

            //Specify host, username and password for your client
            client.Host = "pop.gmail.com";

            // Set username
            client.Username = "******";

            // Set password
            client.Password = "******";

            // Set the port to 995. This is the SSL port of POP3 server
            client.Port = 995;

            // Enable SSL
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                HeaderCollection headers = client.GetMessageHeaders(1);

                for (int i = 0; i < headers.Count; i++)
                {
                    // Display key and value in the header collection
                    Console.Write(headers.Keys[i]);
                    Console.Write(" : ");
                    Console.WriteLine(headers.Get(i));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                client.Disconnect();
            }

            Console.WriteLine(Environment.NewLine + "Displayed header information from emails using POP3 ");
        }
示例#21
0
        public void ManageMail()
        {
            MessageHeader messageHeader;
            string        mailAddress;

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

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

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

                int i = 1;

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

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

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

                    i++;
                }

                client.Disconnect();
                client.Dispose();
            }
        }
示例#22
0
        public IList <MailMessage> ReadAll()
        {
            var result = new List <MailMessage>();

            logger.ConnectingToPop3Server(this.hostname);

            using (Pop3Client client = new Pop3Client())
            {
                client.Connect(hostname, port, useSsl);
                client.Authenticate(username, password);

                logger.ConnectedToPop3Server(this.hostname);

                try
                {
                    int numMessages = client.GetMessageCount();
                    logger.FoundMessages(numMessages);

                    for (int messageNo = 1; messageNo <= numMessages; messageNo++)
                    {
                        logger.ReadingMessage(messageNo);
                        var pop3mail = client.GetMessage(messageNo);
                        logger.MessageRead(pop3mail);

                        var message = MakeMessage(pop3mail);
                        SaveAttachments(pop3mail, message);

                        result.Add(message);
#if !DEBUG
                        logger.DeletingMessage(messageNo);
                        client.DeleteMessage(messageNo);
#endif
                    }//for

                    logger.DisconnectingFromPop3Server(this.hostname);
                    // also forces message deletion
                    client.Disconnect();
                    logger.DisconnectedFromPop3Server(this.hostname);
                }
                catch (Exception e)
                {
                    logger.ErrorWhileReadingFromPop3Server(this.hostname, e);
                }//try

                return(result);
            }//using
        }
        private void _bCountMessage_Click(object sender, EventArgs e)
        {
            // We instantiate the pop3 client.
            Pop3Client pop = new Pop3Client();

            try
            {
                this.AddLogEntry(string.Format("Connection to the pop 3 server : {0}", _tbPop3Server.Text));

                // Connect to the pop3 client
                pop.Connect(_tbPop3Server.Text, _tbUserName.Text, _tbPassword.Text);

                //Retrive the header of the messag at position 1
                if (pop.MessageCount > 0)
                {
                    Header msgHeader = pop.RetrieveHeaderObject(1);

                    //Display the header for the first message
                    this.AddLogEntry(string.Format("Subject: {0} From :{1} Date Sent {2}"
                                                   , msgHeader.Subject, msgHeader.From.Email, msgHeader.DateString));
                }

                else
                {
                    this.AddLogEntry("There is no message in this pop3 account");
                }
            }

            catch (Pop3Exception pexp)
            {
                this.AddLogEntry(string.Format("Pop3 Error: {0}", pexp.Message));
            }

            catch (Exception ex)
            {
                this.AddLogEntry(string.Format("Failed: {0}", ex.Message));
            }

            finally
            {
                if (pop.IsConnected)
                {
                    pop.Disconnect();
                }
            }
        }
示例#24
0
        /// <summary>
        /// 链接至服务器并读取邮件集合
        /// </summary>
        public override Boolean Authenticate()
        {
            try
            {
                pop3Client = new Pop3Client();
                if (pop3Client.Connected)
                {
                    pop3Client.Disconnect();
                }
                pop3Client.Connect(Pop3Address, Pop3Port, false);
                //pop3Client.Authenticate(EmailAddress, EmailPassword, AuthenticationMethod.UsernameAndPassword);
                mailTotalCount = pop3Client.GetMessageCount();

                return(ExitsError = true);
            }
            catch (Exception ex) { ErrorMessage = ex.Message; return(ExitsError = false); }
        }
示例#25
0
        public async Task <bool> DeleteAllMessage()
        {
            using (Pop3Client client = new Pop3Client())
            {
                if (client.Connected)
                {
                    client.Disconnect();
                }
                client.Connect(popServer, popPort, isUseSSL);
                client.Authenticate(accout, pass, AuthenticationMethod.UsernameAndPassword);
                client.DeleteAllMessages();
                await Task.Delay(new Random().Next(500, 1000));

                var count = client.GetMessageCount();
                return(count == 0);
            }
        }
示例#26
0
        /// <summary>
        /// 获取邮件数量
        /// </summary>
        /// <returns></returns>
        public int GetEmailCount()
        {
            int messageCount = 0;

            using (Pop3Client client = new Pop3Client())
            {
                if (client.Connected)
                {
                    client.Disconnect();
                }
                client.Connect(popServer, popPort, isUseSSL);
                client.Authenticate(accout, pass, AuthenticationMethod.UsernameAndPassword);
                messageCount = client.GetMessageCount();
            }

            return(messageCount);
        }
示例#27
0
        public string GetImageAttachmentByMessageUID(string messageUID)
        {
            using (var client = new Pop3Client())
            {
                // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                //client.ServerCertificateValidationCallback = (object s, X509Certificate c, X509Chain h, SslPolicyErrors e) => true;

                client.Connect(Localhost, Pop3DefaultPort, false);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                try
                {
                    // Mandatory authentication
                    client.Authenticate(_login, _password);

                    MimeMessage message = client
                                          .GetMessages(0, client.Count)
                                          .First(msg => msg.MessageId == messageUID);

                    MimePart imageMimePart = message?.Attachments
                                             .Where(p => p.ContentType.MediaType == "image" || p.IsAttachment)
                                             .OfType <MimePart>()
                                             .First();

                    if (!File.Exists(imageMimePart?.FileName))
                    {
                        using (FileStream output = File.Create(imageMimePart?.FileName))
                            imageMimePart?.ContentObject.DecodeTo(output);
                    }

                    return(imageMimePart?.FileName ?? string.Empty);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                    throw;
                }
                finally
                {
                    client.Disconnect(true);
                }
            }
        }
示例#28
0
        public static string RetrieveVerificationLink(DateTime dateSent)
        {
            var client = new Pop3Client();

            for (int j = 0; j < 10; j++)
            {
                client.Connect(Settings.MailServer, Settings.MailPort, true);
                client.Authenticate(Settings.MailUser, Settings.MailPwd);

                var  count     = client.GetMessageCount();
                bool mailFound = false;

                for (int i = count; i > 0; i--)
                {
                    var header = client.GetMessageHeaders(i);
                    if (header.DateSent >= TimeZoneInfo.ConvertTimeToUtc(dateSent.AddTicks(-(dateSent.Ticks % TimeSpan.TicksPerSecond))) && // Ticks datepart is not present in the header
                        header.Subject == "Please confirm your account")
                    {
                        Message message = client.GetMessage(count);

                        MessagePart html = message.FindFirstHtmlVersion();
                        if (html != null)
                        {
                            string content = html.GetBodyAsText();
                            content = content.Replace("<a href='", "");
                            content = content.Replace("'>Please click Here to confirm your email</a>", "");
                            return(content);
                        }

                        mailFound = true;
                        break;
                    }
                }

                if (mailFound)
                {
                    break;
                }

                client.Disconnect();
                Thread.Sleep(5000);     // Five seconds' wait before next attempt
            }

            return("");
        }
示例#29
0
        public bool ValidateAccount(ref string error)
        {
            Pop3Client client = new Pop3Client();

            try
            {
                client.Connect(popServer, popPort, isUseSSL);
                client.Authenticate(accout, pass);
            }
            catch (InvalidLoginException ex)
            {
                error = "邮箱登录失败!";
                Console.WriteLine("0.1邮箱登录失败");
                return(false);
            }
            catch (InvalidUseException ex)
            {
                error = "邮箱登录失败!";
                Console.WriteLine("0.2邮箱登录失败");
                return(false);
            }
            catch (PopServerNotFoundException ex)
            {
                error = "服务器没有找到!";
                Console.WriteLine("0.3服务器没有找到");
                return(false);
            }
            catch (PopServerException ex)
            {
                error = "请在邮箱开通POP3/SMTP!";
                Console.WriteLine("0.4请在邮箱开通POP3/SMTP!");
                return(false);
            }
            catch (Exception ex)
            {
                error = "连接出现异常";
                Console.WriteLine("0.5连接出现异常");
                return(false);
            }
            finally
            {
                client.Disconnect();
            }
            return(true);
        }
示例#30
0
        private void logOutButton_Click(object sender, EventArgs e)
        {
            if (loginButton.Visible == false)
            {
                tabs.TabPages.Remove(sendForm);
                tabs.TabPages.Remove(inboxForm);
                statusLabel.Text     = "";
                loginButton.Visible  = true;
                logOutButton.Visible = false;
                usernameBox.Text     = "";
                passwordBox.Text     = "";
                lettersView.Clear();
                addColumnToListView();
                getMailButton.Visible = true;

                pop.Disconnect();
            }
        }
示例#31
0
        public List <MimeMessage> getAllMessages()
        {
            using (var client = new Pop3Client()) {
                client.Connect("pop.gmail.com", 995, true);

                client.Authenticate("recent:" + Resources.Email, Resources.Password);
                int d = client.GetMessageCount();
                List <MimeMessage> messages = new List <MimeMessage>();
                for (int i = 0; i < client.Count; i++)
                {
                    messages.Add(client.GetMessage(i));
                }
                client.Disconnect(true);


                return(messages);
            }
        }
示例#32
0
 public static bool Disconnect(Pop3Client client)
 {
     if (client.Connected)
     {
         client.Disconnect();
         GC.Collect();
         GC.WaitForPendingFinalizers();
         GC.SuppressFinalize(client);
         return(true);
     }
     else
     {
         GC.Collect();
         GC.WaitForPendingFinalizers();
         GC.SuppressFinalize(client);
         return(false);
     }
 }
示例#33
0
        //public bool valid { get; set; }

        async public static Task <User> authenticate(String email, String password)
        {
            SmtpClient sendingClient   = new SmtpClient();
            Pop3Client receivingClient = new Pop3Client();

            await sendingClient.ConnectAsync("smtp.gmail.com", 465, true);

            await sendingClient.AuthenticateAsync(StrUtil.removeDomain(email), password);

            await receivingClient.ConnectAsync("pop.gmail.com", 995, true);

            await receivingClient.AuthenticateAsync(StrUtil.removeDomain(email), password);

            sendingClient.Disconnect(true);
            receivingClient.Disconnect(true);

            return(new User(email, password));
        }
        private void _bRetrieveMessageAsync_Click(object sender, EventArgs e)
        {
            // We instantiate the pop3 client.
            Pop3Client pop = new Pop3Client();

            try
            {
                this.AddLogEntry(string.Format("Connection to the pop 3 server : {0}", _tbPop3Server.Text));

                // Connect to the pop3 client
                pop.Connect(_tbPop3Server.Text, _tbUserName.Text, _tbPassword.Text);

                if (pop.MessageCount > 0)
                {
                    //Retrive the message at a particulat index
                    pop.MessageRetrieved += new MessageRetrievedEventHandler(MessageRetrived);
                    pop.BeginRetrieveMessage(1, null);
                }

                else
                {
                    this.AddLogEntry("There is no message in this pop3 account");
                }
            }

            catch (Pop3Exception pexp)
            {
                this.AddLogEntry(string.Format("Pop3 Error: {0}", pexp.Message));
            }

            catch (Exception ex)
            {
                this.AddLogEntry(string.Format("Failed: {0}", ex.Message));
            }

            finally
            {
                if (pop.IsConnected)
                {
                    pop.Disconnect();
                }
            }
        }
示例#35
0
        public List <MimeMessage> Receive(int maxCount = 10)
        {
            using (var emailClient = new Pop3Client())
            {
                emailClient.Connect("pop.gmail.com", 995, true);

                emailClient.Authenticate(_from, _password);

                var emails = new List <MimeMessage>();
                for (var i = 0; i < emailClient.Count && i < maxCount; i++)
                {
                    emails.Add(emailClient.GetMessage(i));
                }

                emailClient.Disconnect(true);

                return(emails);
            }
        }
示例#36
0
        void get()
        {
            using (var client = new Pop3Client())
            {
                try{
                    string[] words = login.Split(new char[] { '@' });
                    string   pop3  = "pop." + words[1];
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    client.Connect(pop3, 995, true);

                    client.Authenticate(login, pass);


                    int z = client.Count;
                    for (int i = 0; i < client.Count; i++)
                    {
                        string[] bufMassS = new string[3];
                        var      message  = client.GetMessage(i);

                        int    starti = message.From.ToString().IndexOf(" <");
                        string bufs   = message.From.ToString();
                        bufs = bufs.Remove(0, starti + 1);
                        bufs = bufs.Replace("<", "");
                        bufs = bufs.Replace(">", "");
                        //обрезка
                        bufMassS[1] = bufs;
                        bufMassS[0] = checkSubject(message.Subject.ToString(), 1, message.Subject.ToString());//тема
                        bufMassS[2] = message.TextBody;



                        listEmails.Add(bufMassS);
                    }

                    client.Disconnect(true);
                }
                catch
                {
                }
            }
            listEmails.Reverse();
        }
示例#37
0
        public static string CheckMail(string hostname, int port, bool useSsl, string username, string password)
        {
            string     mailStatus = "";
            Pop3Client client     = new Pop3Client();

            try
            {
                client.Connect(hostname, port, useSsl);
                if (client.Connected)
                {
                    mailStatus += "Server " + hostname + ":" + port.ToString() + ", Connected. Ok." + Environment.NewLine;
                    try
                    {
                        client.Authenticate(username, password);
                        mailStatus += "Username and Password details are Correct. Mail Connection Connected. Ok." + Environment.NewLine;
                    }
                    catch (Exception ex)
                    {
                        mailStatus += "Username and/or Password are incorrect. Please confirm the credentials" + Environment.NewLine;
                    }
                }
                else
                {
                    mailStatus += "Warning. Server " + hostname + ":" + port.ToString() + ", Not Connected. " + Environment.NewLine + "Please check server, port, SSL settings";
                }
            }
            catch (Exception ex)
            {
                mailStatus = ex.Message;
            }
            finally
            {
                try
                {
                    client.Disconnect();
                    mailStatus += "Server disconnected." + Environment.NewLine;
                }
                catch (Exception ex)
                {
                }
            }
            return(mailStatus);
        }
示例#38
0
        public static void GetMessages( string server, string userName, string password, bool useSsl )
        {
            try
            {
                Pop3Client pop3Client = new Pop3Client( );

                Console.WriteLine( "Connecting to POP3 server '{0}'...{1}", server, Environment.NewLine );

                pop3Client.Connect( server, userName, password, useSsl );

                Console.WriteLine( "List Messages...{0}", Environment.NewLine );

                IEnumerable<Pop3Message> messages = pop3Client.List( );

                Console.WriteLine( "Retrieve Messages...{0}", Environment.NewLine );

                foreach ( Pop3Message message in messages )
                {
                    Console.WriteLine( "- Number: {0}", message.Number );

                    pop3Client.Retrieve( message );

                    Console.WriteLine( "\t* MessageId: {0}", message.MessageId );
                    Console.WriteLine( "\t* Date: {0}", message.Date );
                    Console.WriteLine( "\t* From: {0}", message.From );
                    Console.WriteLine( "\t* To: {0}", message.To );
                    Console.WriteLine( "\t* Subject: {0}", message.Subject );
                    Console.WriteLine( "\t* Body Length: {0}", message.Body.Length );
                    Console.WriteLine( );
                }

                Console.WriteLine( "Disconnecting...{0}", Environment.NewLine );
                pop3Client.Disconnect( );
            }
            catch ( Exception ex )
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine( ex.Message );
                Console.ForegroundColor = ConsoleColor.White;
            }
        }
    private void ListMessages()
    {
        lblMessage.Text = "";
        lblMessage.ForeColor = Color.Green;

        try
        {
            // initialize pop3 client
            Pop3Client client = new Pop3Client();
            client.Host = txtHost.Text;
            client.Port = int.Parse(txtPort.Text);
            client.Username = txtUsername.Text;
            client.Password = Session["Password"].ToString();

            // SSL settings
            if (chSSL.Checked == true)
            {
                client.EnableSsl = true;
                client.SecurityMode = Pop3SslSecurityMode.Implicit;
            }

            // connect to pop3 server and login
            client.Connect(true);
            lblMessage.ForeColor = Color.Green;
            lblMessage.Text = "Successfully connected to SSL enabled POP3 Mail server.<br><hr>";

            // get list of messages
            Pop3MessageInfoCollection msgCollection = client.ListMessages();
            gvMessages.DataSource = msgCollection;
            gvMessages.DataBind();

            client.Disconnect();
        }
        catch (Exception ex)
        {
            lblMessage.ForeColor = Color.Red;
            lblMessage.Text = "Error: " + ex.Message;
        }
    }
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_POP3();
            string dstEmail = dataDir + "1234.eml";

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

            //Specify host, username and password for your client
            client.Host = "pop.gmail.com";

            // Set username
            client.Username = "******";

            // Set password
            client.Password = "******";

            // Set the port to 995. This is the SSL port of POP3 server
            client.Port = 995;

            // Enable SSL
            client.SecurityOptions = SecurityOptions.Auto;

            try
            {
                //Save message to disk by message sequence number
                client.SaveMessage(1, dstEmail);

                client.Disconnect();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine(Environment.NewLine + "Retrieved email messages using POP3 ");
        }
示例#41
0
        public void DisconnectFailNotConnect( )
        {
            Pop3Client pop3Client = new Pop3Client( new PlainMessagesDummyNetworkOperations( ) );
            Assert.IsFalse( pop3Client.IsConnected );

            pop3Client.Disconnect( );
            Assert.IsFalse( pop3Client.IsConnected );
        }
示例#42
0
        public void DisconnectOk( )
        {
            Pop3Client pop3Client = new Pop3Client( new PlainMessagesDummyNetworkOperations( ) );
            Assert.IsFalse( pop3Client.IsConnected );

            pop3Client.Connect( "SERVER", "USERNAME", "PASSWORD" );
            Assert.IsTrue( pop3Client.IsConnected );

            pop3Client.Disconnect( );
            Assert.IsFalse( pop3Client.IsConnected );
        }
示例#43
0
        public Dictionary<string, string> GetEmailByMessageId(string messageId, DateTime? data, string host, int port, string username, string password)
        {
            try
            {
                var client = new Pop3Client(host, port, username, password);

                //var builder = new MailQueryBuilder();
                //builder.InternalDate.Since(data);
                //var query = builder.GetQuery();

                //// Get list of messages
                //var messages = client.ListMessages(query);
                var messages = client.ListMessages();

                var result = new Dictionary<string, string>(messages.Count);
                foreach (var message in messages)
                {
                    using (var stream = new MemoryStream())
                    {
                        client.SaveMessage(message.SequenceNumber, stream);
                        var emlMessage = Conversione.ToString(stream);
                        if (!string.IsNullOrEmpty(messageId) && emlMessage.Contains(messageId))
                            result.Add(message.UniqueId, emlMessage);
                        else
                            result.Add(message.UniqueId, emlMessage);
                    }
                }

                // Disconnect from POP3
                client.Disconnect();

                return result;
            }
            catch (Pop3Exception ex)
            {
                _log.DebugFormat("Errore nella lettura delle ricevute email - {0} - messageId:{1} - data:{2} - host:{3} - port:{4} - username:{5} - password:{6}", ex, Utility.GetMethodDescription(), messageId, data, host, port, username, password);
                return new Dictionary<string, string>();
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Errore nella lettura delle ricevute email - {0} - messageId:{1} - data:{2} - host:{3} - port:{4} - username:{5} - password:{6}", ex, Utility.GetMethodDescription(), messageId, data, host, port, username, password);
                return new Dictionary<string, string>();
            }
        }