Example #1
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("Start work");

            string sHostPop = "pop.googlemail.com";
            string sHostImap = "imap.googlemail.com";
            int nPort = 995;
            string sUserName = "******";
            string sPasword = "theSimpsons";

            try
            {
                string sEml = @"E:\ut8_encripted_teamlab.eml";
                
                ActiveUp.Net.Mail.Message m = 
                ActiveUp.Net.Mail.Parser.ParseMessageFromFile(sEml);
                var header = ActiveUp.Net.Mail.Parser.ParseHeader(sEml);
                
                Pop3Client pop = new Pop3Client();

                // Connect to the pop3 client
                pop.ConnectSsl(sHostPop, nPort, "recent:" + sUserName, sPasword);

                if (pop.MessageCount > 0)
                {
                    ActiveUp.Net.Mail.Message message = pop.RetrieveMessageObject(4);
                    string sHtml = message.BodyHtml.Text;
                }
                else
                    System.Console.WriteLine("No letters!");

                pop.Disconnect();

                Imap4Client imap = new Imap4Client();

                imap.ConnectSsl(sHostImap, 993);

                imap.Login(sUserName, sPasword);

                Mailbox inbox = imap.SelectMailbox("inbox");
                
                if (inbox.MessageCount > 0)
                {
                    ActiveUp.Net.Mail.Message message = inbox.Fetch.MessageObject(6);
                    string sHtml = message.BodyHtml.Text;
                }

                imap.Disconnect();

            }
            catch (Exception ex)
            {
                System.Console.Write("\r\n" + ex);
            }

            System.Console.WriteLine("Stop work");

            System.Console.ReadKey();
        }
        private void _bDomainKey_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 a message at a particulat index
                    ActiveUp.Net.Mail.Message message = pop.RetrieveMessageObject(1);
                    if (message.HasDomainKeySignature)
                    {
                        bool signatureValid = message.Signatures.DomainKeys.Verify();

                        if (signatureValid)
                        {
                            this.AddLogEntry("The domain key signature is valid.");
                        }
                        else
                        {
                            this.AddLogEntry("The domain key signature is invalid.");
                        }
                    }
                    else
                    {
                        this.AddLogEntry("The message hasn't domain key signature.");
                    }
                }

                else
                {
                    this.AddLogEntry("There is no messages in the 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();
                }
            }
        }
        private void _bRetrieveSpecificMessage_Click(object sender, EventArgs e)
        {
            // We instantiate the pop3 client.
            Pop3Client pop = new Pop3Client();

            try
            {
                _lvMessages.Items.Clear();

                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 a messaheader at a particulat index (index 1 in this sample)
                    for (int i = 1 ; i < pop.MessageCount + 1; i++)
                    {
                        ActiveUp.Net.Mail.Message message = pop.RetrieveMessageObject(i);

                        ListViewItem lvi = new ListViewItem();
                        lvi.Text = i.ToString("0000");
                        lvi.SubItems.AddRange(new string[] { message.Subject });
                        lvi.Tag = message;

                        _lvMessages.Items.Add(lvi);

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

                    }
                }

                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();
                }
            }
        }
        private void _bCheckBounce_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, _tbUserName.Text, _tbPassword.Text);

                if (pop.MessageCount > 0)
                {
                    // We retrive a message at a particular index (index 1 in this sample)
                    ActiveUp.Net.Mail.Message message = pop.RetrieveMessageObject(1);
                    
                    BounceResult br = message.GetBounceStatus();

                    if (br.Level == 3)
                    {
                        this.AddLogEntry(string.Format("Message sent to  {0} is bounced", br.Email));
                    }
                    
                    else
                    {
                        this.AddLogEntry(string.Format("Message sent to {0} is not bounced", br.Email));
                    }
                }

                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();
                }
            }
        }
Example #5
0
        private void useSelectedButton_Click(object sender, EventArgs e)
        {
            ActiveUp.Net.Mail.Pop3Client client = new ActiveUp.Net.Mail.Pop3Client();
            client.Connect(this.pop3ServerHostTextbox.Text, Convert.ToInt32(this.pop3ServerPortNumericUpDown.Value),
                this.pop3ServerUsernameTextbox.Text, this.pop3ServerPasswordTextbox.Text);

            Header gridSelection = (Header)this.dataGridView1.SelectedRows[0].DataBoundItem;

            _selectedMessage = client.RetrieveMessageObject(gridSelection.IndexOnServer);

            client.Close();
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
Example #6
0
        private void useSelectedButton_Click(object sender, EventArgs e)
        {
            ActiveUp.Net.Mail.Pop3Client client = new ActiveUp.Net.Mail.Pop3Client();
            client.Connect(this.pop3ServerHostTextbox.Text, Convert.ToInt32(this.pop3ServerPortNumericUpDown.Value),
                           this.pop3ServerUsernameTextbox.Text, this.pop3ServerPasswordTextbox.Text);

            Header gridSelection = (Header)this.dataGridView1.SelectedRows[0].DataBoundItem;

            _selectedMessage = client.RetrieveMessageObject(gridSelection.IndexOnServer);

            client.Close();
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
        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();
                }
            }
        }
        private void _bRetrieveMessageList_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);

                this.AddLogEntry("Retrieve message list");

                MessageCollection mc = new MessageCollection();
                for (int n = 1; n < pop.MessageCount + 1; n++)
                {
                    Message newMessage = pop.RetrieveMessageObject(n);
                    mc.Add(newMessage);

                    this.AddLogEntry(string.Format("Message ({0}) : {1}",n.ToString(),newMessage.Subject));
                }

            }

            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();
                }
            }
        }
        private void _bCheckMessage_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, _tbUserName.Text, _tbPassword.Text);

                if (pop.MessageCount > 0)
                {
                    // We retrive a message at a particulat index
                    ActiveUp.Net.Mail.Message message = pop.RetrieveMessageObject(1);

                    bool blackList = false;
                    // We verify if the message is from black listed server
                    foreach (System.Windows.Forms.ListViewItem lvi in _lvDefinedBlackList.Items)
                    {
                        if (message.From.Email.EndsWith(lvi.Text))
                        {
                            this.AddLogEntry(string.Format("Messages from {0} are not allowed", lvi.Text));
                            blackList = true;
                        }
                        else
                        {
                            this.AddLogEntry(string.Format("Messages from {0} are allowed", lvi.Text));
                        }

                        if (blackList)
                            break;
                    }

                    if (!blackList)
                    {
                        foreach (string blackServer in _lvBlackListServers.Items)
                        {
                            if (message.From.Email.EndsWith(blackServer))
                            {
                                this.AddLogEntry(string.Format("Messages from {0} are not allowed", blackServer));
                                blackList = true;
                            }
                            else
                            {
                                this.AddLogEntry(string.Format("Messages from {0} are allowed", blackServer));
                            }

                            if (blackList)
                                break;
                        }
                    }

                    
                }

                else
                {
                    this.AddLogEntry("There is no messages in the 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();
                }
            }
        }
        private void _bSaveAttachment_Click(object sender, EventArgs e)
        {
            if (_tbAttachmentDirectory.Text == string.Empty)
            {
                this.AddLogEntry("You have to set a directory to store the attachments.");
            }

            else
            {
                // 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)
                    {
                        ActiveUp.Net.Mail.Message message = pop.RetrieveMessageObject(1);

                        if (message.Attachments.Count > 0)
                        {
                            // Save the first attachment to the specified directory.
                            message.Attachments[0].StoreToFile(_fbdSaveDirectory.SelectedPath + message.Attachments[0].HeaderFields["FileName"]);
                            this.AddLogEntry(string.Format("Attachments '{0}' saved successfully.", message.Attachments[0].HeaderFields["FileName"]));
                        }

                        else
                        {
                            this.AddLogEntry("There is no attachments in the message.");
                        }
                    }

                    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();
                    }
                }
            }
        }
Example #11
0
        private void btnReceive_Click(object sender, EventArgs e)
        {
            this.listBox1.Items.Clear();
            // We instantiate the pop3 client.
            Pop3Client pop3Client = new Pop3Client();

            string server = this.txtPopServer.Text;
            string username = txtEmail.Text;
            string password = txtPassword.Text;
            int popPort = Convert.ToInt32(txtPopPort.Text);

            try
            {

                // pop3Client.APOPConnect(server, popPort, username, password);

                pop3Client.Connect(server, popPort, username, password);
                //   pop3Client.Authenticate(username, password, SaslMechanism.CramMd5);

                int count = pop3Client.MessageCount;

                this.AddLogEntry(string.Format("共收到{0}封 :", count));

                MessageCollection mc = new MessageCollection();

                //ActiveUp.Net.Mail.Message newMessage = pop.RetrieveMessageObject(count);
                //mc.Add(newMessage);
                // this.AddLogEntry(string.Format("Message ({0}) : {1}", count.ToString(), newMessage.Subject));

                //for (int n = count; n >= 1; n--)
                //{
                //    var msg = pop.RetrieveMessageObject(n);
                //    this.AddLogEntry(string.Format("{0}-({1}) : {2}", n.ToString(), msg.Date.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"), msg.Subject));
                //}

                string str = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                DateTime d;
                DateTime.TryParse(str, out d);

                var date = DateTime.Now.AddDays(-6);

                while (count > 0)
                {
                    var msg = pop3Client.RetrieveMessageObject(count);

                    if (msg.Date.ToLocalTime() < date)
                        break;
                    var subject = msg.Subject;

                    if (subject.Contains("问题回复-【") && subject.Contains("【") && subject.Contains("】"))
                    {
                        var index = subject.IndexOf("【") + 1;
                        var issueNo = subject.Substring(index, subject.IndexOf("】") - index);
                    }

                    this.AddLogEntry(string.Format("{0}-({1}) : {2}", count.ToString(), msg.Date.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"), msg.Subject));
                    count--;
                }

            }
            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 (pop3Client.IsConnected)
                {
                    pop3Client.Disconnect();
                }
            }
        }
        // Returns: True if all messages are proccessed. False if at least one new message is not processed.
        private bool ProcessMessagesPop(Pop3Client client, int max_messages_per_session, WaitHandle stop_event, out int processed_messages_count)
        {
            UpdateTimeCheckedIfNeeded();
            processed_messages_count = max_messages_per_session;
            var bad_messages_exist = false;
            Dictionary<int, string> new_messages;
            var stored_uidl_list = new Dictionary<int, string>();
            var stored_md5_list = new Dictionary<int, string>();

            InvokeGetStoredMessagesUIDL_MD5(stored_uidl_list, stored_md5_list);

            if (!IsUidlSupported)
            {
                _log.Info("UIDL is not supported! Account '{0}' has been skiped.", Account.EMail);
                return true;
            }

            var email_ids = client.GetUniqueIds();

            new_messages =
                email_ids
                .Where(id => !stored_uidl_list.Values.Contains(id.UniqueId))
                .OrderBy(id => id.Index)
                .ToDictionary(id => id.Index, id => id.UniqueId );


            var quota_error_flag = false;

            if (client.IsConnected)
            {
                if (new_messages.Count == 0)
                    _log.Debug("New messages not found.\r\n");
                else
                {
                    _log.Debug("Found {0} new messages.\r\n", new_messages.Count);

                    if (new_messages.Count > 1)
                    {
                        _log.Debug("Calculating order");

                        try
                        {
                            var first_header = client.RetrieveHeaderObject(new_messages.First().Key);
                            var last_header = client.RetrieveHeaderObject(new_messages.Last().Key);

                            if (first_header.Date < last_header.Date)
                            {
                                _log.Debug("Account '{0}' order is DESC", Account.EMail.Address);
                                new_messages = new_messages
                                    .OrderByDescending(item => item.Key) // This is to ensure that the newest message would be handled primarily.
                                    .ToDictionary(id => id.Key, id => id.Value);
                            }
                            else
                                _log.Debug("Account '{0}' order is ASC", Account.EMail.Address);
                        }
                        catch (Exception)
                        {
                            _log.Warn("Calculating order skipped! Account '{0}' order is ASC", Account.EMail.Address);
                        }
                    }

                    var skip_on_date = Account.BeginDate != MailBoxManager.MIN_BEGIN_DATE;

                    var skip_break_on_date = MailQueueItemSettings.PopUnorderedDomains.Contains(Account.Server.ToLowerInvariant());

                    foreach (var new_message in new_messages)
                    {
                        var has_parse_error = false;
                        
                        try
                        {
                            if (stop_event.WaitOne(0))
                            {
                                break;
                            }

                            if (max_messages_per_session == 0)
                            {
                                _log.Debug("Limit of max messages per session is exceeded!");
                                break;
                            }

                            _log.Debug("Processing new message\tid={0}\t{1}\t",
                                new_message.Key,
                                (IsUidlSupported ? "UIDL: " : "MD5: ") + new_message.Value);

                            if (!client.IsConnected)
                            {
                                _log.Warn("POP3 server is disconnected. Skip another messages.");
                                bad_messages_exist = true;
                                break;
                            }

                            Message message = null;

                            try
                            {
                                message = client.RetrieveMessageObject(new_message.Key);
                            }
                            catch (Exception ex)
                            {
                                if (ex is ParsingException || ex is IndexOutOfRangeException)
                                {
                                    _log.Error("ActiveUp Parse error: trying to save message with 'has_parse_error' flag. Exception:\r\n {0}", ex.ToString());
                                    message = GetPop3MessageAfterParseError(client, new_message.Key);
                                    has_parse_error = true;
                                }
                                else
                                    throw;
                            }

                            UpdateTimeCheckedIfNeeded();

                            if (message.Date < Account.BeginDate && skip_on_date)
                            {
                                if (!skip_break_on_date)
                                {
                                    _log.Info("Skip other messages older then {0}.", Account.BeginDate);
                                    break;
                                }
                                _log.Debug("Skip message (Date = {0}) on BeginDate = {1}", message.Date, Account.BeginDate);
                                continue;
                            }

                            var header_md5 = string.Empty;

                            if (IsUidlSupported)
                            {
                                var unique_identifier = string.Format("{0}|{1}|{2}|{3}",
                                                                      message.From.Email,
                                                                      message.Subject,
                                                                      message.DateString,
                                                                      message.MessageId);

                                header_md5 = unique_identifier.GetMd5();

                                if (!message.To.Exists(email =>
                                                       email.Email
                                                            .ToLowerInvariant()
                                                            .Equals(message.From.Email
                                                                           .ToLowerInvariant())))
                                {

                                    var found_message_id = stored_md5_list
                                        .Where(el => el.Value == header_md5)
                                        .Select(el => el.Key)
                                        .FirstOrDefault();

                                    if (found_message_id > 0)
                                    {
                                        InvokeOnUpdateUidl(found_message_id, new_message.Value);
                                        continue; // Skip saving founded message
                                    }
                                }
                            }

                            InvokeOnRetrieve(message,
                                MailFolder.Ids.inbox, 
                                IsUidlSupported ? new_message.Value : "",
                                IsUidlSupported ? header_md5 : new_message.Value, has_parse_error);
                        }
                        catch (IOException io_ex)
                        {
                            if (io_ex.Message.StartsWith("Unable to write data to the transport connection") ||
                                io_ex.Message.StartsWith("Unable to read data from the transport connection"))
                            {
                                _log.Error("ProcessMessages() Account='{0}': {1}",
                                     Account.EMail.Address, io_ex.ToString());

                                max_messages_per_session = 0; //It needed for stop messsages proccessing.
                                bad_messages_exist = true;
                                break;
                            }
                        }
                        catch (MailBoxOutException ex)
                        {
                            _log.Info("ProcessMessages() Tenant={0} User='******' Account='{2}': {3}",
                                Account.TenantId, Account.UserId, Account.EMail.Address, ex.Message);
                            bad_messages_exist = true;
                            break;
                        }
                        catch (TenantQuotaException qex)
                        {
                            _log.Info("Tenant {0} quota exception: {1}", Account.TenantId, qex.Message);
                            quota_error_flag = true;
                        }
                        catch (Exception e)
                        {
                            bad_messages_exist = true;
                            _log.Error("ProcessMessages() Tenant={0} User='******' Account='{2}', MailboxId={3}, MessageIndex={4}, UIDL='{5}' Exception:\r\n{6}\r\n",
                                Account.TenantId, Account.UserId, Account.EMail.Address, Account.MailBoxId, new_message.Key, new_message.Value, e.ToString());
                        }

                        UpdateTimeCheckedIfNeeded();
                        max_messages_per_session--;
                    }
                }
            }
            else
            {
                _log.Debug("POP3 server is disconnected.");
                bad_messages_exist = true;
            }

            InvokeOnDone(quota_error_flag);

            processed_messages_count -= max_messages_per_session;
            return !bad_messages_exist && max_messages_per_session > 0;
        }