public void Fetch(Action<Message> process) { var seenUids = File.Exists(seenUidsFile) ? new HashSet<string>(File.ReadAllLines(seenUidsFile)) : new HashSet<string>(); using (var client = new Pop3Client()) { pop3Authorize(client); List<string> messageUids = client.GetMessageUids(); foreach (var msgInfo in messageUids.Select((uid, index) => new{uid, index}).Where(msgInfo => !seenUids.Contains(msgInfo.uid))) { try { Message message = client.GetMessage(msgInfo.index+1); message.Save(new FileInfo(msgInfo.uid + ".mime")); process(message); seenUids.Add(msgInfo.uid); } catch(Exception e) { log.Error("Error while processing message " + msgInfo + "\r\n" + e); } } File.WriteAllLines(seenUidsFile, seenUids); for(int i=messageUids.Count; i>=1; i--) client.DeleteMessage(i); } }
public void processMail() { Logger.info("Проверка почты: "); try { Pop3Client client = new Pop3Client(); client.Connect(Settings.Single.smtpServer, 110, false); client.Authenticate(Settings.Single.smtpUser, Settings.Single.smtpPassword); List<string> msgs = client.GetMessageUids(); Logger.info(String.Format("Получено {0} сообщений ", msgs.Count)); for (int i = 0; i < msgs.Count; i++) { try { Logger.info("Чтение письма " + i.ToString()); Message msg = client.GetMessage(i); List<MessagePart> files = msg.FindAllAttachments(); Logger.info(String.Format("Прикреплено {0} файлов", files.Count)); if (files.Count == 1) { Logger.info(String.Format("Обработка файла {0}", files[0].FileName)); MessagePart file = files[0]; string pbrData = file.GetBodyAsText(); PBR.getFromText(pbrData); } } catch (Exception e) { Logger.error("Ошибка при обработке письма " + i); } } } catch (Exception e) { Logger.error("Ошибка при работе с почтой " + e.ToString()); } }
/// <summary> /// fetches messages from a pop email server server /// </summary> /// <param name="hostname">link to pop server</param> /// <param name="port">port of pop server</param> /// <param name="useSsl">using an ssl?</param> /// <param name="username">username to login with at the pop server</param> /// <param name="password">password</param> /// <param name="seenUids">remove messages</param> /// <returns>a list of messages</returns> private static List<Message> FetchMessages(string hostname, int port, bool useSsl, string username, string password, List<string> seenUids) { // 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); // Fetch all the current uids seen List<string> uids = client.GetMessageUids(); // Create a list we can return with all new messages List<Message> newMessages = new List<Message>(); // All the new messages not seen by the POP3 client for (int i = 0; i < uids.Count; i++) { string currentUidOnServer = uids[i]; if (!seenUids.Contains(currentUidOnServer)) { // We have not seen this message before. // Download it and add this new uid to seen uids // the uids list is in messageNumber order - meaning that the first // uid in the list has messageNumber of 1, and the second has // messageNumber 2. Therefore we can fetch the message using // i + 1 since messageNumber should be in range [1, messageCount] Message unseenMessage = client.GetMessage(i + 1); // Add the message to the new messages newMessages.Add(unseenMessage); // Add the uid to the seen uids, as it has now been seen seenUids.Add(currentUidOnServer); } } // Return our new found messages return newMessages; } }
private List<Message> FetchUnseenMessages(string hostname, int port, bool useSsl, string username, string password, List<string> seenUids) { List<Message> list3; List<Message> list = new List<Message>(); try { using (Pop3Client client = new Pop3Client()) { int num; client.Connect(hostname, port, useSsl); client.Authenticate(username, password); List<string> messageUids = client.GetMessageUids(); if (messageUids.Count > 0) { num = messageUids.Count; } else { Console.Write("No Emails found in that Email account"); num = 0; } for (int i = 0; i < num; i++) { string item = messageUids[i]; if (!seenUids.Contains(item)) { Message message = client.GetMessage(i + 1); list.Add(message); seenUids.Add(item); } } list3 = list; } } catch (Exception exception) { Console.Write(exception.Message); list3 = list; } return list3; }
public void TestGetMessageUids() { const string welcomeMessage = "+OK"; const string okUsername = "******"; const string okPassword = "******"; const string messageUidAccepted = "+OK"; const string messageUid1 = "1 psycho"; // Message 1 has UID psycho const string messageUid2 = "2 lord"; // Message 2 has UID lord const string uidListEnded = "."; const string serverResponses = welcomeMessage + "\r\n" + okUsername + "\r\n" + okPassword + "\r\n" + messageUidAccepted + "\r\n" + messageUid1 + "\r\n" + messageUid2 + "\r\n" + uidListEnded + "\r\n"; Stream inputStream = new MemoryStream(Encoding.ASCII.GetBytes(serverResponses)); Stream outputStream = new MemoryStream(); Pop3Client client = new Pop3Client(); client.Connect(new CombinedStream(inputStream, outputStream)); client.Authenticate("test", "test"); // Get the UIDs for all the messages in sorted order from 1 and upwards List<string> uids = client.GetMessageUids(); // The list should have size 2 Assert.AreEqual(2, uids.Count); // The first entry should have uid psycho Assert.AreEqual("psycho", uids[0]); // The second entry should have uid lord Assert.AreEqual("lord", uids[1]); }
/// <summary> /// Example showing: /// - how to fetch all messages from a POP3 server /// </summary> /// <param name="hostname">Hostname of the server. For example: pop3.live.com</param> /// <param name="port">Host port to connect to. Normally: 110 for plain POP3, 995 for SSL POP3</param> /// <param name="useSsl">Whether or not to use SSL to connect to server</param> /// <param name="username">Username of the user on the server</param> /// <param name="password">Password of the user on the server</param> /// <returns>All Messages on the POP3 server</returns> public void ProcessNewMessages(string hostname, int port, bool useSsl, string username, string password) { // The client disconnects from the server when being disposed using (Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect(hostname, port, useSsl); // Authenticate ourselves towards the server client.Authenticate(username, password); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); // We don't want to download all messages // List<Message> allMessages = new List<Message>(messageCount); List<string> uids = client.GetMessageUids(); // Messages are numbered in the interval: [1, messageCount] // Ergo: message numbers are 1-based. for (int i = 1; i <= messageCount; i++) { String uid = client.GetMessageUid(i); if (seenUids.Contains(uid)) { continue; } Message m = client.GetMessage(i); if (m.MessagePart != null) { if (m.MessagePart.MessageParts != null) { for (int j = 0; j < m.MessagePart.MessageParts.Count; j++) { //if (m.MessagePart.MessageParts[j].Body != null) //{ // System.Console.Write(ASCIIEncoding.ASCII.GetString(m.MessagePart.MessageParts[j].Body)); //} if (((m.MessagePart.MessageParts[j].IsAttachment) && (m.MessagePart.MessageParts[j].FileName == "invite.ics")) || ((m.MessagePart.MessageParts[j].ContentType != null) && (m.MessagePart.MessageParts[j].ContentType.MediaType.StartsWith("text/calendar")))) { //System.Console.Write(ASCIIEncoding.ASCII.GetString(m.MessagePart.MessageParts[j].Body)); List<String> lines = ParseICalendar(m.MessagePart.MessageParts[j].Body); // Then find the relevant lines. // Make sure this is a VCALENDAR attachment. if ((lines != null) && lines[0].StartsWith("BEGIN:VCALENDAR")) { Meeting meeting = new Meeting(); ExtractAttributes(lines, meeting); String json = meeting.ToJson(); System.Console.WriteLine("Processing Message: " + uid); System.Console.WriteLine("JSON: " + json); seenUids.Add(uid); //PostJsonToWebServer(json); } } } } } //System.Console.Write(ASCIIEncoding.ASCII.GetString(m.MessagePart.MessageParts[0].Body)); //allMessages.Add(m); } } }
/////////////////////////////////////////////////////////////////////// protected async void fetch_messages(string user, string password, int projectid) { List<string> messages = null; Regex regex = new Regex("\r\n"); using (Pop3Client client = new Pop3Client()) { try { write_line("****connecting to server:"); int port = 110; if (Pop3Port != "") { port = Convert.ToInt32(Pop3Port); } bool use_ssl = false; if (Pop3UseSSL != "") { use_ssl = Pop3UseSSL == "1" ? true : false; } write_line("Connecting to pop3 server"); client.Connect(Pop3Server, port, use_ssl); write_line("Autenticating"); client.Authenticate(user, password); write_line("Getting list of documents"); messages = client.GetMessageUids(); } catch (Exception e) { write_line("Exception trying to talk to pop3 server"); write_line(e); return; } int message_number = 0; // loop through the messages for (int i = 0; i < messages.Count; i++) { heartbeat_datetime = DateTime.Now; // because the watchdog is watching if (state != service_state.STARTED) { break; } // fetch the message write_line("Getting Message:" + messages[i]); message_number = Convert.ToInt32(messages[i]); Message mimeMessage = null; try { mimeMessage = client.GetMessage(message_number); } catch (Exception exception) { write_to_log("Error getting message"); write_to_log(exception.ToString()); continue; } // for diagnosing problems if (MessageOutputFile != "") { File.WriteAllBytes(MessageOutputFile, mimeMessage.RawMessage); } // break the message up into lines string from = mimeMessage.Headers.From.Address; string subject = mimeMessage.Headers.Subject; write_line("\nFrom: " + from); write_line("Subject: " + subject); if (!string.IsNullOrEmpty(SubjectMustContain) && subject.IndexOf(SubjectMustContain, StringComparison.OrdinalIgnoreCase) < 0) { write_line("skipping because subject does not contain: " + SubjectMustContain); continue; } bool bSkip = false; foreach (string subjectCannotContainString in SubjectCannotContainStrings) { if (!string.IsNullOrEmpty(subjectCannotContainString)) { if (subject.IndexOf(subjectCannotContainString, StringComparison.OrdinalIgnoreCase) >= 0) { write_line("skipping because subject cannot contain: " + subjectCannotContainString); bSkip = true; break; // done checking, skip this message } } } if (bSkip) { continue; } if (!string.IsNullOrEmpty(FromMustContain) && from.IndexOf(FromMustContain, StringComparison.OrdinalIgnoreCase) < 0) { write_line("skipping because from does not contain: " + FromMustContain); continue; // that is, skip to next message } foreach (string fromCannotContainStrings in FromCannotContainStrings) { if (!string.IsNullOrEmpty(fromCannotContainStrings)) { if (from.IndexOf(fromCannotContainStrings, StringComparison.OrdinalIgnoreCase) >= 0) { write_line("skipping because from cannot contain: " + fromCannotContainStrings); bSkip = true; break; // done checking, skip this message } } } if (bSkip) { continue; } write_line("calling insert_bug.aspx"); bool useBugId = false; // Try to parse out the bugid from the subject line string bugidString = TrackingIdString; if (string.IsNullOrEmpty(TrackingIdString)) { bugidString = "DO NOT EDIT THIS:"; } int pos = subject.IndexOf(bugidString, StringComparison.OrdinalIgnoreCase); if (pos >= 0) { // position of colon pos = subject.IndexOf(":", pos); pos++; // position of close paren int pos2 = subject.IndexOf(")", pos); if (pos2 > pos) { string bugid_string = subject.Substring(pos, pos2 - pos); write_line("BUGID=" + bugid_string); try { int bugid = Int32.Parse(bugid_string); useBugId = true; write_line("updating existing bug " + Convert.ToString(bugid)); } catch (Exception e) { write_line("bugid not numeric " + e.Message); } } } // send request to web server try { HttpClientHandler handler = new HttpClientHandler { AllowAutoRedirect = true, UseCookies = true, CookieContainer = new CookieContainer() }; using (var httpClient = new HttpClient(handler)) { var loginParameters = new Dictionary<string, string> { { "user", ServiceUsername }, { "password", ServicePassword } }; HttpContent loginContent = new FormUrlEncodedContent(loginParameters); var loginResponse = await httpClient.PostAsync(LoginUrl, loginContent); loginResponse.EnsureSuccessStatusCode(); string rawMessage = Encoding.Default.GetString(mimeMessage.RawMessage); var postBugParameters = new Dictionary<string, string> { { "projectId", Convert.ToString(projectid) }, { "fromAddress", from }, { "shortDescription", subject}, { "message", rawMessage} //Any other paramters go here }; if (useBugId) { postBugParameters.Add("bugId", bugidString); } HttpContent bugContent = new FormUrlEncodedContent(postBugParameters); var postBugResponse = await httpClient.PostAsync(InsertBugUrl, bugContent); postBugResponse.EnsureSuccessStatusCode(); } if (MessageInputFile == "" && DeleteMessagesOnServer == "1") { write_line("sending POP3 command DELE"); client.DeleteMessage(message_number); } } catch (Exception e) { write_line("HttpWebRequest error url=" + InsertBugUrl); write_line(e); write_line("Incrementing total error count"); total_error_count++; } // examine response if (total_error_count > TotalErrorsAllowed) { write_line("Stopping because total error count > TotalErrorsAllowed"); stop(); } } // end for each message if (MessageInputFile == "") { write_line("\nsending POP3 command QUIT"); client.Disconnect(); } else { write_line("\nclosing input file " + MessageInputFile); } } }
//получение аттачментов public void GetAttach(DateTime date) { string s = @"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\MyDataBase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; DataSet ds = new DataSet(); SqlDataAdapter daBranch = new SqlDataAdapter("Select * from Branch", s); SqlDataAdapter daProv = new SqlDataAdapter("Select * from Provisioner", s); daBranch.Fill(ds, "Branch"); daProv.Fill(ds, "Provisioner"); DataTable dtBranch = ds.Tables["Branch"]; DataTable dtProv = ds.Tables["Provisioner"]; var emailBrach = dtBranch.AsEnumerable() .Select(t => t.Field<string>("email")); var emailProv = dtProv.AsEnumerable() .Select(t => t.Field<string>("email")); using (Pop3Client client = new Pop3Client()) { client.Connect("pop3.mail.ru", 110, false); client.Authenticate("*****@*****.**", "mag17012014"); List<string> listIdMsg = client.GetMessageUids();//получаем список id всех писем for (int i = 1; i <= listIdMsg.Count(); i++) { OpenPop.Mime.Message msg = client.GetMessage(i); //получаум письмо по Id; string address = msg.Headers.From.Address.ToString(); //получаем адрес отправителя DateTime dateMsg = DateTime.Parse(msg.Headers.Date); //получаем дату сообщения List<MessagePart> listAttach = msg.FindAllAttachments(); //получаем все аттачменты сообщения foreach (var elem in emailBrach) { if (address.Substring(0, address.Length) == elem && dateMsg.ToString().Substring(0, 10) == date.ToString().Substring(0, 10)) { if (listAttach.Count > 0) { foreach (MessagePart attach in listAttach) { string filePath = Path.Combine(@"D:\MailBranch", attach.FileName); attach.Save(new FileInfo(filePath)); } } } } foreach (var elem in emailProv) { if (address.Substring(0, address.Length) == elem && dateMsg.ToString().Substring(0, 10) == date.ToString().Substring(0, 10)) { if (listAttach.Count > 0) { foreach (MessagePart attach in listAttach) { string filePath = Path.Combine(@"D:\MailProvisioner", attach.FileName); attach.Save(new FileInfo(filePath)); } } } } } } }
/////////////////////////////////////////////////////////////////////// protected void fetch_messages(string user, string password, int projectid) { List<string> messages = null; Regex regex = new Regex("\r\n"); using (Pop3Client client = new Pop3Client()) { try { write_line("****connecting to server:"); int port = 110; if (Pop3Port != "") { port = Convert.ToInt32(Pop3Port); } bool use_ssl = false; if (Pop3UseSSL != "") { use_ssl = Pop3UseSSL == "1" ? true : false; } write_line("Connecting to pop3 server"); client.Connect(Pop3Server, port, use_ssl); write_line("Autenticating"); client.Authenticate(user, password); write_line("Getting list of documents"); messages = client.GetMessageUids(); } catch (Exception e) { write_line("Exception trying to talk to pop3 server"); write_line(e); return; } int message_number = 0; // loop through the messages for (int i = 0; i < messages.Count; i++) { heartbeat_datetime = DateTime.Now; // because the watchdog is watching if (state != service_state.STARTED) { break; } // fetch the message write_line("Getting Message:" + messages[i]); message_number = Convert.ToInt32(messages[i]); Message mimeMessage = null; try { mimeMessage = client.GetMessage(message_number); } catch (Exception exception) { write_to_log("Error getting message" ); write_to_log(exception.ToString()); continue; } // for diagnosing problems if (MessageOutputFile != "") { File.WriteAllBytes(MessageOutputFile, mimeMessage.RawMessage); } // break the message up into lines string from = mimeMessage.Headers.From.Address; string subject = mimeMessage.Headers.Subject; write_line("\nFrom: " + from); write_line("Subject: " + subject); if (!string.IsNullOrEmpty(SubjectMustContain) && subject.IndexOf(SubjectMustContain, StringComparison.OrdinalIgnoreCase) < 0) { write_line("skipping because subject does not contain: " + SubjectMustContain); continue; } bool bSkip = false; foreach (string subjectCannotContainString in SubjectCannotContainStrings) { if (!string.IsNullOrEmpty(subjectCannotContainString)) { if (subject.IndexOf(subjectCannotContainString, StringComparison.OrdinalIgnoreCase) >= 0) { write_line("skipping because subject cannot contain: " + subjectCannotContainString); bSkip = true; break; // done checking, skip this message } } } if (bSkip) { continue; } if (!string.IsNullOrEmpty(FromMustContain) && from.IndexOf(FromMustContain, StringComparison.OrdinalIgnoreCase) < 0) { write_line("skipping because from does not contain: " + FromMustContain); continue; // that is, skip to next message } foreach (string fromCannotContainStrings in FromCannotContainStrings) { if (!string.IsNullOrEmpty(fromCannotContainStrings)) { if (from.IndexOf(fromCannotContainStrings, StringComparison.OrdinalIgnoreCase) >= 0) { write_line("skipping because from cannot contain: " + fromCannotContainStrings); bSkip = true; break; // done checking, skip this message } } } if (bSkip) { continue; } write_line("calling insert_bug.aspx"); string Url = InsertBugUrl; // Try to parse out the bugid from the subject line string bugidString = TrackingIdString; if (string.IsNullOrEmpty(TrackingIdString)) { bugidString = "DO NOT EDIT THIS:"; } int pos = subject.IndexOf(bugidString, StringComparison.OrdinalIgnoreCase); if (pos >= 0) { // position of colon pos = subject.IndexOf(":", pos); pos++; // position of close paren int pos2 = subject.IndexOf(")", pos); if (pos2 > pos) { string bugid_string = subject.Substring(pos, pos2 - pos); write_line("BUGID=" + bugid_string); try { int bugid = Int32.Parse(bugid_string); Url += "?bugid=" + Convert.ToString(bugid); write_line("updating existing bug " + Convert.ToString(bugid)); } catch (Exception e) { write_line("bugid not numeric " + e.Message); } } } string rawMessage = Encoding.Default.GetString(mimeMessage.RawMessage); string post_data = "username="******"&password="******"&projectid=" + Convert.ToString(projectid) + "&from=" + HttpUtility.UrlEncode(from) + "&short_desc=" + HttpUtility.UrlEncode(subject) + "&message=" + HttpUtility.UrlEncode(rawMessage); byte[] bytes = Encoding.UTF8.GetBytes(post_data); // send request to web server HttpWebResponse res = null; try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Url); req.Credentials = CredentialCache.DefaultCredentials; req.PreAuthenticate = true; //req.Timeout = 200; // maybe? //req.KeepAlive = false; // maybe? req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = bytes.Length; Stream request_stream = req.GetRequestStream(); request_stream.Write(bytes, 0, bytes.Length); request_stream.Close(); res = (HttpWebResponse)req.GetResponse(); } catch (Exception e) { write_line("HttpWebRequest error url=" + Url); write_line(e); } // examine response if (res != null) { int http_status = (int)res.StatusCode; write_line(Convert.ToString(http_status)); string http_response_header = res.Headers["BTNET"]; res.Close(); if (http_response_header != null) { write_line(http_response_header); // only delete message from pop3 server if we // know we stored in on the web server ok if (MessageInputFile == "" && http_status == 200 && DeleteMessagesOnServer == "1" && http_response_header.IndexOf("OK") == 0) { write_line("sending POP3 command DELE"); client.DeleteMessage(message_number); } } else { write_line("BTNET HTTP header not found. Skipping the delete of the email from the server."); write_line("Incrementing total error count"); total_error_count++; } } else { write_line("No response from web server. Skipping the delete of the email from the server."); write_line("Incrementing total error count"); total_error_count++; } if (total_error_count > TotalErrorsAllowed) { write_line("Stopping because total error count > TotalErrorsAllowed"); stop(); } } // end for each message if (MessageInputFile == "") { write_line("\nsending POP3 command QUIT"); client.Disconnect(); } else { write_line("\nclosing input file " + MessageInputFile); } } }
private void toolStripMenuItem1_Click(object sender, EventArgs e) { // The client disconnects from the server when being disposed using (Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect(config.host, config.port, config.ssl); // Authenticate ourselves towards the server client.Authenticate(config.login, config.password); // Fetch all the current uids seen List<string> uids = client.GetMessageUids(); // All the new messages not seen by the POP3 client int length = uids.Count; for (int i = 0; i < length; i++) { string currentUidOnServer = uids[i]; if (!readMails.Contains(currentUidOnServer)) { unreadMails++; // Add the message to the new messages readMails.Add(uids[i]); } } label1.Text = unreadMails.ToString(); // Return our new found messages } }
private void RefreshingThread() { Pop3Client client = new Pop3Client(); client.Connect(config.host, config.port, config.ssl); client.Authenticate(config.login, config.password); List<string> uids; int length = 0; while(true) { uids = client.GetMessageUids(); length = uids.Count; for (int i = 0; i < length; i++) { string currentUidOnServer = uids[i]; if (!readMails.Contains(currentUidOnServer)) { unreadMails++; // Add the message to the new messages readMails.Add(uids[i]); } } //outLabel.Text = unreadMails.ToString(); Thread.Sleep(config.msRefreshDelay); } client.Disconnect(); }
private void ReceivingLoop() { using (Pop3Client client = new Pop3Client()) { for (; ; ) { try { if (!client.Connected) { client.Connect("pop.gmail.com", 995, true); client.Authenticate(mail_username, mail_password); List<string> uids = client.GetMessageUids(); List<Message> newMessages = new List<Message>(); for (int i = 0; i < uids.Count; i++) { string currentUidOnServer = uids[i]; Message unseenMessage = client.GetMessage(i + 1); newMessages.Add(unseenMessage); } for (int i = 0; i < newMessages.Count; i++) { Console.WriteLine("Message: " + newMessages.ElementAt(i).ToMailMessage().Body); ConvertReceivedToOrder(newMessages.ElementAt(i).Headers.Subject, newMessages.ElementAt(i).ToMailMessage().Body); } } } catch (Exception e) { Console.WriteLine("Cannot connect: " + e.Message); Thread.Sleep(2000); } finally { try { if (client.Connected) client.Disconnect(); do Thread.Sleep(500); while (client.Connected); } catch (Exception e) { Console.WriteLine("Cannot disconnect - reset connection: " + e.Message); client.Reset(); Thread.Sleep(2000); } } } } }
/// <summary> /// Example showing: /// - how to use UID's (unique ID's) of messages from the POP3 server /// - how to download messages not seen before /// (notice that the POP3 protocol cannot see if a message has been read on the server /// before. Therefore the client need to maintain this state for itself) /// </summary> /// <param name="seenUids"> /// List of UID's of all messages seen before. /// New message UID's will be added to the list. /// Consider using a HashSet if you are using >= 3.5 .NET /// </param> /// <returns>A List of new Messages on the server</returns> public dsTables GetUnseenMail(List<string> seenUids) { // The client disconnects from the server when being disposed using (Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect(POPHost, POPPort, EnableSSL); // Authenticate ourselves towards the server client.Authenticate(POPUsername, POPPassword); // Fetch all the current uids seen List<string> uids = client.GetMessageUids(); // Create a list we can return with all new messages List<Message> newMessages = new List<Message>(); // All the new messages not seen by the POP3 client for (int i = 0; i < uids.Count; i++) { string currentUidOnServer = uids[i]; if (!seenUids.Contains(currentUidOnServer)) { // We have not seen this message before. // Download it and add this new uid to seen uids // the uids list is in messageNumber order - meaning that the first // uid in the list has messageNumber of 1, and the second has // messageNumber 2. Therefore we can fetch the message using // i + 1 since messageNumber should be in range [1, messageCount] Message unseenMessage = client.GetMessage(i + 1); // Add the message to the new messages newMessages.Add(unseenMessage); // Add the uid to the seen uids, as it has now been seen seenUids.Add(currentUidOnServer); PrepareMessageAndAttachments(newMessages); } } } return DownloadedMessages; }