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; } }
protected void Page_Load(object sender, EventArgs e) { try { using (Pop3Client client = new Pop3Client()) { //Para conectar no servidor do gmail use a porta 995 e SSL client.Connect("pop.gmail.com", 995, true); //Para conectar no servidor do hotmail use a porta 995 e SSL //client.Connect("pop3.live.com", 995, true); //usuário e senha para autenticar client.Authenticate("luisfelipe.lambert", "sakuda5G"); //Pega o número de mensagens int messageCount = client.GetMessageCount(); //Instanciar a lista List<Message> mensagens = new List<Message>(); //Pegar as mensagens for (int i = messageCount; i > 0; i--) { //Adicionar a mensagem a lista mensagens.Add(client.GetMessage(i)); } //Popular o repeater com as mensagens repMensagens.DataSource = mensagens; repMensagens.DataBind(); } } catch (Exception ex) { //Caso ocorra algum erro, uma mensagem será exibida na página litMensagemErro.Text = ex.ToString(); } }
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 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)); } } }
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); } } } } }
//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 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 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}); } } }
/* 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 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; }
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)); } }
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 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 { }; }
public static List<Message> GetAllMails(string hostname, int port, bool useSsl, string username, string password) { using(Pop3Client client = new Pop3Client()) { client.Connect(hostname, port, useSsl); client.Authenticate(username, password); int messageCount = client.GetMessageCount(); Debug.WriteLine(messageCount); List<Message> allMessages = new List<Message>(messageCount); for (int i = messageCount; i > 0; i--) { allMessages.Add(client.GetMessage(i)); Debug.WriteLine(client.GetMessage(i).MessagePart); } return allMessages; } }
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 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; } }
/// <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); } } }
protected void Page_Load(object sender, EventArgs e) { Pop3Client pop = new Pop3Client(); pop.Connect("email-ssl.com.br", 995,true); pop.Authenticate("*****@*****.**", "yourpassword"); if (pop.Connected) { Int32 tot = pop.GetMessageCount(); lblTotMessage.Text = "Conexão feito. Total Mensagem: " + tot.ToString(); DataTable datatb = new DataTable(); datatb.Columns.Add("MessageNumber"); datatb.Columns.Add("From"); datatb.Columns.Add("Subject"); datatb.Columns.Add("DateSent"); int counter = 0; for (int i = 1; i < tot; i++) { Message message = pop.GetMessage(i); datatb.Rows.Add(); datatb.Rows[datatb.Rows.Count - 1]["MessageNumber"] = i; datatb.Rows[datatb.Rows.Count - 1]["Subject"] = message.Headers.Subject; datatb.Rows[datatb.Rows.Count - 1]["DateSent"] = message.Headers.DateSent; counter++; if (counter > 20) { break; } } gvTicket.DataSource = datatb; gvTicket.DataBind(); } }
public override void onPageLoad() { Pop3Client client = new Pop3Client(); client.Connect("pop3.live.com", 995, true); client.Authenticate("*****@*****.**", "sedona72894"); // 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--) { if(i == messageCount - 10) break; echo(client.GetMessage(i).ToMailMessage().Subject + "<br />"); } }
//------------------------------------------------------------------------------------------- private string GetActivationCode() { using (Pop3Client client = new Pop3Client()) { client.Connect(Helper.GetAppSetting("pop3_server"), 110, false); client.Authenticate(Helper.GetAppSetting("pop3_username"), Helper.GetAppSetting("pop3_password")); int x = client.GetMessageCount(); for (int i = 1; i < x + 1; i++) { Message msg = client.GetMessage(i); string subj = msg.Headers.Subject; if (subj == "Please activate your Weavver ID") { string activationCode = System.Text.Encoding.GetEncoding("utf-8").GetString(msg.FindFirstHtmlVersion().Body); activationCode = activationCode.Substring(activationCode.IndexOf("Or use the following code:") + 30); activationCode = activationCode.Substring(0, activationCode.IndexOf("<br>")); client.DeleteMessage(i); return activationCode; } } } return null; }
/// <summary> /// получаем список сообщений из ящика /// </summary> /// <param name="hostname">хост. Например, pop.yandex.ru</param> /// <param name="port">порт. Например, 110</param> /// <param name="useSsl">использовать ssl</param> /// <param name="username">логин</param> /// <param name="password">пароль</param> /// <returns>список емейлов</returns> public static List<OpenPop.Mime.Message> FetchAllEmailMessages(string hostname, int port, bool useSsl, string username, string password) { // The client disconnects from the server when being disposed using(Pop3Client client = new Pop3Client()) { client.Connect(hostname, port, useSsl); client.Authenticate(username, password); // 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. for(int i = 1; i <= messageCount; i++) allMessages.Add(client.GetMessage(i)); // Now return the fetched messages return allMessages; } }
/// <summary> /// 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> /// <param name="deleteImagAfterFetch">If true images on Pop3 will be deleted after beeing fetched</param> /// <returns>All Messages on the POP3 server</returns> public static List<OpenPop.Mime.Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password, bool deleteImagAfterFetch) { // The client disconnects from the server when being disposed using (Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect(hostname, port, useSsl); client.Authenticate(username, password); int messageCount = client.GetMessageCount(); // We want to download all messages List<OpenPop.Mime.Message> allMessages = new List<OpenPop.Mime.Message>(messageCount); for (int i = messageCount; i > 0; i--) { allMessages.Add(client.GetMessage(i)); if (deleteImagAfterFetch) { client.DeleteMessage(i); } } return allMessages; } }
/// <summary> /// Método DescargarCorreos. /// Permite descargar los correos de una casilla de correo del tipo Gmail. /// </summary> /// <param name="pCuenta">Cuenta para descargar correos</param> /// <returns>Lista de emails descargados</returns> public override List<EmailDTO> DescargarCorreos(CuentaDTO pCuenta) { List<EmailDTO> iListaCorreosDescargados = new List<EmailDTO>(); Pop3Client iPop = new Pop3Client(); int iCantidadMensajes; string iIDMensaje; try { iPop.Connect("pop.gmail.com", 995, true); iPop.Authenticate(pCuenta.Direccion, pCuenta.Contraseña); iCantidadMensajes = iPop.GetMessageCount(); string iCuerpo = ""; string iTipoCorreo = ""; List<String> iDestino = new List<String>(); List<String> iCC = new List<String>(); List<String> iCCO = new List<String>(); List<MessagePart> iListaAdjuntos = new List<MessagePart>(); for (int i = iCantidadMensajes; i > 0; i--) { iDestino.Clear(); iCC.Clear(); iCCO.Clear(); Message iMensaje = iPop.GetMessage(i); iIDMensaje = iPop.GetMessageHeaders(i).MessageId; if (iIDMensaje == null) { iIDMensaje = ""; } MessagePart iTexto = iMensaje.FindFirstPlainTextVersion(); if (iTexto != null) { iCuerpo = iTexto.GetBodyAsText(); } else { MessagePart iHTML = iMensaje.FindFirstHtmlVersion(); if (iHTML != null) { iCuerpo = iHTML.GetBodyAsText(); } } if (iMensaje.Headers.From.Address == pCuenta.Direccion) { iTipoCorreo = "Enviado"; } else { iTipoCorreo = "Recibido"; } foreach (RfcMailAddress direccionCorreo in iMensaje.Headers.To) { iDestino.Add(direccionCorreo.Address); } foreach (RfcMailAddress direccionCC in iMensaje.Headers.Cc) { iCC.Add(direccionCC.Address); } foreach (RfcMailAddress direccionCCO in iMensaje.Headers.Bcc) { iCCO.Add(direccionCCO.Address); } EmailDTO iNuevoMail = new EmailDTO( pCuenta.ID, iTipoCorreo, iMensaje.Headers.From.Address, iDestino, iMensaje.Headers.Subject, iCuerpo, iMensaje.Headers.DateSent.ToString(), true, iCC, iCCO, iIDMensaje, "No leído" ); iListaCorreosDescargados.Add(iNuevoMail); } } catch (InvalidLoginException) { throw new ServiciosCorreoException("No se puede actualizar la bandeja de la cuenta " + pCuenta.Direccion + ". Hubo un problema en el acceso"); } catch (PopServerNotFoundException) { throw new ServiciosCorreoException("No se puede actualizar la bandeja de la cuenta " + pCuenta.Direccion + ". Hubo un error en el acceso al servidor POP3 de Gmail"); } catch (Exception) { throw new ServiciosCorreoException("No se puede actualizar la bandeja de la cuenta " + pCuenta.Direccion + "."); } return iListaCorreosDescargados; }
/// <summary> /// gets all unread email from Gmail and returns a List of System.Net.Email.MailMessage Objects /// </summary> /// <param name="username">Gmail Login</param> /// <param name="password">mail Password</param> public static List<MailMessage> FetchAllUnreadMessages(string username, string password) { List<MailMessage> mlist = new List<MailMessage>(); // The client disconnects from the server when being disposed try { using (Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect("pop.gmail.com", 995, true); // Authenticate ourselves towards the server client.Authenticate(username, password); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); for (int x = messageCount; x > 0; x--) { Message m = new Message(client.GetMessage(x).RawMessage); System.Net.Mail.MailMessage mm = m.ToMailMessage(); mlist.Add(mm); } return mlist; } } catch { return mlist; } }
public void RetrieveEmails(string EmailAddress, string Password, string ConnString, string DeleteMessage, string HostName, int Port, bool UseSsl, bool sendreceivedemail, bool SendOverDueReceivedEmail) { Pop3Client client = new Pop3Client(); client.Connect(HostName, Port, UseSsl);//the type of server client.Authenticate(EmailAddress, Password);//connects to the inbox we want to get the emails from int Count = client.GetMessageCount();//gets the message count for the inbox of the above email for (int i = 1; i <= Count; i++)//loops through the messages in the inbox { OpenPop.Mime.Message message = client.GetMessage(i);//gets the message string email = message.Headers.From.Address.ToString();//this gets the email address string subject = message.Headers.Subject.ToString();//this gets the subject string Parent = getBetween(subject, "(", ")"); int parent; try { parent = Convert.ToInt32(Parent); } catch { parent = 0; } string body = message.FindFirstPlainTextVersion().GetBodyAsText();//this gets the body int ticketid = AddEmailToDatabase(ConnString, email, subject, body, parent);//this add the email message to the database and returns its ticketid if (parent == 0) { if (sendreceivedemail == true) { SendReceivedEmail(ConnString, email, EmailAddress, Password, ticketid);//sends an email back saying we received there email } } foreach (OpenPop.Mime.MessagePart emailattachment in message.FindAllAttachments())//this loops through all the attachments for a message { string OriginalFileName = emailattachment.FileName;//gets the original file name of the attachment string ContentID = emailattachment.ContentId;//if this is set then the attachment is inline. string ContentType = emailattachment.ContentType.MediaType;//type of attachment pdf, jpg, png, etc. byte[] Content = emailattachment.Body;//gets the body of the attachment as a byte[] using (MemoryStream MS = new MemoryStream(Content))//puts the Content[] into a memory stream { Image im = Image.FromStream(MS, true, true);//Image from the memorystream int sourceWidth = im.Width;//the original width of the image int sourceHeight = im.Height;//the original height of the image float nPercent = 0; float nPercentW = 0; float nPercentH = 0; //the following code checks which is larger the height or width and then resizes the image accordingly nPercentW = ((float)900 / (float)sourceWidth); nPercentH = ((float)900 / (float)sourceHeight); if (nPercentH < nPercentW) nPercent = nPercentH; else nPercent = nPercentW; int destWidth = (int)(sourceWidth * nPercent); int destHeight = (int)(sourceHeight * nPercent); Bitmap b = new Bitmap(destWidth, destHeight); Graphics g = Graphics.FromImage((Image)b); g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(im, 0, 0, destWidth, destHeight); g.Dispose(); MemoryStream m = new MemoryStream(); b.Save(m, ImageFormat.Jpeg); Content = m.ToArray(); } AddAttachmentToDatabase(ConnString, ticketid, OriginalFileName, Content);//adds the attachment to the database //write the attachment to the disk //System.IO.File.WriteAllBytes("C:/Users/David/Documents/Visual Studio 2012/Projects/GetEmails/GetEmails/Attachments/" +ticketid+ OriginalFileName, emailattachment.Body);//overwrites MessagePart.Body with attachment //string attachment = "~/Attachments/" + ticketid + OriginalFileName; //AddAttachmentToDatabase(ticketid,attachment); } } if (DeleteMessage == "Yes")//checks whether to delete the message from the inbox { for (int i = Count; i > 0; i--) { client.DeleteMessage(i);//deletes the messages from the inbox } client.Dispose(); } if (SendOverDueReceivedEmail == true) { SendOverDueEmail(ConnString, EmailAddress, Password); //This will send a message to the user notifying them of a ticket that has not been opened after 3 hours } }
public static List<MailParts> CheckInbox(ref string resultTopic, ref string resultMsg) { if (resultMsg == null) throw new ArgumentNullException("resultMsg"); //Dictionary<int, Message> messages = new Dictionary<int, Message>(); Pop3Client pop3Client = new Pop3Client(); List<MailParts> querys = new List<MailParts>(); try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(Settings.POPserver, Settings.POPport, true); pop3Client.Authenticate(Settings.EmailUser, Settings.EmailPass); int count = pop3Client.GetMessageCount(); for (int i = count; i >= 1; i -= 1) { try { Message message = pop3Client.GetMessage(i); //messages.Add(i, message); if (message.Headers.Subject.Equals("Aramis-IT: Sending query")) { if (message.MessagePart != null && message.MessagePart.IsText) { string[] parts = message.MessagePart.GetBodyAsText().Split( new[] { ParameterTag }, StringSplitOptions.RemoveEmptyEntries); MailParts mail = new MailParts { Parameter = new List<SQLiteParameter>() }; bool isFirst = true; foreach (string part in parts) { if (!isFirst) { string[] p = part.Split('='); mail.Parameter.Add(new SQLiteParameter(p[0], p[1].Replace("\r\n", ""))); } else { isFirst = false; mail.Command = part; } } querys.Add(mail); } } } catch (Exception e) { MessageBox.Show( "TestForm: Message fetching failed: " + e.Message + "\r\n" + "Stack trace:\r\n" + e.StackTrace); } } } catch (InvalidLoginException) { resultTopic = "POP3 Server Authentication"; resultMsg = "The server did not accept the user credentials!"; return null; } catch (PopServerNotFoundException) { resultTopic = "POP3 Retrieval"; resultMsg = "The server could not be found"; return null; } catch (PopServerLockedException) { resultTopic = "POP3 Account Locked"; resultMsg = "The mailbox is locked. It might be in use or under maintenance."; return null; } catch (LoginDelayException) { resultTopic = "POP3 Account Login Delay"; resultMsg = "Login not allowed. Server enforces delay between logins."; return null; } catch (Exception e) { resultTopic = "POP3 Retrieval"; resultMsg = "Error occurred retrieving mail. " + e.Message; return null; } finally { if(pop3Client.Connected) { pop3Client.Disconnect(); } } //foreach (Message msg in messages.Values) //{ // if (msg.MessagePart != null && // msg.MessagePart.MessageParts != null && // msg.MessagePart.MessageParts.Count >= 1 && // msg.MessagePart.MessageParts[0].IsText) // { // string body = msg.MessagePart.MessageParts[0].GetBodyAsText(); // //querys.Add(body); // } //} return querys; }
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); } }