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); //Display Msg Count this.AddLogEntry(string.Format("Message Count: {0}", pop.MessageCount.ToString())); } 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 _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(); } } }
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 _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(); } } }
private void _bRetriveToFile_Click(object sender, EventArgs e) { if (_tbMessageFilename.Text == string.Empty) { this.AddLogEntry("You have to set a message filename."); } 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) { // Store the message in the specified filename. pop.StoreMessage(1, false, _tbMessageFilename.Text); this.AddLogEntry("Message saved successfully."); } 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 _bFilterEmails_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); AddressCollection ac; HeaderCollection hc = new HeaderCollection(); //Retrive a message headers for (int n = 1; n < pop.MessageCount + 1; n++) { Header h = pop.RetrieveHeaderObject(n); ac = new AddressCollection(); ac.Add(h.From); ac = Validator.Filter(ac); //If address is not filtered if (ac.Count > 0) { hc.Add(h); } } this.AddLogEntry(string.Format(" {0} messages passed the filter", hc.Count.ToString())); } 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 retrieveMessagesButton_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); HeaderCollection headers = new HeaderCollection(); for(int index = 1; index <= client.MessageCount; index++) headers.Add(client.RetrieveHeaderObject(index)); client.Close(); this.dataGridView1.DataSource = headers; }
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 _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(); } } }
private void retrieveMessagesButton_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); HeaderCollection headers = new HeaderCollection(); for (int index = 1; index <= client.MessageCount; index++) { headers.Add(client.RetrieveHeaderObject(index)); } client.Close(); this.dataGridView1.DataSource = headers; }
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 _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(); } } }
private static BaseProtocolClient BuildMailClient(MailClientType type) { BaseProtocolClient client; switch (type) { case MailClientType.Imap: client = new Imap4Client(); break; case MailClientType.Pop3: client = new Pop3Client(); break; case MailClientType.Smtp: client = new SmtpClient(); break; default: throw new ArgumentException(String.Format("Unknown client type: {0}", type)); } try { client.SendTimeout = Convert.ToInt32(WebConfigurationManager.AppSettings["mail.send-tcp-timeout"] ?? "30000"); client.ReceiveTimeout = Convert.ToInt32(WebConfigurationManager.AppSettings["mail.recieve-tcp-timeout"] ?? "30000"); client.CertificatePermit = Convert.ToBoolean(WebConfigurationManager.AppSettings["mail.certificate-permit"] ?? "false"); } catch (Exception e) { client.ReceiveTimeout = 30000; client.SendTimeout = 30000; client.CertificatePermit = false; var logger = LogManager.GetLogger("MailBoxManager"); var message = String.Format("Problems with config parsing for SendTimeout: {0} or RecieveTimeout: {1}. Values was reseted to default - 30000.\n", WebConfigurationManager.AppSettings["mail.send-tcp-timeout"], WebConfigurationManager.AppSettings["mail.recieve-tcp-timeout"]); logger.DebugException(message, e); } return client; }
/// <summary> /// Connect the pop3 client. /// </summary> /// <param name="accountInfo">The account information.</param> public void Connect(AccountSettings.AccountInfo accountInfo) { if (accountInfo != null && accountInfo.MailAccountType == AccountType.POP3) { this._pop3Client = new Pop3Client(); int port = accountInfo.InPort; bool ssl = accountInfo.IncomingIsSSL; string serverName = accountInfo.IncomingServerName; string user = accountInfo.EmailAddress; string password = accountInfo.Password; bool useInPort = accountInfo.InPortEnabled; if (ssl) { if (useInPort) { this._pop3Client.ConnectSsl(serverName, port, user, password); } else { this._pop3Client.ConnectSsl(serverName, user, password); } } else { if (useInPort) { this._pop3Client.Connect(serverName, port, user, password); } else { this._pop3Client.Connect(serverName, user, password); } } } }
/// <summary> /// Connect the pop client. /// </summary> /// <param name="accountInfo">The information account</param> public void Connect(string pop, string login, string _password, string printer) { try { this._pop3Client = new Pop3Client(); this.pop3 = pop; this.login = login; this.password = _password; this._pop3Client.ConnectSsl(this.pop3, this.login, this.password); } catch (Exception) { if (this._pop3Client.IsConnected) this._pop3Client = new Pop3Client(); MessageBox.Show("Could not connect to Pop3 Server" + "\n" + "Verifies The settings", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } if(printer == null || printer == String.Empty) { MessageBox.Show("No printer has been selected", "No printer", MessageBoxButtons.OK, MessageBoxIcon.Information); } this.printerName = printer; }
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 }
private Message GetPop3MessageAfterParseError(Pop3Client client, int message_index) { var header = client.RetrieveHeaderObject(message_index); var eml_message_string = client.RetrieveMessageString(message_index); var message = new Message(header); message.AddAttachmentFromString("original_message.eml", eml_message_string); return message; }
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(); } } }
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 GetCapa(Pop3Client client) { try { var capaParams = client.GetServerCapabilities(); if (capaParams.Length <= 0) return; var index = Array.IndexOf(capaParams, "LOGIN-DELAY"); if (index > -1) { int delay; if (int.TryParse(capaParams[index], NumberStyles.Integer, CultureInfo.InvariantCulture, out delay)) Account.ServerLoginDelay = delay; } _isUidlSupported = Array.IndexOf(capaParams, "UIDL") > -1; } catch { // CAPA NOT SUPPORTED try { // CHECK UIDL SUPPORT client.GetUniqueIds(); _isUidlSupported = true; } catch { // UIDL NOT SUPPORTED _isUidlSupported = false; } } }
private Dictionary<int, string> GetPop3NewMessagesIDs(Pop3Client client) { var newMessages = new Dictionary<int, string>(); var emailIds = client.GetUniqueIds(); if (!emailIds.Any() || emailIds.Count == Account.MessagesCount) return newMessages; var i = 0; var chunk = tasksConfig.ChunkOfPop3Uidl; var emails = emailIds.Skip(i).Take(chunk).ToList(); do { var checkList = emails.Select(e => e.UniqueId).Distinct().ToList(); var existingUidls = mailBoxManager.CheckUidlExistance(Account.MailBoxId, checkList); if (!existingUidls.Any()) { foreach ( var item in emails.Select(email => new KeyValuePair<int, string>(email.Index, email.UniqueId)) .Where(item => !newMessages.Contains(item))) { newMessages.Add(item.Key, item.Value); } } else if (existingUidls.Count != emails.Count) { foreach (var item in (from email in emails where !existingUidls.Contains(email.UniqueId) select new KeyValuePair<int, string>(email.Index, email.UniqueId)).Where( item => !newMessages.Contains(item))) { newMessages.Add(item.Key, item.Value); } } i += chunk; emails = emailIds.Skip(i).Take(chunk).ToList(); } while (emails.Any()); return newMessages; }
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(); } } } }
// 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; }