public void Test() { const string hostName = "pop.gmail.com"; int port = 995; bool useSsl = true; string userName = "******"; string password = "******"; using(Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect(hostName, port, useSsl); // Authenticate ourselves towards the server client.Authenticate(userName, password); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); // We want to download all messages List<Message> allMessages = new List<Message>(messageCount); // Messages are numbered in the interval: [1, messageCount] // Ergo: message numbers are 1-based. // Most servers give the latest message the highest number for (int i = messageCount; i > 0; i--) { allMessages.Add(client.GetMessage(i)); } allMessages.ForEach(m=>Console.WriteLine("Display name: {0}", m.Headers.From.DisplayName)); } }
/// <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 static List<Message> 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); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); // We want to download all messages List<Message> allMessages = new List<Message>(messageCount); // Messages are numbered in the interval: [1, messageCount] // Ergo: message numbers are 1-based. // Most servers give the latest message the highest number for (int i = messageCount; i > 0; i--) { allMessages.Add(client.GetMessage(i)); } // Now return the fetched messages return allMessages; } }
private void ReadAllEmails() { // The client disconnects from the server when being disposed using (Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect(EmailConfiguration.Pop3, EmailConfiguration.PopPort, true, 1800, 1800, removeCertificateCallback); // Authenticate ourselves towards the server client.Authenticate(EmailConfiguration.Email, EmailConfiguration.EmailPwd); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); _systemLogger.Tell(string.Format("Total messages found: {0}", messageCount)); // Most servers give the latest message the highest number for (int i = messageCount; i > 0; i--) { var msg = client.GetMessage(i); // Now return the fetched messages _emailProcessorActor.Tell(new EmailMessage(){Subject = msg.Headers.Subject, Date = msg.Headers.Date}); } } }
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()); } }
private static void fetchAllMessages(object sender, DoWorkEventArgs e) { int percentComplete; // The client disconnects from the server when being disposed using (Pop3Client client = new Pop3Client()) { // Connect to the server //client.Connect("pop.gmail.com", 995, true); client.Connect("mail1.stofanet.dk", 110, false); // Authenticate ourselves towards the server client.Authenticate("2241859m002", "big1234"); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); // We want to download all messages List<OpenPop.Mime.Message> allMessages = new List<OpenPop.Mime.Message>(messageCount); // Messages are numbered in the interval: [1, messageCount] // Ergo: message numbers are 1-based. // Most servers give the latest message the highest number for (int i = messageCount; i > 0; i--) { allMessages.Add(client.GetMessage(i)); percentComplete = Convert.ToInt16((Convert.ToDouble(allMessages.Count) / Convert.ToDouble(messageCount)) * 100); (sender as BackgroundWorker).ReportProgress(percentComplete); } // Now return the fetched messages e.Result = allMessages; } }
//------------------------------------------------------------------------------------------- private void ImportEmails(Communication_EmailAccounts account) { Console.WriteLine("Importing e-mails for " + account.Id + " -- " + account.Host); using (Pop3Client client = new Pop3Client()) { // connect client.Connect(account.Host, account.Port, (account.Type == "pops")); client.Authenticate(account.Username, account.Password); // iterate over the messages int messageCount = client.GetMessageCount(); List<Message> allMessages = new List<Message>(messageCount); for (int i = 1; i <= messageCount; i++) { using (WeavverEntityContainer data = new WeavverEntityContainer()) { //data.SearchAllTables("asdf"); // save to database Message m = (Message) client.GetMessage(i); if (m.MessagePart.IsText) { Communication_Emails item = new Communication_Emails(); item.From = m.Headers.From.Raw; item.Subject = m.Headers.Subject; item.Raw = System.Text.ASCIIEncoding.ASCII.GetString(m.RawMessage); data.SaveChanges(); client.DeleteMessage(i); } } } } }
/* Function to retrive Email from the POP3 Server */ public void GetAllMails(object sender, DoWorkEventArgs e) { int percentComplete; using(Pop3Client client = new Pop3Client()) { /* Set the Server, Port, ssl and username/password */ client.Connect(Setting.Default.pop3_server, Setting.Default.pop3_port, Setting.Default.smtp_ssl); client.Authenticate(Setting.Default.username, Setting.Default.password); int messageCount = client.GetMessageCount(); Debug.WriteLine(messageCount); /* Create a list to contain the messages */ List<Message> allMessages = new List<Message>(); /* A loop to calculate the progress of retriving the Emails */ for (int i = messageCount; i > 0; i--) { allMessages.Add(client.GetMessage(i)); percentComplete = Convert.ToInt16((Convert.ToDouble(allMessages.Count) / Convert.ToDouble(messageCount)) * 100); (sender as BackgroundWorker).ReportProgress(percentComplete); } e.Result = allMessages; } }
public override bool HasMessages() { if (!pop3Client.Connected) { pop3Client.Dispose(); pop3Client = new Pop3Client(); pop3Client.Connect(HostName, Port, useSSL); pop3Client.Authenticate(Login, Password); } if (0 >= index) { index = count = pop3Client.GetMessageCount(); if (0 == index) { pop3Client.Disconnect(); pop3Client.Dispose(); pop3Client = new Pop3Client(); pop3Client.Connect(HostName, Port, useSSL); pop3Client.Authenticate(Login, Password); } //for (int i = count; i >= 1; i -= 1) } return 0 < index; }
private void ConnectToPop3() { client = new Pop3Client(); client.Connect(settings.Pop3Server, settings.Pop3Port, settings.Pop3UseSSL); client.Authenticate(settings.Pop3UserName, settings.Pop3Password); }
public void FetchAllMessages() { // The client disconnects from the server when being disposed using (Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect(_hostName, _port, true); // Authenticate ourselves towards the server client.Authenticate(_username, _password); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); // We want to download all messages List<Message> allMessages = new List<Message>(messageCount); // Messages are numbered in the interval: [1, messageCount] // Ergo: message numbers are 1-based. for (int i = 1; i <= messageCount; i++) { allMessages.Add(client.GetMessage(i)); } } }
//Connect to gmail, get emails and ad it to a MessageList public static List<OpenPop.Mime.Message> GetAllMessages(string hostname, int port, bool ssl, string username, string password) { try { Pop3Client client = new Pop3Client(); if (client.Connected) { client.Disconnect(); } client.Connect(hostname, port, ssl); client.Authenticate(username, password); int messageCount = client.GetMessageCount(); List<OpenPop.Mime.Message> allMessages = new List<OpenPop.Mime.Message>(messageCount); for (int i = messageCount; i > messageCount - 5; i--) { allMessages.Add(client.GetMessage(i)); } return allMessages; } catch(Exception ex) { MessageBox.Show("You have written username or password wrong or something else has happened! Program will not keep going, please open it again, thank you : " + ex.Message); Thread.CurrentThread.Abort(); //EmailClient. } return null; }
public void TestAutoAuthenticationUsernameAndPassword() { const string welcomeMessage = "+OK POP3 server ready"; const string okUsername = "******"; const string loginMessage = "+OK mrose's maildrop has 2 messages (320 octets)"; const string serverResponses = welcomeMessage + "\r\n" + okUsername + "\r\n" + loginMessage + "\r\n"; Stream inputStream = new MemoryStream(Encoding.ASCII.GetBytes(serverResponses)); MemoryStream outputStream = new MemoryStream(); Pop3Client client = new Pop3Client(); client.Connect(new CombinedStream(inputStream, outputStream)); // The Pop3Client should now have seen, that the server does not support APOP Assert.IsFalse(client.ApopSupported); client.Authenticate("mrose", "tanstaaf"); string[] commandsFired = GetCommands(new StreamReader(new MemoryStream(outputStream.ToArray())).ReadToEnd()); const string firstCommand = "USER mrose"; Assert.AreEqual(firstCommand, commandsFired[0]); const string secondCommand = "PASS tanstaaf"; Assert.AreEqual(secondCommand, commandsFired[1]); }
public void TestMethodInitialize() { settings = new TestSettings(); client = new Pop3Client(); client.Connect(settings.Pop3Server, settings.Pop3Port, settings.Pop3UseSSL); client.Authenticate(settings.Pop3UserName, settings.Pop3Password); }
public CallDataProviderImplPop3(ISelectorConfig config) : base(config) { this.pop3Client = new Pop3Client(); pop3Client.Connect(HostName, Port, useSSL); pop3Client.Authenticate(Login, Password); NULL_MESSAGE = new CallMessageImpl(pop3Client, 0, this); }
public IEnumerable<MessageDTO> GetMessages(string hostname, int port, bool useSsl, string username, string password, int? maxNumber = null) { var allMessages = new List<MessageDTO>(); try { // The client disconnects from the server when being disposed using (var client = new Pop3Client()) { client.Connect(hostname, port, useSsl); client.Authenticate(username, password, AuthenticationMethod.UsernameAndPassword); var maxCount = client.GetMessageCount(); //work out subset to take from messages var messageCount = (maxNumber.HasValue && maxNumber < maxCount) ? (maxCount - maxNumber.Value) : 0; //message list is 1 based //loop written backwards so messages are in correct order for (var i = maxCount; i > messageCount; i--) { var currentMessage = client.GetMessage(i); var html = currentMessage.FindFirstHtmlVersion(); allMessages.Add(new MessageDTO { Body = html != null && html.Body != null ? Encoding.UTF8.GetString(html.Body) : string.Empty, DateSent = currentMessage.Headers.DateSent, DisplayName = currentMessage.Headers.From.DisplayName, From = currentMessage.Headers.From.Address, Id = currentMessage.Headers.MessageId, Subject = currentMessage.Headers.Subject, Uid = currentMessage.Headers.MessageId }); } } } catch (Exception ex) { var path = Path.GetTempPath(); var stream = File.OpenWrite(Path.Combine(path, "mailFireErrorLog.log")); using (var fileWriter = new StreamWriter(stream)) { fileWriter.Write(string.Format("Exception occurred: {0} - at {1}", ex.Message, DateTime.Now)); } } return allMessages; }
public void ConectarPop(ServerDTO server, CuentaDTO cuenta) { cliente = new Pop3Client(); try { cliente.Connect(server.PopServer, server.PopPort, server.Ssl); cliente.Authenticate(cuenta.User, cuenta.Password); } catch (OpenPop.Pop3.Exceptions.PopClientException ex) { Console.WriteLine(ex.Message); } }
static void ETest() { var client = new OpenPop.Pop3.Pop3Client(); //new POPClient(); client.Connect("pop.gmail.com", 995, true); client.Authenticate("user", "pass"); var count = client.GetMessageCount(); OpenPop.Mime.Message message = client.GetMessage(count); Console.WriteLine(message.Headers.Subject); } //end etest
private static void DownloadMailsAndPushToIssueTracker() { var host = Settings.Get("Pop3Host", ""); var port = Settings.Get("Pop3Port", 110); var useSsl = Settings.Get("Pop3UseSsl", false); var username = Settings.Get("Pop3Username", ""); var password = Settings.Get("Pop3Password", ""); if (host.IsNoE()) { Console.WriteLine("\tNo Pop3Host specified."); LogOwnError(new ApplicationException("No Pop3Host specified.")); return; } try { Console.WriteLine("\tConnecting to POP3 server {0}:{1} ({4}) using {2} / {3} ...", host, port, username, password, useSsl ? "SSL" : "no SSL"); using (var pop3Client = new Pop3Client()) { pop3Client.Connect(host, port, useSsl); if (username.HasValue()) pop3Client.Authenticate(username, password); Console.WriteLine("\tFetching message count ..."); var messageCount = pop3Client.GetMessageCount(); for (var i = 1; i <= messageCount; i++) { try { Console.WriteLine("\tFetching message {0} / {1} ...", i, messageCount); var message = pop3Client.GetMessage(i); if (PushToIssueTracker(message)) pop3Client.DeleteMessage(i); } catch (Exception ex) { Console.WriteLine("\tUnable to fetch or push message: " + ex); LogOwnError(new ApplicationException("Unable to fetch or push message: " + ex.Message, ex)); } } pop3Client.Disconnect(); } } catch (Exception ex) { Console.WriteLine("\tUnable to download mails: " + ex); LogOwnError(new ApplicationException("Unable to download mails: " + ex.Message, ex)); } }
private static GetEmailResponse GetPopEmail() { var client = new Pop3Client(); client.Connect("pop.gmail.com", 995, true); client.Authenticate("*****@*****.**", "Woq0wy951", AuthenticationMethod.UsernameAndPassword); var count = client.GetMessageCount(); var message = client.GetMessage(count); Console.WriteLine(message.Headers.Subject); return new GetEmailResponse { }; }
//TODO: change the return type as needed public static List<SourcedAdoNetLog> PopGetLogEmails(int numEmails = 50, string email = "*****@*****.**", string pass = "******") { using (Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect("pop.gmail.com", 995, true); // Authenticate ourselves towards the server client.Authenticate(email, pass, AuthenticationMethod.UsernameAndPassword); // Get the number of messages in the inbox int messageCount = numEmails; //int messageCount = client.GetMessageCount(); // We want to download all messages List<SourcedAdoNetLog> allLogs = new List<SourcedAdoNetLog>(); // 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--) { //TODO: i > messageCount - numEmails; ** make sure that is greater than 0 though.. var message = client.GetMessage(i); if (message == null) continue; var plainText = message.FindFirstPlainTextVersion(); if (plainText == null) continue; var body = plainText.GetBodyAsText(); try { var json = body.FromJson<AdoNetLog>(); SourcedAdoNetLog srcLog = new SourcedAdoNetLog { Source = "Email:\n" + email, Date = json.Date, Level = json.Level, Logger = json.Logger, Message = json.Message, Exception = json.Exception, }; allLogs.Add(srcLog); } catch (Exception e) { Log.Error(String.Format("Failed to parse an AdoNetLog out from the following email body:\n{0}", body), e); } } return allLogs; } }
private static List<Message> GetNewMessages(Pop3Client pop3Client) { var allMessages = new List<Message>(); pop3Client.Connect(Hostname, Port, UseSsl); pop3Client.Authenticate(Username, Password); var messageCount = pop3Client.GetMessageCount(); for (var i = messageCount; i > 0; i--) { allMessages.Add(pop3Client.GetMessage(i)); } return allMessages; }
public void TestAccountLoginDelayResponseApop() { const string welcomeMessage = "+OK POP3 server ready <*****@*****.**>"; const string loginMessage = "-ERR [LOGIN-DELAY] wait some time before loggin in"; const string serverResponses = welcomeMessage + "\r\n" + loginMessage + "\r\n"; Stream inputStream = new MemoryStream(Encoding.ASCII.GetBytes(serverResponses)); MemoryStream outputStream = new MemoryStream(); Pop3Client client = new Pop3Client(); client.Connect(new CombinedStream(inputStream, outputStream)); Assert.Throws<LoginDelayException>(delegate { client.Authenticate("foo", "bar", AuthenticationMethod.Apop); }); }
/// <summary> /// Example showing: /// - how to set timeouts /// - how to override the SSL certificate checks with your own implementation /// </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="timeouts">Read and write timeouts used by the Pop3Client</param> public static void BypassSslCertificateCheck(string hostname, int port, int timeouts) { // The client disconnects from the server when being disposed using (Pop3Client client = new Pop3Client()) { // Connect to the server using SSL with specified settings // true here denotes that we connect using SSL // The certificateValidator can validate the SSL certificate of the server. // This might be needed if the server is using a custom normally untrusted certificate client.Connect(hostname, port, true, timeouts, timeouts, certificateValidator); // Do something extra now that we are connected to the server } }
public void button1_Click(object sender, EventArgs e) { Properties.Settings.Default.UserName = textBox1.Text.ToString(); Properties.Settings.Default.Password = textBox2.Text.ToString(); lbAuth.Text = ""; pbxAuthOk.Visible = false; pbxAuthFail.Visible = false; try { using (Pop3Client client = new Pop3Client()) { // Connect to the server pop.myopera.com client.Connect("pop.myopera.com", 995, true); // Authenticate ourselves towards the server /HejHej client.Authenticate(Properties.Settings.Default.UserName, Properties.Settings.Default.Password); if (client.Connected == true) { pbxAuthOk.Visible = true; lbAuth.Text = "Authentication OK!"; Properties.Settings.Default.Save(); } client.Disconnect(); } } catch (Exception) { pbxAuthFail.Visible = true; lbAuth.Text = "Something's wrong! \nMaybe bad username or password.."; Properties.Settings.Default.UserName = null; Properties.Settings.Default.Save(); if (Properties.Settings.Default.UserName != null) { lbCurrentUsr.Text = Properties.Settings.Default.UserName; } else { lbCurrentUsr.Text = "No Current user is saved."; } } }
public static List<Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password) { using (Pop3Client client = new Pop3Client()) { client.Connect(hostname, port, useSsl); client.Authenticate(username, password, AuthenticationMethod.UsernameAndPassword); //int messageCount = client.GetMessageCount(); int messageCount = 2; List<Message> allMessages = new List<Message>(messageCount); for (int i = messageCount; i > 0; i--) { allMessages.Add(client.GetMessage(i)); } return allMessages; } }
public void TestAccountLoginDelayResponseCramMd5() { const string welcomeMessage = "+OK"; const string challengeResponse = "+ PDE4OTYuNjk3MTcwOTUyQHBvc3RvZmZpY2UucmVzdG9uLm1jaS5uZXQ+"; const string loginDelay = "-ERR [LOGIN-DELAY]"; const string serverResponses = welcomeMessage + "\r\n" + challengeResponse + "\r\n" + loginDelay + "\r\n"; Stream inputStream = new MemoryStream(Encoding.ASCII.GetBytes(serverResponses)); MemoryStream outputStream = new MemoryStream(); Pop3Client client = new Pop3Client(); client.Connect(new CombinedStream(inputStream, outputStream)); Assert.Throws<LoginDelayException>(delegate { client.Authenticate("tim", "tanstaaftanstaaf", AuthenticationMethod.CramMd5); }); }
/// <summary> /// Удаляет все письма с сервера. /// </summary> /// <param name="Login">Логин</param> /// <param name="Password">Пароль</param> /// <param name="Server">POP3 сервер</param> /// <param name="Port">порт</param> /// <param name="UseSSL">использовать или нет SSL</param> public static void DeleteAllEmails(string Login, string Password, string Server, int Port, bool UseSSL) { using (Pop3Client client = new Pop3Client()) { client.Connect(Server, Port, UseSSL); client.Authenticate(Login, Password, AuthenticationMethod.UsernameAndPassword); try { client.DeleteAllMessages(); } catch (OpenPop.Pop3.Exceptions.PopServerException ex) { Log.MesQuestion("Скорее всего превышено количество запросов"); Log.MesQuestion(ex.Message); } } }
/// <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; } }
public void Retrieve() { var messages = new List<Message>(); using (var client = new Pop3Client()) { var appSettings = ConfigurationManager.AppSettings; client.Connect(appSettings["host"], 110, false); client.Authenticate(appSettings["user"], appSettings["pass"], AuthenticationMethod.UsernameAndPassword); for (var i = client.GetMessageCount(); i > 0; i--) { var message = client.GetMessage(i); messages.Add(message); #if (!DEBUG) client.DeleteMessage(i); #endif } } _parser.Parse(messages); }
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 Execute(IJobExecutionContext context) { _logger.Debug("RetrievePop3DataJob"); var settings = Properties.Settings.Default.Pop3Settings; using (var client = new Pop3Client()) { try { // Connect to the server client.Connect(settings.HostName, settings.Port, settings.UseSSL); // Authenticate ourselves towards the server client.Authenticate(settings.UserName, settings.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. // Most servers give the latest message the highest number for (int i = messageCount; i > 0; i--) { var message = client.GetMessage(i).ToMailMessage(); _logger.Debug($"Retrieve message {i}"); //client.DeleteMessage(i); //_logger.Debug($"Delete message {i}"); } } catch (Exception ex) { _logger.Error(this, ex); } } }
private void EnviarRespostaAtuomatica_Tick(object sender, ElapsedEventArgs e) { /* * LENDO OS E-MAILS QUE CHEGAM NA CAIXA DE ENTRADA */ try { using (var mail = new OpenPop.Pop3.Pop3Client()) { /* * Classe que conecta e autentica com o e-mail [email protected] */ mail.Connect(hostname, port, useTls); mail.Authenticate(username, password); int contadorMensagem = mail.GetMessageCount(); listaEmails.Clear(); for (int i = contadorMensagem; i > 0; i--) { /* * Percorre os e-mails da caixa de entrada e pega algumas informações: * - ID do e-mail * - Assunto (para verificar se deve ou não responder) * - Remetente * - Data de recebimento da mensagem * Ao final, aramzena as informações de cada mensagem numa Lista, na memória. */ var popEmail = mail.GetMessage(i); string mailText = string.Empty; var popText = popEmail.FindFirstPlainTextVersion(); if (popText != null) { mailText = popText.GetBodyAsText(); } listaEmails.Add(new Email() { Id = popEmail.Headers.MessageId, Assunto = popEmail.Headers.Subject, De = popEmail.Headers.From.Address, Para = string.Join("; ", popEmail.Headers.To.Select(to => to.Address)), Data = popEmail.Headers.Date, ConteudoTexto = mailText } ); } if (mail.GetMessageCount() > 0) { /* * Enquanto tiver e-mails na caixa de entrada, o programa faz o seguinte: * - Pega o ID de cada mensagem e faz uma varredura no arquivo "emails_respondidos.txt", localizado no servidor * - Se o ID NÃO CONSTAR no arquivo, o programa ENVIA uma resposta automática, de acordo com o assunto recebido. * - Adiciona o e-mail enviado à lista de e-mails respondidos. * - Se o ID CONSTAR, ignora a mensagem e NÃO ENVIA a resposta. */ using (SmtpClient objSmtp = new SmtpClient(hostname, 587)) { objSmtp.EnableSsl = true; objSmtp.Credentials = new NetworkCredential(username, password); idsLidos = File.ReadLines(caminhoArquivo).ToList(); foreach (Email item in listaEmails) { if (!idsLidos.Contains(item.Id)) { if (item.Assunto == "Contato do Site - \"Matrícula mais de um segmento\"") { Escrever(item.Id, item.Data); objSmtp.Send(Mensagens.GerarMensagemDefault(username, ObterRemetente(item.ConteudoTexto), ObterResposta(item.Assunto))); Console.WriteLine("Respostas enviadas..."); } else if (item.Assunto == "Contato do Site - \"Matrícula Berçário\"") { Escrever(item.Id, item.Data); objSmtp.Send(Mensagens.GerarMensagemBercario(username, ObterRemetente(item.ConteudoTexto), ObterResposta(item.Assunto))); Console.WriteLine("Respostas enviadas..."); } else if (item.Assunto == "Contato do Site - \"Matrícula Infantil\"") { Escrever(item.Id, item.Data); objSmtp.Send(Mensagens.GerarMensagemInfantil(username, ObterRemetente(item.ConteudoTexto), ObterResposta(item.Assunto))); Console.WriteLine("Respostas enviadas..."); } else if (item.Assunto == "Contato do Site - \"Matrícula Fundamental 1\"") { Escrever(item.Id, item.Data); objSmtp.Send(Mensagens.GerarMensagemFundamental_1(username, ObterRemetente(item.ConteudoTexto), ObterResposta(item.Assunto))); Console.WriteLine("Respostas enviadas..."); } else if (item.Assunto == "Contato do Site - \"Matrícula Fundamental 2\"") { Escrever(item.Id, item.Data); objSmtp.Send(Mensagens.GerarMensagemFundamental_2(username, ObterRemetente(item.ConteudoTexto), ObterResposta(item.Assunto))); Console.WriteLine("Respostas enviadas..."); } } } } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } }