Пример #1
0
        /**
         * http://hpop.sourceforge.net/examples.php
         */
        public static List <Message> Receive(string hostname, int port, bool useSsl, string username, string password, bool deleteMessages)
        {
            // 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 <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));
                    if (deleteMessages)
                    {
                        client.DeleteMessage(i);
                    }
                }


                // Now return the fetched messages
                return(allMessages);
            }
        }
Пример #2
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);
                }
            }
        }
Пример #3
0
 public void priem(string login, string pass)
 {
     using (OpenPop.Pop3.Pop3Client client = new Pop3Client())
     {
         client.Connect("pop3.mail.ru", 110, false);
         client.Authenticate(login, pass, AuthenticationMethod.UsernameAndPassword);
         if (client.Connected)
         {
             int            messageCount = client.GetMessageCount(); //получаем список айдишников писем в почте
             List <Message> allMessages  = new List <Message>(messageCount);
             for (int i = messageCount; i > 0; i--)
             {
                 allMessages.Add(client.GetMessage(i));
             }
             int schet = 0;
             foreach (Message msg in allMessages)
             {
                 schet += 1;
                 var att = msg.FindAllAttachments();
                 foreach (var ado in att)
                 {
                     ado.Save(new System.IO.FileInfo(System.IO.Path.Combine("c:\\", ado.FileName)));
                     client.DeleteMessage(schet);
                 }
             }
         }
     }
 }
Пример #4
0
        private void ok_Click(object sender, RoutedEventArgs e)
        {
            //ProcessStartInfo startInfo = new ProcessStartInfo();
            //startInfo.FileName = @"D:\green_fox_stuff\repos\cs_practice_and_poc\SimpleIMAP4\SimpleIMAP4\bin\Debug\SimpleIMAP4.exe";
            //startInfo.Arguments = @"/a " + textBox.Text + " " + passwordBox.Password;
            //Process.Start(startInfo);
            string eMailAdress = emailAddress.Text;
            string password    = passwordBox.Password;

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

                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate("*****@*****.**", "Frujudmat999");

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

                    message.WriteTo($"{i}.msg");

                    var testText = message.GetTextBody(MimeKit.Text.TextFormat.Plain);
                    richTextBox.Selection.Text += $"{message.Date} Subject: {message.Subject} Message: {testText}";

                    client.DeleteMessage(i);
                }
                client.Disconnect(true);
            }
        }
Пример #5
0
        public bool DeleteMail(string messageId)
        {
            var result = false;

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

                // 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 = 1; messageItem <= messageCount; 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);
                        result = true;
                        break;
                    }
                }

                client.Disconnect();
            }

            return(result);
        }
Пример #6
0
        private static bool CheckEmail(Pop3Client client, string expectedFromAddr, string expectedSubject, DateTime startTime, bool deleteMailOnSuccess = false)
        {
            Console.WriteLine("Email Assert: start time: " + startTime.ToLongTimeString());
            MessageHeader msg          = null;
            int           messageCount = client.GetMessageCount();

            for (int i = messageCount; i > 0; i--)
            {
                msg = client.GetMessageHeaders(i);
                Console.Write($"{DateTime.UtcNow.ToLongTimeString()} Message: {msg.DateSent} | {msg.Subject} | ");
                if (ValidateTime(RecentMsgThreshold, startTime, msg.DateSent))
                {
                    if (ValidateConditions(expectedFromAddr, expectedSubject, msg))
                    {
                        Console.Write("Match" + Environment.NewLine);
                        if (deleteMailOnSuccess)
                        {
                            client.DeleteMessage(i);
                        }
                        return(true);
                    }
                }
                else
                {
                    Console.Write("Wrong time" + Environment.NewLine);
                    return(false);
                }
            }
            return(false);
        }
Пример #7
0
        /// <summary>
        /// 获取邮件的所有附件
        /// </summary>
        /// <param name="host">服务器主机名,如: pop3.live.com</param>
        /// <param name="port">服务器端口号,通常: 110 for plain POP3, 995 for SSL POP3</param>
        /// <param name="useSsl">是否使用SSL连接服务器</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="isDelete">是否删除所有邮件</param>
        /// <returns>获取所有附件从POP3服务器</returns>
        public static List <MailAttachment> FetchAllAttachments(string host, int port, bool useSsl, string userName, string password, bool isDelete = false)
        {
            var attachments = new List <MailAttachment>();

            using (var client = new Pop3Client())
            {
                client.Connect(host, port, useSsl);
                client.Authenticate(userName, password);
                //获取邮件数量
                var messageCount = client.GetMessageCount();
                for (var i = messageCount; i > 0; i--)
                {
                    var message = client.GetMessage(i);
                    if (isDelete)
                    {
                        client.DeleteMessage(i);
                    }
                    var messageParts = message.FindAllAttachments();
                    if (messageParts.Count > 0)
                    {
                        messageParts.ForEach(o =>
                        {
                            attachments.Add(new MailAttachment
                            {
                                Header = message.Headers,
                                Part   = o
                            });
                        });
                    }
                }
            }
            return(attachments);
        }
Пример #8
0
        public String GetLastMail(AccountData acc)
        {
            int waitInSeconds = 30;

            for (int i = 0; i < waitInSeconds; i++)
            {
                Pop3Client pop3 = new Pop3Client("localhost", 110, acc.Name, acc.Password, false);
                pop3.Connect();
                pop3.Authenticate();

                if (pop3.GetMessageCount() > 0)
                {
                    MailMessage m        = pop3.GetMessage(1);
                    string      str_body = m.Body;
                    pop3.DeleteMessage(1);
                    pop3.LogOut();
                    return(str_body);
                }
                else
                {
                    System.Threading.Thread.Sleep(1000);
                }
            }
            return(null);
        }
Пример #9
0
        public void Poll()
        {
            using (var client = new Pop3Client())
            {
                this.initialize(client);
                var deleted = 0;
                for (; this.mailCount < client.Count; this.mailCount++)
                {
                    try
                    {
                        var message = client.GetMessage(this.mailCount);
                        this.OnPublish?.Invoke(this, new OnPublishArgs(this.composeOutput(message)));
                        if (this.DeleteOnRead)
                        {
                            client.DeleteMessage(this.mailCount);
                            deleted++;
                        }
                    }
                    catch (Exception ex)
                    {
#warning This should be logged properly.
                        Console.WriteLine($"{DateTime.UtcNow}|ERROR|{nameof(POP3Listener)}|{ex.ToString()}");
                    }
                }

                client.Disconnect(true);
                //sucessfully deleted
                if (this.DeleteOnRead)
                {
                    this.mailCount -= deleted;
                }
            }
        }
Пример #10
0
 private void delete_button_Click(object sender, EventArgs e)
 {
     if (trigger == 0)
     {
         int removed_total = 0;
         for (int i = (inbox_list.Items.Count); i > 0; i--)
         {
             if (inbox_list.GetItemChecked(i - 1))
             {
                 Console.WriteLine(Email_Count - 1 - i);
                 incoming.DeleteMessage(Email_Count - i);
                 inbox_list.Items.RemoveAt(i - 1);
                 Email_List.Remove((Email_Count - i).ToString());
                 removed_total++;
             }
         }
         Email_Count = Email_Count - removed_total;
     }
     incoming.Logout();
     incoming.Disconnect();
     Get_Emails();
     message_text.Text = "";
     from_Text.Text    = "";
     date_Text.Text    = "";
     subject_text.Text = "";
     onebox.Visible    = false; twobox.Visible = false; threebox.Visible = false;
 }
Пример #11
0
        public string GetLastMail(AccountData account)
        {
            for (int i = 0; i < 20; i++)
            {
                var pop3 = new Pop3Client("localhost", 110, account.Name, account.Password, false);

                pop3.Connect();
                pop3.Authenticate();
                var count = pop3.GetMessageCount();

                if (count > 0)
                {
                    var message = pop3.GetMessage(1);
                    var body    = message.Body;

                    pop3.DeleteMessage(1);

                    return(body);
                }

                System.Threading.Thread.Sleep(3000);
            }

            return(null);
        }
Пример #12
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);
            }
        }
 /// <summary>
 /// The delete stored messages.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="msgs">The msgs.</param>
 private static void DeleteStoredMessages(Pop3Client client, IEnumerable <Header> msgs)
 {
     foreach (Header msg in from header in msgs where header.stored select header)
     {
         client.DeleteMessage(msg.num);
     }
 }
Пример #14
0
        public static void DownloadMessages()
        {
            using (var client = new Pop3Client(new ProtocolLogger("pop3.log"))) {
                client.Connect("pop.gmail.com", 995, SecureSocketOptions.SslOnConnect);

                //test acount on gmail
                client.Authenticate("*****@*****.**", "ehodowca");

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

                    string messageStr = string.Format("MAIL: body : {0} From: {1} , To : {2}  , Date : {3} , Sender: {4}, Subject: {5}, Text Body: {6} ", message.Body, message.From, message.To, message.Date, message.Sender, message.Subject, message.TextBody);

                    string messageDatas = string.Format("MAILs datas:  Attachments: {0} ResentFrom: {1} , Cc : {2}  , Headers : {3} , Importance: {4}, References: {5}, ResentBcc: {6} , ResentCc: {7} ,  ReplyTo: {8} , ResentFrom: {9} ,  ResentSender: {10}  ,  ResentTo: {11}, XPriority {12} ", message.Attachments, message.ResentFrom, message.Cc, message.Headers, message.Importance, message.References, message.ResentBcc, message.ResentCc, message.ReplyTo, message.ResentFrom, message.ResentSender, message.ResentTo, message.XPriority);
                    System.Console.WriteLine("MAIL :");
                    System.Console.WriteLine(messageStr);
                    System.Console.WriteLine("-------------------------");
                    System.Console.WriteLine("DATAS:  :");
                    System.Console.WriteLine("Działa");
                    System.Console.WriteLine(messageDatas);
                    // write the message to a file
                    message.WriteTo(string.Format("{0}.msg", i));

                    // mark the message for deletion
                    client.DeleteMessage(i);
                }

                client.Disconnect(true);
            }
        }
Пример #15
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); //Если цикл завершился возвращаем ничего - письмо так и не пришло
        }
Пример #16
0
        public string GetLastMail(AccountData account)
        {
            for (int i = 0; i < 2; i++)
            {
                Pop3Client pop3 = new Pop3Client("localhost", 110, account.Name, account.Password, false);
                pop3.Connect();

                pop3.Authenticate();

                //Ждем завершения аутентификации
                ////int attempt = 0;
                ////while (!pop3.IsAuthenticated && attempt < 100)
                ////{
                ////    System.Threading.Thread.Sleep(100);
                ////    attempt++;
                ////}

                if (pop3.GetMessageCount() > 0)
                {
                    ReadOnlyMailMessage message = pop3.GetMessage(1);
                    string body = message.Body;
                    pop3.DeleteMessage(1);
                    pop3.LogOut();
                    return(body);
                }
                else
                {
                    System.Threading.Thread.Sleep(3000);
                }
            }
            return(null);
        }
Пример #17
0
        /// <summary>
        /// Example showing:
        ///  - how to delete a specific message from a 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>
        /// <param name="messageNumber">
        /// The number of the message to delete.
        /// Must be in range [1, messageCount] where messageCount is the number of messages on the server.
        ///
        ///
        /// </param>
        public static void DeleteMessageOnServer(string hostname, int port, bool useSsl, string username, string password, int messageNumber)
        {
            // Silme şu mantıkla yapılıyor.Serverda bulunan bütün mailler tarihe göre sıralı halde.En uzaktaki tarihi
            // 1 , sonraki 2 ...Yani en son eklenen maili silmek için "messageCount" değeri girilmelidir.


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

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

                // When a QUIT command is sent to the server, the connection between them are closed.
                // When the client is disposed, the QUIT command will be sent to the server
                // just as if you had called the Disconnect method yourself.


                //TODO: disconnect() çağrılmadığı sürece maili silmez.!!!
                client.Disconnect();
            }
        }
Пример #18
0
 public String GetLastMail(AccountData account)
 {
     for (int i = 0; i < 20; i++)
     {
         //чтобы избежать кещирования, которое делает Pop3 будем подключаться заново
         //порт 110 - стандартный порт для pop3
         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(body);
         }
         else
         {
             System.Threading.Thread.Sleep(3000);
         }
     }
     return(null);
 }
Пример #19
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);
        }
Пример #20
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);
        }
Пример #21
0
        public static void DeleteMessage(int messageNumber)
        {
            try
            {
                using (Pop3Client client = new Pop3Client())
                {
                    // Connect to the server
                    client.Connect(hostname, port, useSsl);

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

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

                    // When a QUIT command is sent to the server, the connection between them are closed.
                    // When the client is disposed, the QUIT command will be sent to the server
                    // just as if you had called the Disconnect method yourself.
                    client.Dispose();
                }
                return;
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                throw;
            }
        }
Пример #22
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();
            }
        }
Пример #23
0
        public async Task <GetResult <IReadOnlyList <Packet> > > GetPacketsAsync(ClientConfiguration clientConfiguration = null)
        {
            var getResult = new GetResult <IReadOnlyList <Packet> >();
            var userName  = clientConfiguration == null ? _configuration.PopUsername : clientConfiguration.UserName;
            var password  = clientConfiguration == null ? _configuration.PopPassword : clientConfiguration.Password;

            try
            {
                using (var emailClient = new Pop3Client())
                {
                    emailClient.Connect(_configuration.PopServer, _configuration.PopPort, true);
                    await emailClient.AuthenticateAsync(userName, password);

                    var list = new List <Packet>();
                    for (var i = 0; i < emailClient.Count; i++)
                    {
                        var message = emailClient.GetMessage(i);
                        var packet  = new Packet()
                        {
                            Message = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody,
                            Topic   = message.Subject
                        };

                        // Check for attachments
                        if (message.Attachments.Any())
                        {
                            foreach (var attachment in message.Attachments)
                            {
                                var part = (MimePart)attachment;

                                using (var stream = new MemoryStream())
                                {
                                    part.Content.DecodeTo(stream);
                                    packet.Data = stream.ToArray();
                                }
                            }
                        }

                        list.Add(packet);
                        emailClient.DeleteMessage(i);
                    }

                    getResult.Content   = list;
                    getResult.Succeeded = true;
                    emailClient.Disconnect(true);
                }
            }
            catch (Exception e)
            {
                _logManager.LogError(e, $@"EmailProvider.GetPacketAsync");
                getResult.Succeeded = false;
                getResult.Errors.Add(new CommunicationError
                {
                    Code        = e.HResult.ToString(),
                    Description = e.Message
                });
            }
            return(getResult);
        }
Пример #24
0
        // 删除邮件
        private void btnDeleteMail_Click(object sender, EventArgs e)
        {
            if (lstViewMailList.SelectedItems.Count == 0)
            {
                MessageBox.Show("请先选择阅读的邮件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            int index = lstViewMailList.SelectedItems[0].Index;

            messageMail = popClient.GetMessage(index + 1);
            if (MessageBox.Show("确认要删除邮件" + messageMail.Headers.Subject + "吗?", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                popClient.DeleteMessage(index + 1);
                popClient.Disconnect();
                btnRefreshMailList.PerformClick();
            }
        }
Пример #25
0
 public void EliminarMensaje(string strMailUserAddress, string strMailUserPassword, int intIdMensaje)
 {
     using (Pop3Client pop3Client = new Pop3Client())
     {
         pop3Client.Connect(smtpHost, smtpPort, false);
         pop3Client.Authenticate(strMailUserAddress, strMailUserPassword);
         pop3Client.DeleteMessage(intIdMensaje);
     }
 }
Пример #26
0
        public static void p5_pop3_get(ApplicationContext context, ActiveEventArgs e)
        {
            // Making sure we remove arguments supplied.
            using (new ArgsRemover(e.Args, true)) {
                // Creating our POP3 client.
                using (var client = new Pop3Client()) {
                    // Connecting to POP3 server using helper from Common class.
                    Common.ConnectServer(context, client, e.Args, "pop3");

                    // Making sure we're able to post QUIT signal when done, regardless of what happens inside of this code.
                    try {
                        // Figuring out how many messages to retrieve, defaulting to "5" if not explicitly told something else by caller,
                        // making sure we never try to retrieve more messages than server actually has.
                        int noMessages = Math.Min(client.Count, e.Args.GetExChildValue("count", context, 5));

                        // Fetching messages from server, but not any more messages than caller requested, or number of available messages.
                        for (int idxMsg = 0; idxMsg < noMessages; idxMsg++)
                        {
                            // Process message returned from POP3 server by building Node structure wrapping message.
                            var msgNode = ProcessMessage(
                                context,
                                e.Args,
                                client.GetMessage(idxMsg));

                            // Handle message after processing.
                            e.Args.Add(msgNode);

                            // Checking if we should delete message from server.
                            if (e.Args.GetExChildValue("delete", context, false))
                            {
                                // Deleting message from server.
                                client.DeleteMessage(idxMsg);
                            }
                        }

                        // Checking to see if caller provided a lambda callback, at which case, we invoke it before exiting
                        // scope, since handling of emails might trigger an exception, at which case we do NOT want to send the
                        // QUIT signal to the POP3 server.
                        var lambda = e.Args [".onfinished"];
                        if (lambda != null)
                        {
                            // Invoking lambda callback, letting caller do his thing.
                            context.RaiseEvent("eval-mutable", lambda);
                        }
                    } catch {
                        // Disconnecting from server, making sure we do NOT send the QUIT signal.
                        // Otherwise emails will be registered as "read" (or deleted in fact) on POP3 server.
                        client.Disconnect(false);
                        throw;
                    } finally {
                        // Disconnecting from server, making sure we send the QUIT signal.
                        client.Disconnect(true);
                    }
                }
            }
        }
Пример #27
0
        public void DeleteMessage(int messageId)
        {
            if (!client.Connected)
            {
                client.Connect(PopServer, PopPort, EnableSSL);
                client.Authenticate(Username, Password);
            }

            client.DeleteMessage(messageId);
        }
Пример #28
0
 public void Delete(GXPOP3Session sessionInfo)
 {
     try
     {
         client.DeleteMessage(lastReadMessage);
     }
     catch (PopServerException e)
     {
         LogError("Delete message error", e.Message, MailConstants.MAIL_ServerRepliedErr, e);
     }
 }
Пример #29
0
 public override bool GetMailAttachment(int mailIndex, string receiveBackpath)
 {
     if (mailIndex == 0)
     {
         return(false);
     }
     else if (mailIndex > mailTotalCount)
     {
         return(false);
     }
     else
     {
         try
         {
             Message message = pop3Client.GetMessage(mailIndex);
             //邮件的全部附件.
             List <MessagePart> attachments = message.FindAllAttachments();
             foreach (MessagePart attachment in attachments)
             {
                 string   fileName     = attachment.FileName;
                 string   fileFullName = receiveBackpath + "\\" + fileName;
                 FileInfo fileInfo     = new FileInfo(fileFullName);
                 if (fileInfo.Exists)
                 {
                     fileInfo.Delete();
                 }
                 attachment.Save(fileInfo);
             }
             pop3Client.DeleteMessage(mailIndex);
             return(true);
         }
         catch (Exception ex)
         {
             ErrorMessage = ex.Message;
             return(false);
         }
     }
     return(true);
 }
Пример #30
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;
            }
        }