public List <MailMessage> ObtenerMensajes() { int cantidadmensajes = ObtenerCantidadMensajes(); List <MailMessage> mensajes = new List <MailMessage>(); for (int i = 1; i <= cantidadmensajes; i++) { try { MailMessage mensaje = cliente.GetMessage(i).ToMailMessage(); String fechaStr = cliente.GetMessageHeaders(i).DateSent.ToString("dd/MM/yyyy"); mensaje.Subject = mensaje.Subject + fechaStr; mensajes.Add(mensaje); } catch (Exception ex) { continue; } } return(mensajes); }
public static void Run() { // ExStart:RetrievingEmailHeaders // Create an instance of the Pop3Client class Pop3Client client = new Pop3Client(); // Specify host, username. password, Port and SecurityOptions for your client client.Host = "pop.gmail.com"; client.Username = "******"; client.Password = "******"; client.Port = 995; client.SecurityOptions = SecurityOptions.Auto; try { HeaderCollection headers = client.GetMessageHeaders(1); for (int i = 0; i < headers.Count; i++) { // Display key and value in the header collection Console.Write(headers.Keys[i]); Console.Write(" : "); Console.WriteLine(headers.Get(i)); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { client.Dispose(); } // ExEnd:RetrievingEmailHeaders Console.WriteLine(Environment.NewLine + "Displayed header information from emails using POP3 "); }
public string GetMailLink() { Message message = null; int allMessageCount; MessagePart plainTextPart = null; bool flag = true; while (flag) { using (Pop3Client client = new Pop3Client()) { client.Connect(GetPopServer(), _Pop3Port, _Pop3SSL); client.Authenticate(String.Format(GetAccountGmail(), String.Empty), GetAccountPassword(), AuthenticationMethod.UsernameAndPassword); allMessageCount = client.GetMessageCount(); for (int i = 1; i <= allMessageCount; i++) { MessageHeader mes = client.GetMessageHeaders(i); if (mes.From.Address.Contains(_MailActiveLinkFromAdrees) && mes.Subject.Contains("Account activation")) { message = client.GetMessage(i); plainTextPart = message.FindFirstHtmlVersion(); flag = false; } } client.Disconnect(); } } return(Regex.Match(plainTextPart.GetBodyAsText(), _RegExpPatternForActivationLink).ToString().Replace("\"", String.Empty)); }
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); }
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); } }
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); }
// ----------------------------------------------------------- / 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); }
/// <summary> /// Возвращает перечень подтвержденных/неподтвержденных заявок /// </summary> /// <param name="email"></param> /// <param name="user"></param> /// <param name="password"></param> /// <returns></returns> public static List <Models.ClamedServices> GetClaimResult(string server, string user, string password) { List <Models.ClamedServices> claims = new List <Models.ClamedServices>(); Pop3Client client = new Pop3Client(); ///---Проверка ящика с подтвержденными сообщениями if (client.Connected) { client.Disconnect(); } client.Connect(server, 110, false); client.Authenticate(user, password); int count = client.GetMessageCount(); List <string> uids = client.GetMessageUids(); List <string> seenUids = GetSeenUIDs(); for (int i = 0; i < uids.Count; i++) { string currentUidOnServer = uids[i]; if (!seenUids.Contains(currentUidOnServer)) { try { string body; Message unseenMessage = client.GetMessage(i + 1); MessagePart plainTextPart = unseenMessage.FindFirstPlainTextVersion(); if (plainTextPart != null) { body = plainTextPart.GetBodyAsText(); ///---Проверяю сообщение на предмет валидного secret. if (body.Trim().Length >= 42) { MessageHeader headers = client.GetMessageHeaders(i + 1); string secret = body.Trim().Substring(6, body.Trim().Length - 6); ///---Проверяю есть ли в базе запрос с данным secret if (Lib.ApplicationHelper.SecretExists(secret)) { claims.Add(new Models.ClamedServices() { secret = secret, user = Lib.ADAuth.GetUserByEmail(headers.From.Address.Trim()) }); } } } } catch (Exception e) { } ///---Помечаю сообщение как прочитанное MarkMessageAsReaded(currentUidOnServer); } } return(claims); }
//------------------------------------------------------------------- public CResultAErreur RetrieveMail(C2iMail mail) { CResultAErreur result = CResultAErreur.True; if (mail.CompteMail == null) { result.EmpileErreur("Erreur dans CRecepteurMail: mail est nul"); } CParametreCompteMail parametre = mail.CompteMail.ParametreCompteMail; if (parametre == null) { result.EmpileErreur("Erreur dans CRecepteurMail: Le ¨Parametre de compte est nul"); return(result); } mail.BeginEdit(); using (Pop3Client client = new Pop3Client()) { try { client.Connect(parametre.PopServer, parametre.PopPort, parametre.UseSsl); // Authenticate ourselves towards the server client.Authenticate(parametre.User, parametre.Password); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); // Messages are numbered in the interval: [1, messageCount] // Ergo: message numbers are 1-based. string strIdRecherche = mail.MessageId; for (int i = 1; i <= messageCount; i++) { MessageHeader messageHead = client.GetMessageHeaders(i); if (messageHead.MessageId == strIdRecherche) // Bingo ! C'est lui que je cherche { Message messageComplet = client.GetMessage(i); mail.FillFromMessage(messageComplet); } } } catch (Exception exception) { result.EmpileErreur(exception.Message); } finally { client.Disconnect(); } } result = mail.CommitEdit(); return(result); }
private void Read_Emails() { Pop3Client pop3Client; pop3Client = new Pop3Client(); pop3Client.Connect("pop.asia.secureserver.net", 995, true); pop3Client.Authenticate("*****@*****.**", "Titlereport247", AuthenticationMethod.UsernameAndPassword); int count = pop3Client.GetMessageCount(); DataTable dtMessages = new DataTable(); dtMessages.Columns.Add("MessageNumber"); dtMessages.Columns.Add("TO"); dtMessages.Columns.Add("From"); dtMessages.Columns.Add("Subject"); dtMessages.Columns.Add("DateSent"); int counter = 0; for (int i = count; i >= 1; i--) { OpenPop.Mime.Header.MessageHeader msgheader = pop3Client.GetMessageHeaders(i); string From = msgheader.From.ToString(); if (From == "*****@*****.**") { string subject = msgheader.Subject.ToString(); if (From == "Mail Delivery System") { //message = pop3Client.GetMessage(i); } else { // OpenPop.Mime.Message message = pop3Client.GetMessage(i); dtMessages.Rows.Add(); dtMessages.Rows[dtMessages.Rows.Count - 1]["MessageNumber"] = i; dtMessages.Rows[dtMessages.Rows.Count - 1]["From"] = msgheader.From.DisplayName; dtMessages.Rows[dtMessages.Rows.Count - 1]["Subject"] = msgheader.Subject; dtMessages.Rows[dtMessages.Rows.Count - 1]["DateSent"] = msgheader.DateSent; counter++; if (counter > 1) { break; } } } } dataGridView1.DataSource = dtMessages; }
public void LoginForm_PasswordRestoreWithValidEmail() { using (IWebDriver driver = new FirefoxDriver()) { driver.Navigate().GoToUrl(gg); //Открытие формы IWebElement formLink = driver.FindElement(By.XPath(@"//*[@id=""top_back""]/div[3]/a[1]")); formLink.Click(); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5)); IWebElement overlay = driver.FindElement(By.Id("cboxOverlay")); IWebElement colorbox = driver.FindElement(By.Id("colorbox")); IWebElement messageBox = driver.FindElement(By.ClassName("status-error")); IWebElement emailField = wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("Email"))); IWebElement restoreLink = wait.Until(ExpectedConditions.ElementToBeClickable(By.LinkText("Я не помню пароль"))); Assert.IsTrue(colorbox.Displayed, "Форма не открылась"); emailField.SendKeys(validEmail); restoreLink.Click(); try { wait.Until(ExpectedConditions.TextToBePresentInElementLocated(By.ClassName("status-message"), "Инструкция по восстановлению отправлена")); } catch (Exception e) { Assert.Fail("Не появилось сообщение об отправке письма"); } } using (Pop3Client client = new Pop3Client()) { client.Connect(hostname, port, useSsl); client.Authenticate(validEmail, emailPass); int messageNumber = client.GetMessageCount(); int i = 0; while (messageNumber == 0 && i < 60) { client.Disconnect(); System.Threading.Thread.Sleep(5000); client.Connect(hostname, port, useSsl); client.Authenticate(validEmail, emailPass); messageNumber = client.GetMessageCount(); i = i++; } Assert.IsTrue(messageNumber > 0, "Письмо не пришло"); MessageHeader headers = client.GetMessageHeaders(messageNumber); RfcMailAddress from = headers.From; string subject = headers.Subject; client.DeleteAllMessages(); Assert.IsFalse(from.HasValidMailAddress && from.Address.Equals("*****@*****.**") && "Восстановление пароля на Gama - Gama".Equals(subject), "Письмо не пришло"); } }
/// <summary> /// Load every mail from client in MailItems /// </summary> /// <returns>A list off MailItems</returns> public string[][] Load_Mail_List() { if (IsConnected) { dispatcherTimer.Stop(); Thread.Sleep(0500); try{ int messageCount = client.GetMessageCount(); string[][] All_Mails = new string[messageCount][]; for (int i = messageCount; i > 0; i--) { MessageHeader headers = client.GetMessageHeaders(i); RfcMailAddress from = headers.From; string[] Mail = new string[4]; Mail[0] = headers.MessageId; if (!String.IsNullOrEmpty(from.DisplayName)) { Mail[1] = from.DisplayName; } else { Mail[1] = from.Address; } Mail[2] = headers.DateSent.Day.ToString("D2") + "/" + headers.DateSent.Month.ToString("D2") + " " + headers.DateSent.Year.ToString("D4") + " " + headers.DateSent.Hour.ToString("D2") + ":" + headers.DateSent.Minute.ToString("D2") + ":" + headers.DateSent.Second.ToString("D2"); Mail[3] = headers.Subject; All_Mails[messageCount - i] = Mail; } return(All_Mails); } catch { // mail receiving error MessageBox.Show("Mail receiving error.", "error"); } dispatcherTimer.Start(); } return(null); }
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; } }
public List <string> GetLastTenMessages() { var res = new List <string>(); var messageCount = _client.GetMessageCount(); var i = messageCount; while (i >= messageCount - 9 && i >= 1) { var headers = _client.GetMessageHeaders(i); var subject = headers.Subject; res.Add(subject); i--; } return(res); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_POP3(); string dstEmail = dataDir + "message.msg"; //Create an instance of the Pop3Client class Pop3Client client = new Pop3Client(); //Specify host, username and password for your client client.Host = "pop.gmail.com"; // Set username client.Username = "******"; // Set password client.Password = "******"; // Set the port to 995. This is the SSL port of POP3 server client.Port = 995; // Enable SSL client.SecurityOptions = SecurityOptions.Auto; try { HeaderCollection headers = client.GetMessageHeaders(1); for (int i = 0; i < headers.Count; i++) { // Display key and value in the header collection Console.Write(headers.Keys[i]); Console.Write(" : "); Console.WriteLine(headers.Get(i)); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { client.Disconnect(); } Console.WriteLine(Environment.NewLine + "Displayed header information from emails using POP3 "); }
public void DeleteMessagesOnServer(Message DefectEmail, string ProjectScope) { EmailSettings EmailSetting = new EmailSettings(); V1Logging Logs = new V1Logging(); V1XMLHelper V1XMLHelp = new V1XMLHelper(); string ToEmailAddress = V1XMLHelp.GetEmailAddressFromProjectScope(ProjectScope); try { EmailSetting = EmailSetting.GetEmailSettings(ToEmailAddress); // The client disconnects from the server when being disposed using (Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect(EmailSetting.Pop3Server, EmailSetting.Pop3PortNumber, EmailSetting.UseSSLPop3); // Authenticate ourselves towards the server client.Authenticate(ToEmailAddress, EmailSetting.Password); if (client.Connected == true) { // Get the number of messages on the POP3 server int messageCount = client.GetMessageCount(); // Run trough each of these messages and download the headers for (int messageItem = messageCount; messageItem > 0; messageItem--) { // If the Message ID of the current message is the same as the parameter given, delete that message if (client.GetMessageHeaders(messageItem).MessageId == DefectEmail.Headers.MessageId) { // Delete client.DeleteMessage(messageItem); } } client.Disconnect(); } else { Logs.LogEvent("ERROR - Deleting Message - Can't connect to server to delete message."); } } } catch (Exception ex) { Logs.LogEvent("ERROR - Deleting Message - " + ex.ToString()); } }
public 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(); } }
public ArrayImpl GetHeaders(StructureImpl filter) { var result = new ArrayImpl(); if (client.Count > 0) { var allHeaders = client.GetMessageHeaders(0, client.Count); foreach (var headers in allHeaders) { var mailMessage = new InternetMailMessage(headers); result.Add(mailMessage); } } return(result); }
private List <EmailInformation> GetLatestMail() { _logger.WriteLine("Getting latest mail"); using (var client = new Pop3Client()) { _logger.WriteLine($"Connecting to host:[{_config.Hostname}], port:[{_config.Port}]"); // Connect to the server client.Connect(_config.Hostname, _config.Port, _config.UseSSL); _logger.WriteLine($"Authenticating with user:[{_config.Username}]"); // Authenticate ourselves towards the server client.Authenticate(_config.Username, _config.Password); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); _logger.WriteLine($"#{messageCount} messages are pending collection"); // We want to download all messages var allMessages = new List <EmailInformation>(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--) { var headers = client.GetMessageHeaders(i); var msg = client.GetMessage(i); allMessages.Add(new EmailInformation { From = headers.From?.Address, Body = msg.FindFirstPlainTextVersion().GetBodyAsText(), TimeOfMail = headers.DateSent, DateTimeProcessed = DateTime.UtcNow, partitionKey = "newmail" }); } _logger.WriteLine($"#{messageCount} messages have been collected"); // Now do something with the messages return(allMessages); } }
public static void HeadersFromAndSubject(string hostname, int port, bool useSsl, string username, string password) { // The client disconnects from the server when being disposed using (Pop3Client client = new Pop3Client()) { log.Info("Try to connect server..."); client.Connect(hostname, port, useSsl); // Connect to the server client.Authenticate(username, password); // Authenticate ourselves towards the server log.Info("Server connected."); // We want to check the headers of the message before we download the full message int messageCount = client.GetMessageCount(); log.Info($"You have {messageCount} messages."); int messageNumber; for (messageNumber = 1; messageNumber <= messageCount; messageNumber++) { MessageHeader headers = client.GetMessageHeaders(messageNumber); RfcMailAddress from = headers.From; string subject = headers.Subject; // Only want to download message if: is from [email protected] and has subject "Some subject" if (from.HasValidMailAddress && from.Address.Equals("*****@*****.**") && ("a".Equals(subject) || "b".Equals(subject))) { log.Info($"The subject you are looking for is: {subject}"); // Download the full message Message message = client.GetMessage(messageNumber); log.Info($"The message sent date is: {message.Headers.DateSent}"); if (message.Headers.DateSent >= DateTime.Today) { log.Info("Try to get the mail..."); foreach (MessagePart attachment in message.FindAllAttachments()) { if (attachment.FileName.Equals("c.zip")) { // Save the raw bytes to a file var oldfilename = attachment.FileName; var newfilename = oldfilename.Substring(0, oldfilename.Length - 4) + "_" + DateTime.Now.ToString("yyyyMMdd") + ".zip"; File.WriteAllBytes(newfilename, attachment.Body); } } log.Info("Done."); } } } } }
public static string RetrieveVerificationLink(DateTime dateSent) { var client = new Pop3Client(); for (int j = 0; j < 10; j++) { client.Connect(Settings.MailServer, Settings.MailPort, true); client.Authenticate(Settings.MailUser, Settings.MailPwd); var count = client.GetMessageCount(); bool mailFound = false; for (int i = count; i > 0; i--) { var header = client.GetMessageHeaders(i); if (header.DateSent >= TimeZoneInfo.ConvertTimeToUtc(dateSent.AddTicks(-(dateSent.Ticks % TimeSpan.TicksPerSecond))) && // Ticks datepart is not present in the header header.Subject == "Please confirm your account") { Message message = client.GetMessage(count); MessagePart html = message.FindFirstHtmlVersion(); if (html != null) { string content = html.GetBodyAsText(); content = content.Replace("<a href='", ""); content = content.Replace("'>Please click Here to confirm your email</a>", ""); return(content); } mailFound = true; break; } } if (mailFound) { break; } client.Disconnect(); Thread.Sleep(5000); // Five seconds' wait before next attempt } return(""); }
/// <summary> /// The get msgs for sb. /// </summary> /// <param name="client"> /// The client. /// </param> /// <returns> /// The <see cref="List"/>. /// </returns> private static List <Header> GetMsgsForSB(Pop3Client client) { var headers = new List <Header>(); for (int i = 0; i < client.GetMessageCount(); i++) { MessageHeader msg = client.GetMessageHeaders(i + 1); if (msg.Subject.Contains("MESSAGE_FROM_BUS_CLIENT")) { headers.Add(new Header { msg = client.GetMessage(i + 1), num = i + 1 }); } } return(headers); }
public List <MessageHeaderViewModel> GetInbox() { var messages = new List <MessageHeaderViewModel>(); for (int i = 0; i < 15; i++) { var headers = pop3Client.GetMessageHeaders(i); var messHeader = new MessageHeaderViewModel { Date = headers[HeaderId.Date], From = headers[HeaderId.From], Title = headers[HeaderId.Subject], Id = i }; messages.Add(messHeader); } return(messages); }
public Dictionary <int, string> Pop3(int messageNr) { Dictionary <int, string> headers = new Dictionary <int, string>(); using (Pop3Client client = new Pop3Client()) { client.Connect("pop.gmail.com", 995, true); client.Authenticate(MailAddress, Password); for (int i = 1; i <= messageNr; i++) { var header = client.GetMessageHeaders(i); RfcMailAddress from = header.From; string subject = header.Subject; headers.Add(i, " Subject: " + header.Subject + "\n From: " + header.From + "\n DateSent: " + header.DateSent); } } return(headers); }
/// <summary> /// Example showing: /// - how to delete fetch an emails headers only /// - how to delete a message from the server /// </summary> /// <param name="client">A connected and authenticated Pop3Client from which to delete a message</param> /// <param name="messageId">A message ID of a message on the POP3 server. Is located in <see cref="MessageHeader.MessageId"/></param> /// <returns><see langword="true"/> if message was deleted, <see langword="false"/> otherwise</returns> public bool DeleteMessageByMessageId(Pop3Client client, string messageId) { // 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> /// Example showing: /// - how to fetch only headers from a POP3 server /// - how to examine some of the headers /// - how to fetch a full message /// - how to find a specific attachment and save it to a file /// </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 examine. /// Must be in range [1, messageCount] where messageCount is the number of messages on the server. /// </param> public static void HeadersFromAndSubject(string hostname, int port, bool useSsl, string username, string password, int messageNumber) { // 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); // We want to check the headers of the message before we download // the full message MessageHeader headers = client.GetMessageHeaders(messageNumber); RfcMailAddress from = headers.From; string subject = headers.Subject; // Only want to download message if: // - is from [email protected] // - has subject "Some subject" if (from.HasValidMailAddress && from.Address.Equals("*****@*****.**") && "Some subject".Equals(subject)) { // Download the full message Message message = client.GetMessage(messageNumber); // We know the message contains an attachment with the name "useful.pdf". // We want to save this to a file with the same name foreach (MessagePart attachment in message.FindAllAttachments()) { if (attachment.FileName.Equals("useful.pdf")) { //TODO: gelen dosyanın boyutuna göre, task oluşturduktan sonra o task'a ait tabloya güncelleme yap. //long byteSize = attachment.Body.Length; // Save the raw bytes to a file File.WriteAllBytes(attachment.FileName, attachment.Body); } } } } }
/// <summary> /// ищет письмо с нужной темой /// </summary> /// <param name="userEmail">email на который стучимся</param> /// <param name="Subject">Тема письма, которое нужно прочитать</param> /// <param name="Password">Пароль</param> /// <returns></returns> public static bool GetYandexTextTheme(string userEmail, string Subject, string Password) { Pop3Client client = new Pop3Client(); client.Connect("pop.yandex.ru", 995, true); client.Authenticate(userEmail.Substring(0, userEmail.IndexOf("@")), Password); int messageCount = client.GetMessageCount(); for (Int32 i = 1; i <= messageCount; i++) { MessageHeader headers = client.GetMessageHeaders(i); RfcMailAddress from = headers.From; string subject = headers.Subject; //проверяем тему письма, если та что нам надо, добавляем письмо в список писем if (subject == Subject) { return(true); } } return(false); }
/// <summary> /// Get the unread messages from service which from specify address. /// </summary> /// <param name="hostname"></param> /// <param name="port"></param> /// <param name="useSsl"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="address"></param> /// <param name="seenUids"></param> /// <returns></returns> public static Dictionary <string, Message> FetchUnseenMessages(string hostname, int port, bool useSsl, string username, string password, string address, List <string> seenUids) { var messages = new Dictionary <string, Message>(); try { using (var client = new Pop3Client()) { client.Connect(hostname, port, useSsl); client.Authenticate(username, password); var count = client.GetMessageCount(); for (var i = 1; i <= count; i++) { var header = client.GetMessageHeaders(i); var uid = client.GetMessageUid(i); if (seenUids.Contains(uid)) { continue; } if (header.From.Address == address) { messages.Add(uid, client.GetMessage(i)); } } } return(messages); } catch (Exception) { return(messages); } }
public void GetEvent() { List <Event> Event = new List <Event>(); int MessageCount = client.GetMessageCount(); for (int i = MessageCount; i > 0; i--) { MessageHeader Header = client.GetMessageHeaders(i); if (Header.From.Address == "*****@*****.**") { Message message = client.GetMessage(i); string Text = message.MessagePart.GetBodyAsText(); while (Text.IndexOf("<div>") != -1) { string TextEvent = Text.Substring(Text.IndexOf("<div>"), (Text.IndexOf("</div>") - Text.IndexOf("<div>"))); Text = Text.Remove(0, Text.IndexOf("</div>") + 6); if (TextEvent.IndexOf("Мероприятия изменены") != -1) { Console.WriteLine("Мероприятия изменены"); } else if (TextEvent.IndexOf("Мероприятия удалены из расписания:") != -11) { } else if (TextEvent.IndexOf("Мероприятия добавлены в расписание:") != -1) { } } } } // return (Event); }
//Used to click verification links in hotmail //Params: email - The email to search in // password - Email password // linkPattern - Regex used to find the link we need to click public string verifyHotmail(string email, string password, string linkPattern, string subject) { // The client disconnects from the server when being disposed string link = ""; using (Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect("pop3.live.com", 995, true); // Authenticate ourselves towards the server client.Authenticate(email, password); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); // We want to check the headers of the message before we download // the full message OpenPop.Mime.Message message = null; //stores the message with the link in it for (int i = 1; i <= messageCount; ++i) { MessageHeader headers = client.GetMessageHeaders(i); if (headers.Subject.ToString().Contains(subject)) { message = client.GetMessage(i); break; } } //grab the link out of the email //fiverr: @"(https?):((//)|(\\\\))+fiverr\.com/+[\w\d:#@%/;$()~_?\+-=\\\.&]*" if (System.Text.RegularExpressions.Regex.IsMatch(message.FindFirstHtmlVersion().GetBodyAsText(), linkPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase)) { System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(message.FindFirstHtmlVersion().GetBodyAsText(), linkPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase); link = match.Value.ToString(); } } return(link); }