/// <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> /// 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; }
public void TestGetMessageHeaders() { const string welcomeMessage = "+OK"; const string okUsername = "******"; const string okPassword = "******"; const string messageTopAccepted = "+OK"; const string messageHeaders = "Subject: [Blinded by the lights] New Comment On: Comparison of .Net libraries for fetching emails via POP3"; const string messageHeaderToBodyDelimiter = ""; // Blank line ends message const string messageListingEnd = "."; const string serverResponses = welcomeMessage + "\r\n" + okUsername + "\r\n" + okPassword + "\r\n" + messageTopAccepted + "\r\n" + messageHeaders + "\r\n" + messageHeaderToBodyDelimiter + "\r\n" + messageListingEnd + "\r\n"; Stream inputStream = new MemoryStream(Encoding.ASCII.GetBytes(serverResponses)); Stream outputStream = new MemoryStream(); Pop3Client client = new Pop3Client(); client.Connect(new CombinedStream(inputStream, outputStream)); client.Authenticate("test", "test"); // Fetch the header of message 7 MessageHeader header = client.GetMessageHeaders(7); const string expectedSubject = "[Blinded by the lights] New Comment On: Comparison of .Net libraries for fetching emails via POP3"; string subject = header.Subject; Assert.AreEqual(expectedSubject, subject); }
/// <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")) { // Save the raw bytes to a file File.WriteAllBytes(attachment.FileName, attachment.Body); } } } } }
public bool FindAndDownloadBudget(BackgroundWorker bw) { bool attachmentFound = false; try { Log.n("Kobler til e-post server \"" + main.appConfig.epostPOP3server + "\".."); using (Pop3Client client = new Pop3Client()) { client.Connect(main.appConfig.epostPOP3server, main.appConfig.epostPOP3port, main.appConfig.epostPOP3ssl); if (bw != null) { if (bw.CancellationPending) { if (client.Connected) client.Disconnect(); return false; } } Log.d("Logger inn med brukernavn \"" + main.appConfig.epostBrukernavn + "\".."); SimpleAES aes = new SimpleAES(); client.Authenticate(main.appConfig.epostPOP3username, aes.DecryptString(main.appConfig.epostPOP3password)); int count = client.GetMessageCount(); Log.d("Innlogging fullført. Antall meldinger i innboks: " + count); if (count == 0) { Log.n("Innboks for \"" + main.appConfig.epostPOP3username + "\" er tom. " + "Endre innstillinger i ditt e-post program til å la e-post ligge igjen på server", Color.Red); client.Disconnect(); return false; } main.processing.SetText = "Søker i innboks.. (totalt " + count + " meldinger)"; Log.n("Søker i innboks.. (totalt " + count + " meldinger)"); for (int i = count + 1; i-- > 1;) { if (attachmentFound || maxEmailAttemptsReached) break; if (bw != null) if (bw.CancellationPending) break; Log.d("Sjekker meldingshode " + (count - i + 1) + ".."); MessageHeader header = client.GetMessageHeaders(i); if (HeaderMatch(header)) { if (header.DateSent.Date != selectedDate.Date) { Log.d("Fant C810 e-post med annen dato: " + header.DateSent.ToShortDateString() + " ser etter: " + selectedDate.ToShortDateString() + " Emne: \"" + header.Subject + "\" Fra: \"" + header.From.MailAddress + "\""); continue; } Log.d("--------- Fant C810 e-post kandidat: Fra: \"" + header.From.MailAddress.Address + "\" Emne: \"" + header.Subject + "\" Sendt: " + header.DateSent.ToShortDateString() + " (" + header.DateSent.ToShortTimeString() + ")"); Log.d("Laster ned e-post # " + i + ".."); Message message = client.GetMessage(i); foreach (MessagePart attachment in message.FindAllAttachments()) { if (attachmentFound) break; Log.d("Vedlegg: " + attachment.FileName); if (AttachmentMatch(attachment)) attachmentFound = ParseAndSaveDailyBudget(attachment, message.Headers.DateSent, message.Headers.Subject, message.Headers.From.MailAddress.Address); } } if (!attachmentFound) Log.d("Fant ingen C810 vedlegg i e-post # " + i); } client.Disconnect(); } if (attachmentFound) return true; else if (!attachmentFound && maxEmailAttemptsReached) Log.n("Maksimum antall e-post nedlastninger er overgått. Innboks søk er avsluttet", Color.Red); else Log.n("Fant ingen C810 e-post med budsjett for dato " + selectedDate.ToShortDateString() + ". Innboks søk er avsluttet", Color.Red); } catch (PopServerNotFoundException) { Log.n("E-post server finnes ikke eller DNS problem ved tilkobling til " + main.appConfig.epostPOP3server, Color.Red); } catch (PopServerNotAvailableException ex) { Log.n("E-post server \"" + main.appConfig.epostPOP3server + "\" svarer ikke. Feilmelding: " + ex.Message, Color.Red); } catch (Exception ex) { if (ex.Message.Contains("Authentication failed") || ex.Message.Contains("credentials")) Log.n("Feil brukernavn eller passord angitt for " + main.appConfig.epostPOP3username + ". Sjekk e-post innstillinger!", Color.Red); else { Log.Unhandled(ex); Log.n("Feil ved henting av epost. Beskjed: " + ex.Message); } } return false; }
public static void CollectHomework(string email, string password, string pattern) { // The client disconnects from the server when being disposed using (Pop3Client client = new Pop3Client()) { // Connect to the server var t = email.Split(new[] { '@' }); t[0] = "pop"; string server = string.Join(".", t); client.Connect(server, 110, false); // Authenticate ourselves towards the server client.Authenticate(email, 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); Console.WriteLine("Number of email : " + 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; i++) { Console.WriteLine("Scanning the " + i + "th email."); if (client.GetMessageHeaders(i).Subject.ToLower().StartsWith(pattern.ToLower())) { allMessages.Add(client.GetMessage(i)); } } allMessages = allMessages.OrderBy(x => x.Headers.DateSent).ToList(); var homeworkDic = new Dictionary<string, List<Message>>(); foreach (var item in allMessages) { var k = item.Headers.Subject.Substring(pattern.Length).Trim(); if (!homeworkDic.ContainsKey(k)) { homeworkDic[k] = new List<Message>(); } homeworkDic[k].Add(item); } string root = Directory.GetCurrentDirectory(); var gradeDir = new DirectoryInfo(root + "\\for grade"); var receivedSet = new HashSet<string>(); foreach (var st in gradeDir.GetDirectories()) { var number = new string(st.Name.Where(char.IsDigit).ToArray()); if (homeworkDic.ContainsKey(number)) { receivedSet.Add(number); var mails = homeworkDic[number]; Dictionary<string, MessagePart> dic = new Dictionary<string, MessagePart>(); foreach (var p in mails.SelectMany(x => x.FindAllAttachments())) { dic[p.FileName] = p; } foreach (var item in dic.Values) { var file = new FileInfo(st.FullName + "\\" + item.FileName); //if (file.Exists) continue; item.Save(file.Create()); } } } app = new Microsoft.Office.Interop.Excel.Application(); app.Visible = true; app.DisplayAlerts = false; app.Workbooks.Add(root + "\\feedback.xlsx"); int pos = 0; for (int i = 1; i <= app.Workbooks[1].Worksheets.Count; ++i) { if (app.Workbooks[1].Worksheets[i].Name == "number") { pos = i; } } var Numbers = new Dictionary<string, List<FileInfo>>(); for (int i = 7; ; ++i) { var val = app.Workbooks[1].Worksheets[pos].Cells[i, 4].Value; if (val == null) break; var num = val.ToString(); if (receivedSet.Contains(num)) app.Workbooks[1].Worksheets[pos].Cells[i, 11].Value = "收到邮件"; } app.Workbooks[1].SaveAs(root + "\\feedback.xlsx"); app.Workbooks[1].Close(); Helper.CloseWordExcel(); } }
private void test(MailPwd mp) { Pop3Client pop3Client = new Pop3Client(); data sev = m_dicPopServers[emailToDomain(mp.email)]; pop3Client.Connect(sev.pop3,sev.port , sev.isSSL); pop3Client.Authenticate(mp.email, mp.pwd); // int count = pop3Client.GetMessageCount(); int messageCount = pop3Client.GetMessageCount(); // init index list List<EmailMap> em = new List<EmailMap>(); try { string dirPath = @"data\inbox\" + mp.email; //serilize index.xml /* if (File.Exists(dirPath+"\\index.xml")) { string confPath = dirPath + "\\index.xml"; var serializer = new XmlSerializer(typeof(List<EmailMap>)); using (var stream = File.OpenRead(confPath)) { var other = (List<EmailMap>)(serializer.Deserialize(stream)); em.AddRange(other); stream.Close(); } }*/ List<EmailMap> emTmp = new List<EmailMap>(); // string[] paths= Directory.GetFiles(dirPath, "*", SearchOption.AllDirectories); List<Message> allMessages = new List<Message>(messageCount); int nCurCount = m_dicEmails[mp.email].Count; // 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 = nCurCount + 1; i <= messageCount; i++) { // allMessages.Add(pop3Client.GetMessage(i)); Message msg=pop3Client.GetMessage(i); string strSubject=msg.Headers.Subject; string filename=pop3Client.GetMessageHeaders(i).MessageId; emTmp.Add(new EmailMap { title = strSubject,file=filename }); //write to htm file // If the selected node is not a subnode and therefore does not // have a MessagePart in it's Tag property, we genericly find some content to show // Find the first text/plain version MessagePart plainTextPart = msg.FindFirstPlainTextVersion(); string strContent; if (plainTextPart != null) { // The message had a text/plain version - show that one strContent = plainTextPart.GetBodyAsText(); } else { // Try to find a body to show in some of the other text versions List<MessagePart> textVersions = msg.FindAllTextVersions(); if (textVersions.Count >= 1) strContent = textVersions[0].GetBodyAsText(); else strContent = "<<KibodWapon>> Cannot find a text version body in this message to show <<contact me qq408079058>>"; } string strMailPath = dirPath + "\\" + filename + ".htm"; using (System.IO.StreamWriter file = new System.IO.StreamWriter(strMailPath)) { file.WriteLine("<head><meta charset=\"UTF-8\"></head>"); file.WriteLine(strContent); file.Close(); } File.WriteAllText(dirPath + "\\" + filename + ".eml", Encoding.ASCII.GetString(msg.RawMessage)); } //serilize index.xml m_dicEmails[mp.email].AddRange(emTmp); try { string confPath =@"data\inbox\" + mp.email+"\\index.xml"; File.Delete(confPath); var serializer = new XmlSerializer(typeof(List<EmailMap>)); using (var stream = File.OpenWrite(confPath)) { serializer.Serialize(stream, em); stream.Close(); } } catch (Exception ee) { Console.WriteLine(ee.Message); } } catch (Exception UAEx) { Console.WriteLine(UAEx.Message); } pop3Client.Disconnect(); }
private static bool DeleteMessageByMessageId(Pop3Client client, string messageId) { var messageCount = client.GetMessageCount(); for (var messageItem = messageCount; messageItem > 0; messageItem--) { if (client.GetMessageHeaders(messageItem).MessageId != messageId) continue; client.DeleteMessage(messageItem); return true; } return false; }
private static IDictionary<string, Message> GetNewMessages(Pop3Client pop3Client) { var allMessages = new Dictionary<string, Message>(); pop3Client.Connect(Hostname, Port, UseSsl); pop3Client.Authenticate(Username, Password); var messageCount = pop3Client.GetMessageCount(); for (var i = messageCount; i > 0; i--) { allMessages.Add(pop3Client.GetMessageHeaders(i).MessageId, pop3Client.GetMessage(i)); } return allMessages; }
/// <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; }
private static bool DeleteMessageByMessageId(string hostname, int port, bool useSsl, string username, string password, 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; } }