public static void ReadEmail() { using (OpenPop.Pop3.Pop3Client client = new OpenPop.Pop3.Pop3Client()) { client.Connect("pop.gmail.com", 995, true); client.Authenticate("recent:[email protected]", "pass"); if (client.Connected) { Console.WriteLine("Checking inbox"); var count = client.GetMessageCount(); OpenPop.Mime.Message message = client.GetMessage(count); OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion(); builder.Append("Subject: " + message.Headers.Subject + "\n"); builder.Append("Date: " + message.Headers.Date + "\n"); builder.Append("Body: " + plainText.GetBodyAsText()); Console.WriteLine(builder.ToString()); //verifica se existem anexos e caso sim salva-os na pasta var att = message.FindAllAttachments(); foreach (var ado in att) { ado.Save(new System.IO.FileInfo(System.IO.Path.Combine(@"C:\Users\wviegas\Documents\will", ado.FileName))); } } } }
private void ReceiveMails() { try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect("pop.gmail.com", 995, true); pop3Client.Authenticate(textBox_email.Text, textBox_passwd.Text); int count = pop3Client.GetMessageCount(); for (int i = count; i >= 1; i -= 1) { try { Application.DoEvents(); Message message = pop3Client.GetMessage(i); MessagePart plainTextPart = message.FindFirstPlainTextVersion(); ListViewItem lvi = new ListViewItem(message.Headers.From.Address.ToString()); lvi.SubItems.Add(message.Headers.Date.ToString()); lvi.SubItems.Add(message.Headers.Subject.ToString()); lvi.SubItems.Add(plainTextPart.GetBodyAsText()); listViewMails.Items.Add(lvi); } catch (Exception e) { MessageBox.Show(e.Message); } } } catch (InvalidLoginException) { MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication"); } catch (PopServerNotFoundException) { MessageBox.Show(this, "The server could not be found", "POP3 Retrieval"); } catch (PopServerLockedException) { MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked"); } catch (LoginDelayException) { MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay"); } catch (Exception e) { MessageBox.Show(this, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval"); } finally { } }
/// <summary> /// 获取某个编号的那封邮件,返回EmailInfo对象 /// </summary> /// <param name="no"></param> /// <returns></returns> private EmailInfo getEmailInfo(int no) { OpenPop.Mime.Header.MessageHeader head = emailClient.GetMessageHeaders(no); //OpenPop.Mime.Message message = emailClient.GetMessage(no); EmailInfo emailinfo = new EmailInfo(); emailinfo.From = head.From.Raw; foreach (var toAdd in head.To) { emailinfo.To += toAdd.Raw + ","; } foreach (var ccAdd in head.Cc) { emailinfo.Cc += ccAdd.Raw + ","; } emailinfo.Subject = head.Subject; emailinfo.Date = head.DateSent.ToString(); emailinfo.no = no; string content = ""; int size = emailClient.GetMessageSize(no); if (size > 10 * 1024 * 1024) { emailinfo.Content = "****邮件过大,无法获取。请到邮箱中查看此邮件!****"; } else { OpenPop.Mime.Message message = emailClient.GetMessage(no); if (message.MessagePart.IsText) { content = message.MessagePart.GetBodyAsText(); } else if (message.MessagePart.IsMultiPart) { MessagePart plainTextPart = message.FindFirstPlainTextVersion(); if (plainTextPart != null) { // The message had a text/plain version - show that one content = plainTextPart.GetBodyAsText(); } else { // Try to find a body to show in some of the other text versions //List<MessagePart> textVersions = message.FindAllTextVersions(); //if (textVersions.Count >= 1) // content = textVersions[0].GetBodyAsText(); //else // content = ""; } } emailinfo.Content = content; } return(emailinfo); }
public void Get_Decoding() { Ping p = new Ping(); PingReply pr = p.Send("mail.ru"); status = pr.Status; if (status == IPStatus.Success)//Проверка интернет соединения { // using чтобы соединение автоматически закрывалось using (Pop3Client client = new Pop3Client()) { client.Connect("pop.mail.ru", 995, true); // Подключение к серверу client.Authenticate("*****@*****.**", "Vadim762905", AuthenticationMethod.UsernameAndPassword); // Аутентификация (проверка логина и пароля) if (client.Connected) { // Перебор всех сообщений for (int i = client.GetMessageCount(); i > 0; i--) { Message message = client.GetMessage(i); string subject = message.Headers.Subject; string from = message.Headers.From.Address.ToString(); string body = ""; if (from == "*****@*****.**" && subject == "RSA") { MessagePart mpPlain = message.FindFirstPlainTextVersion(); // ищем сообщениие if (mpPlain != null) //проветка сообщения на пустоту { Encoding enc = mpPlain.BodyEncoding; body = enc.GetString(mpPlain.Body); //получаем текст сообщения texts_codings.Text = body; texts_decoding.Text = criptograph.Decryption(body); email.Text = from; maila.Content = "Сообщение найдено и декодировано"; break; } maila.Content = "К сожалению сообщение не найдено"; } } } } } else { maila.Content = "Интернет соединение отсутствует !!!"; } }
internal void get() { client.Connect("pop.gmail.com", 995, true); // Connects to the pop3 server for gmail client.Authenticate("*****@*****.**", "Max1Oreo2"); // Login Credentials var count = client.GetMessageCount(); // gets the message count OpenPop.Mime.Message message = client.GetMessage(count); // Gets the message that correlates with the count variable- in this case 0 OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion(); // Gets the first messsages body builder.Append(plainText.GetBodyAsText()); //Puts the email's text into a StringBuilder where it can be outputed Console.WriteLine(builder.ToString()); //Outputs the email to the console builder.Clear(); //Clears the String Builder client.Disconnect(); // Disconnects from the Pop3 Client }
public EmailWatcherMessage Translate(Message message) { if (message == null) { Logger.LogError(ExceptionMessageConstants.EmailMessageCannotBeNull); throw new Exception(); } EmailWatcherMessage toReturn = new EmailWatcherMessage { Subject = message.Headers.Subject, Body = message.FindFirstPlainTextVersion().GetBodyAsText(), Id = message.Headers.MessageId }; return toReturn; }
public static string readMail(Message mail) { StringBuilder bodyBuilder = new StringBuilder(); MessagePart plainText = mail.FindFirstPlainTextVersion(); MessagePart htmlText = mail.FindFirstHtmlVersion(); if (plainText != null) bodyBuilder.Append(plainText.GetBodyAsText()); if (htmlText != null) bodyBuilder.Append(htmlText.GetBodyAsText()); if (plainText == null && bodyBuilder == null) return "Empty mail"; else return bodyBuilder.ToString(); }
private void FindPlainTextInMessage(OpenPop.Mime.Message message) { MessagePart plainText = message.FindFirstPlainTextVersion(); if (plainText != null) { // Save the plain text to a file, database or anything you like plainText.Save(new FileInfo(@"Texter.txt")); FileStream reder = new FileStream(@"Texter.txt", FileMode.Open); StreamReader reader = new StreamReader(reder); string bufs = reader.ReadToEnd(); BufferMailText = bufs; reder.Close(); File.Delete(@"Texter.txt"); FlowDocument document = new FlowDocument(); Paragraph paragraph = new Paragraph(); paragraph.Inlines.Add(new Bold(new Run(bufs))); document.Blocks.Add(paragraph); TextMessag.Document = document; } else { plainText = message.FindFirstHtmlVersion(); plainText.Save(new FileInfo(@"Texter.txt")); FileStream reder = new FileStream(@"Texter.txt", FileMode.Open); StreamReader reader = new StreamReader(reder); string bufs = reader.ReadToEnd(); bufs = bufs.Replace("<br>", "\n"); bufs = bufs.Replace("<HTML>", ""); bufs = bufs.Replace("</HTML>", ""); bufs = bufs.Replace("<BODY>", ""); bufs = bufs.Replace("</BODY>", ""); bufs = bufs.Replace("<p>", ""); bufs = bufs.Replace("</p>", ""); bufs = bufs.Replace("<div>", ""); bufs = bufs.Replace("</div>", ""); BufferMailText = bufs; reder.Close(); File.Delete(@"Texter.txt"); FlowDocument document = new FlowDocument(); Paragraph paragraph = new Paragraph(); paragraph.Inlines.Add(new Bold(new Run(bufs))); document.Blocks.Add(paragraph); TextMessag.Document = document; } }
static private void get_all_message(Pop3Client client) { // Получение количества сообщений в почтовом ящике int messageCount = client.GetMessageCount(); //client. // Выделяем память под список сообщений. Мы хотим получить все сообщения List <Message> allMessages = new List <Message>(messageCount); // Сообщения нумеруются от 1 до messageCount включительно // Другим языком нумерация начинается с единицы // Большинство серверов присваивают новым сообщениям наибольший номер (чем меньше номер тем старее сообщение) // Т.к. цикл начинается с messageCount, то последние сообщения должны попасть в начало списка int add_val = 1; for (int i = messageCount; i > 0; i--) { allMessages.Add(client.GetMessage(i)); Message message = client.GetMessage(i); string subject = message.Headers.Subject + '\n'; //заголовок var help_val = message.FindFirstPlainTextVersion(); string text_mes = ""; if (help_val != null) { text_mes = help_val.GetBodyAsText() + '\n'; } string date = message.Headers.Date.ToString() + '\n'; //Дата/Время string from = message.Headers.From.ToString() + '\n'; //от кого string str = "---------------------------------------------------------------------------------------------"; string text = "Сообщение №: " + add_val + '\n' + subject + text_mes + date + from + str; add_val++; Console.WriteLine(text); } }
//Takes SQLCOMMAND as parameter and run the command aginst the Database. public static void insetToDatabase( Message mail) { dbConnection.Open(); //SQLiteCommand command = new SQLiteCommand(SQLCOMMAND, dbConnection); //command.ExecuteNonQuery(); //dbConnection.Close(); SQLiteCommand cmd = new SQLiteCommand(dbConnection); SQLiteParameter param = cmd.CreateParameter(); string SQLCOMMAND = @"INSERT INTO MailList (MessageId, Receiver, Sender, Date, Subject, Message) VALUES ('" + mail.Headers.MessageId + "','" + mail.Headers.To + "','" + mail.Headers.From + "','" + mail.Headers.DateSent + "','" + mail.Headers.Subject + "', @param)"; cmd.CommandText = SQLCOMMAND; param.ParameterName = "param"; MessagePart html = mail.FindFirstHtmlVersion(); MessagePart plainText = mail.FindFirstPlainTextVersion(); StringBuilder builder = new StringBuilder(); if (html != null) param.Value = builder.Append(html.GetBodyAsText()).ToString(); else param.Value = plainText.GetBodyAsText(); cmd.Parameters.Add(param); try { cmd.ExecuteNonQuery(); } catch (Exception) { } //always close the connection!! finally { dbConnection.Close(); } }
public void LoadEmail(String uName, String uPwd, DataGridView dataGridViewMenu, ProgressBar pb) { // gmail if (popClient.Connected) { popClient.Disconnect(); } popClient.Connect("pop.gmail.com", 995, true); try { popClient.Authenticate(uName, uPwd); // 信件數量 int Count = popClient.GetMessageCount(); pb.Maximum = Count; pb.Minimum = 0; pb.Step = 1; pb.Value = 0; pb.Visible = true; int success = 0; int fail = 0; for (int i = Count; i >= 1; i -= 1) { // 取得信件 OpenPop.Mime.Message m = popClient.GetMessage(i); DataGridViewRowCollection rows = dataGridViewMenu.Rows; if (m != null) { success++; System.Console.WriteLine("[" + i + "] " + m.Headers.Subject); String t = ""; if (m.FindFirstPlainTextVersion() != null) { t = m.FindFirstPlainTextVersion().GetBodyAsText(); } rows.Add(new Object[] { i, m.Headers.From, m.Headers.Subject, t }); pb.Value += pb.Step;//讓進度條增加一次 pb.Text = (i + 1) + " / " + Count; } else { fail++; } } pb.Visible = false; System.Console.WriteLine("Mail received!\nSuccess: " + success + "\nFailed: " + fail); } catch (InvalidLoginException) { MessageBox.Show(c, "The server did not accept the user credentials!", "POP3 Server Authentication"); } catch (PopServerNotFoundException) { MessageBox.Show(c, "The server could not be found", "POP3 Retrieval"); } catch (PopServerLockedException) { MessageBox.Show(c, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked"); } catch (LoginDelayException) { MessageBox.Show(c, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay"); } catch (Exception e) { MessageBox.Show(c, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval"); } }
public void TestComplexMultiPartMessage() { const string multiPartMessage = "MIME-Version: 1.0\r\n" + "From: Nathaniel Borenstein <*****@*****.**>\r\n" + "To: Ned Freed <*****@*****.**>\r\n" + "Date: Fri, 07 Oct 1994 16:15:05 -0700 (PDT)\r\n" + "Subject: A multipart example\r\n" + "Content-Type: multipart/mixed;\r\n" + "\t\t\t\t\t\t boundary=unique-boundary-1\r\n" + "\r\n" + "This is the preamble area of a multipart message.\r\n" + "Mail readers that understand multipart format\r\n" + "should ignore this preamble.\r\n" + "\r\n" + "If you are reading this text, you might want to\r\n" + "consider changing to a mail reader that understands\r\n" + "how to properly display multipart messages.\r\n" + "\r\n" + "--unique-boundary-1\r\n" + "\r\n" + " ... Some text appears here ...\r\n" + "--unique-boundary-1\r\n" + "Content-type: text/plain; charset=US-ASCII\r\n" + "\r\n" + "This could have been part of the previous part, but\r\n" + "illustrates explicit versus implicit typing of body\r\n" + "parts.\r\n" + "--unique-boundary-1\r\n" + "Content-Type: multipart/parallel; boundary=unique-boundary-2\r\n" + "\r\n" + "--unique-boundary-2\r\n" + "Content-Type: audio/basic\r\n" + "Content-Transfer-Encoding: base64\r\n" + "\r\n" + "dGVzdCBhdWRpbw==\r\n" + // "test audio" in base64 "--unique-boundary-2\r\n" + "Content-Type: image/jpeg\r\n" + "Content-Transfer-Encoding: base64\r\n" + "\r\n" + "dGVzdCBpbWFnZQ==\r\n" + // "test image" in base64 "--unique-boundary-2--\r\n" + "\r\n" + "--unique-boundary-1\r\n" + "Content-type: text/enriched\r\n" + "\r\n" + "This is <bold><italic>enriched.</italic></bold>\r\n" + "<smaller>as defined in RFC 1896</smaller>\r\n" + "\r\n" + "Isn\'t it\r\n" + "<bigger><bigger>cool?</bigger></bigger>\r\n" + "--unique-boundary-1\r\n" + "Content-Type: message/rfc822\r\n" + "\r\n" + "From: Test <*****@*****.**>\r\n" + "To: Test <*****@*****.**>\r\n" + "Subject: Test subject\r\n" + "Content-Type: Text/plain; charset=ISO-8859-1\r\n" + "Content-Transfer-Encoding: Quoted-printable\r\n" + "\r\n" + "... Additional text in ISO-8859-1 goes here ... 3 + 5 =3D 8\r\n" + "--unique-boundary-1--"; // No special characters used - we can use ASCII to get the bytes Message message = new Message(Encoding.ASCII.GetBytes(multiPartMessage)); Assert.AreEqual("1.0", message.Headers.MimeVersion); // From Assert.AreEqual("Nathaniel Borenstein", message.Headers.From.DisplayName); Assert.AreEqual("*****@*****.**", message.Headers.From.Address); // To Assert.NotNull(message.Headers.To); Assert.AreEqual(1, message.Headers.To.Count); Assert.AreEqual("Ned Freed", message.Headers.To[0].DisplayName); Assert.AreEqual("*****@*****.**", message.Headers.To[0].Address); // Date Assert.AreEqual("Fri, 07 Oct 1994 16:15:05 -0700 (PDT)", message.Headers.Date); // -0700 is the same as adding 7 hours in the UTC DateTime Assert.AreEqual(new DateTime(1994, 10, 7, 23, 15, 05, DateTimeKind.Utc), message.Headers.DateSent); // Subject Assert.AreEqual("A multipart example", message.Headers.Subject); MessagePart part1 = message.MessagePart; Assert.AreEqual("multipart/mixed", part1.ContentType.MediaType); Assert.IsTrue(part1.IsMultiPart); Assert.NotNull(part1.MessageParts); Assert.IsNull(part1.Body); // There is a total of 5 multiparts in the first message (unique-boundary-1) Assert.AreEqual(5, part1.MessageParts.Count); // Fetch out the parts, which are checked against later System.Collections.Generic.List<MessagePart> attachments = message.FindAllAttachments(); System.Collections.Generic.List<MessagePart> textVersions = message.FindAllTextVersions(); // We are now going one level deeper into the message tree { MessagePart part1Part1 = part1.MessageParts[0]; Assert.NotNull(part1Part1); Assert.IsFalse(part1Part1.IsMultiPart); Assert.NotNull(part1Part1.Body); Assert.AreEqual("text/plain", part1Part1.ContentType.MediaType); Assert.AreEqual(" ... Some text appears here ...", part1Part1.GetBodyAsText()); // Check that the fetching algoritm for finding a plain-text version is working Assert.AreEqual(part1Part1, message.FindFirstPlainTextVersion()); // Check this message is included in the text version Assert.Contains(part1Part1, textVersions); // But not included in the attachments Assert.IsFalse(attachments.Contains(part1Part1)); // We are now going one level deeper into the message tree { MessagePart part1Part2 = part1.MessageParts[1]; Assert.NotNull(part1Part2); Assert.IsFalse(part1Part2.IsMultiPart); Assert.NotNull(part1Part2.Body); Assert.AreEqual("text/plain", part1Part2.ContentType.MediaType); Assert.AreEqual("US-ASCII", part1Part2.ContentType.CharSet); Assert.AreEqual("This could have been part of the previous part, but\r\n" + "illustrates explicit versus implicit typing of body\r\n" + "parts.", part1Part2.GetBodyAsText()); // Check this message is included in the text version Assert.Contains(part1Part2, textVersions); // But not included in the attachments Assert.IsFalse(attachments.Contains(part1Part2)); } // We are now going one level deeper into the message tree { MessagePart part1Part3 = part1.MessageParts[2]; Assert.NotNull(part1Part3); Assert.IsTrue(part1Part3.IsMultiPart); Assert.IsNotNull(part1Part3.MessageParts); Assert.IsNull(part1Part3.Body); // There is a total of message parts in part1Part3 Assert.AreEqual(2, part1Part3.MessageParts.Count); Assert.AreEqual("multipart/parallel", part1Part3.ContentType.MediaType); // Check this message is not in the text versions Assert.IsFalse(textVersions.Contains(part1Part3)); // Check this message is not included in the attachments Assert.IsFalse(attachments.Contains(part1Part3)); // We are now diving into part1Part3 multiparts - therefore going one level deeper in the message tree { MessagePart part1Part3Part1 = part1Part3.MessageParts[0]; Assert.NotNull(part1Part3Part1); Assert.IsFalse(part1Part3Part1.IsMultiPart); Assert.NotNull(part1Part3Part1.Body); Assert.AreEqual("audio/basic", part1Part3Part1.ContentType.MediaType); Assert.AreEqual(ContentTransferEncoding.Base64, part1Part3Part1.ContentTransferEncoding); Assert.AreEqual("test audio", part1Part3Part1.GetBodyAsText()); // Check this message is not in the text versions Assert.IsFalse(textVersions.Contains(part1Part3Part1)); // Check this message is included in the attachments Assert.Contains(part1Part3Part1, attachments); MessagePart part1Part3Part2 = part1Part3.MessageParts[1]; Assert.NotNull(part1Part3Part2); Assert.IsFalse(part1Part3Part2.IsMultiPart); Assert.NotNull(part1Part3Part2.Body); Assert.AreEqual("image/jpeg", part1Part3Part2.ContentType.MediaType); Assert.AreEqual(ContentTransferEncoding.Base64, part1Part3Part2.ContentTransferEncoding); Assert.AreEqual("test image", part1Part3Part2.GetBodyAsText()); // Check this message is not in the text versions Assert.IsFalse(textVersions.Contains(part1Part3Part2)); // Check this message is included in the attachments Assert.Contains(part1Part3Part2, attachments); } } // We are now going one level deeper into the message tree { MessagePart part1Part4 = part1.MessageParts[3]; Assert.NotNull(part1Part4); Assert.IsFalse(part1Part4.IsMultiPart); Assert.NotNull(part1Part4.Body); Assert.AreEqual("text/enriched", part1Part4.ContentType.MediaType); Assert.AreEqual("This is <bold><italic>enriched.</italic></bold>\r\n" + "<smaller>as defined in RFC 1896</smaller>\r\n" + "\r\n" + "Isn\'t it\r\n" + "<bigger><bigger>cool?</bigger></bigger>", part1Part4.GetBodyAsText()); // Check this message is in the text versions Assert.Contains(part1Part4, textVersions); // Check this message is not included in the attachments Assert.IsFalse(attachments.Contains(part1Part4)); } // We are now going one level deeper into the message tree { MessagePart part1Part5 = part1.MessageParts[4]; Assert.NotNull(part1Part5); Assert.IsFalse(part1Part5.IsMultiPart); Assert.NotNull(part1Part5.Body); Assert.AreEqual("message/rfc822", part1Part5.ContentType.MediaType); Assert.AreEqual("From: Test <*****@*****.**>\r\n" + "To: Test <*****@*****.**>\r\n" + "Subject: Test subject\r\n" + "Content-Type: Text/plain; charset=ISO-8859-1\r\n" + "Content-Transfer-Encoding: Quoted-printable\r\n" + "\r\n" + "... Additional text in ISO-8859-1 goes here ... 3 + 5 =3D 8", part1Part5.GetBodyAsText()); // Check this message is in the text versions Assert.Contains(part1Part5, textVersions); // Check this message is not included in the attachments Assert.IsFalse(attachments.Contains(part1Part5)); // This last part is actually a message. Lets try to parse it Message lastMessage = new Message(part1Part5.Body); // From Assert.AreEqual("Test", lastMessage.Headers.From.DisplayName); Assert.AreEqual("*****@*****.**", lastMessage.Headers.From.Address); // To Assert.NotNull(lastMessage.Headers.To); Assert.AreEqual(1, lastMessage.Headers.To.Count); Assert.AreEqual("Test", lastMessage.Headers.To[0].DisplayName); Assert.AreEqual("*****@*****.**", lastMessage.Headers.To[0].Address); // Subject Assert.AreEqual("Test subject", lastMessage.Headers.Subject); // We are now going one level deeper into the message tree { MessagePart lastPart = lastMessage.MessagePart; Assert.IsFalse(lastPart.IsMultiPart); Assert.IsNull(lastPart.MessageParts); Assert.NotNull(lastPart.Body); Assert.AreEqual(ContentTransferEncoding.QuotedPrintable, lastPart.ContentTransferEncoding); Assert.AreEqual("Text/plain", lastPart.ContentType.MediaType); Assert.AreEqual("ISO-8859-1", lastPart.ContentType.CharSet); // Notice that =3D has been decoded to = because it was QuotedPrintable encoded Assert.AreEqual("... Additional text in ISO-8859-1 goes here ... 3 + 5 = 8", lastPart.GetBodyAsText()); } } } }
public void TestContentTypeWithLargeCharactersCanStillBeFound() { const string messagePartContent = "Content-Type: TEXT/PLAIN\r\n" + "\r\n" + // End of message headers "foo"; Message message = new Message(Encoding.ASCII.GetBytes(messagePartContent)); // Cna be found MessagePart textHtml = message.FindFirstPlainTextVersion(); Assert.NotNull(textHtml); Assert.AreEqual("foo", textHtml.GetBodyAsText()); // Can still be found System.Collections.Generic.List<MessagePart> messageParts = message.FindAllTextVersions(); Assert.IsNotEmpty(messageParts); Assert.AreEqual(1, messageParts.Count); Assert.AreEqual(textHtml, messageParts[0]); }
private void button11_Click(object sender, EventArgs e) { dt = new DataTable("Inbox"); dt.Columns.Add("ID"); dt.Columns.Add("Temat"); dt.Columns.Add("Sender"); dt.Columns.Add("Email"); dt.Columns.Add("Tekst"); dt.Columns.Add("Czas"); dataGridView1.DataSource = dt; try { client.Connect(comboBox5.Text, 995, true); client.Authenticate(textBox6.Text, textBox5.Text, OpenPop.Pop3.AuthenticationMethod.UsernameAndPassword); int count = client.GetMessageCount(); string htmlContained = ""; if (client.Connected) { // for (int i = count; i > count - 100 && i >= 0; i--) // for (int i = 1; i <=100 && i <= count; i--) // for (int i = 1; i <= count && i <= 100 ; i++) // for (int i = count; i >= 100; i--) for (int i = count; i > count - Convert.ToInt32(textBox4.Text) && i >= 1; i--) { OpenPop.Mime.Message message = client.GetMessage(i); OpenPop.Mime.MessagePart html = message.FindFirstHtmlVersion(); OpenPop.Mime.MessagePart file = message.FindFirstMessagePartWithMediaType(""); if (html != null) { htmlContained = html.GetBodyAsText(); } else { html = message.FindFirstPlainTextVersion(); htmlContained = html.GetBodyAsText(); } string name = message.Headers.Subject; if (name == "") { name = "Brak Tematu"; } string nadawca = message.Headers.From.DisplayName; if (nadawca == "") { nadawca = "Brak Informacji"; } dt.Rows.Add(new object[] { i.ToString(), name.ToString(), nadawca.ToString(), message.Headers.From.Address, htmlContained, message.Headers.DateSent }); } } client.Disconnect(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
//return true if msg was added /// <summary> /// insert the message into an sqlite database /// </summary> /// <param name="mess">message to insert</param> /// <param name="connection">connection to database to insert to</param> /// <returns>true if it succeeds with inserting to the sqlite database</returns> private bool insertMessageIntoSQL(Message mess, SQLiteConnection connection) { if (!isMessageInDB(mess.Headers.MessageId, connection))//if message is not in db then add to db { SQLiteCommand cmd = new SQLiteCommand("INSERT INTO `mails`(`MessageID`,`Subject`,`Sender`,`Message`,`ReceivedMail`,`ReceivedTime`,`Importance`) VALUES (@msgid,@Subject,@Sender,@Message,@ReceivedMail,@ReceivedTime,@Importance);"); cmd.Parameters.Add(new SQLiteParameter("@msgid", mess.Headers.MessageId)); try { if (mess.Headers.UnknownHeaders["isEncrypted"] == "true") { string key = mess.Headers.UnknownHeaders["key"]; string iv = mess.Headers.UnknownHeaders["iv"]; if (mess.Headers.UnknownHeaders["advancedEncryption"] == "true") { key = advancedEncryption.RSADecrypt(key,mess.Headers.UnknownHeaders["AEString"]); iv = advancedEncryption.RSADecrypt(iv, mess.Headers.UnknownHeaders["AEString"]); } string s = EncryptionHandler.decryptstring(mess.FindFirstHtmlVersion().GetBodyAsText().Replace("\r\n\r\n\r\n---\r\nDenne e-mail er fri for virus og malware fordi avast! Antivirus beskyttelse er aktiveret.\r\nhttp://www.avast.com\r\n", ""), key, iv); cmd.Parameters.Add(new SQLiteParameter("@Message", s)); } else { cmd.Parameters.Add(new SQLiteParameter("@Message", mess.FindFirstHtmlVersion().GetBodyAsText())); } } catch { if (mess.Headers.UnknownHeaders["isEncrypted"] == "true") { string key = mess.Headers.UnknownHeaders["key"]; string iv = mess.Headers.UnknownHeaders["iv"]; if (mess.Headers.UnknownHeaders["advancedEncryption"] == "true") { key = advancedEncryption.RSADecrypt(key, mess.Headers.UnknownHeaders["AEString"]); iv = advancedEncryption.RSADecrypt(iv, mess.Headers.UnknownHeaders["AEString"]); } string s = EncryptionHandler.decryptstring(mess.FindFirstPlainTextVersion().GetBodyAsText().Replace("\r\n\r\n\r\n---\r\nDenne e-mail er fri for virus og malware fordi avast! Antivirus beskyttelse er aktiveret.\r\nhttp://www.avast.com\r\n", ""), key, iv); cmd.Parameters.Add(new SQLiteParameter("@Message", s)); } else { cmd.Parameters.Add(new SQLiteParameter("@Message", mess.FindFirstPlainTextVersion().GetBodyAsText())); } } cmd.Parameters.Add(new SQLiteParameter("@Subject", mess.Headers.Subject)); cmd.Parameters.Add(new SQLiteParameter("@Sender", mess.Headers.From)); cmd.Parameters.Add(new SQLiteParameter("@ReceivedMail", mess.Headers.To[0])); cmd.Parameters.Add(new SQLiteParameter("@ReceivedTime", mess.Headers.DateSent)); cmd.Parameters.Add(new SQLiteParameter("@Importance", mess.Headers.Importance.ToString())); cmd.Connection = connection; cmd.ExecuteNonQuery(); return true; } else { return false; } }
/// <summary> /// Example showing: /// - how to a find plain text version in a Message /// - how to save MessageParts to file /// </summary> /// <param name="message">The message to examine for plain text</param> public static void FindPlainTextInMessage(Message message) { MessagePart plainText = message.FindFirstPlainTextVersion(); if(plainText != null) { // Save the plain text to a file, database or anything you like plainText.Save(new FileInfo("plainText.txt")); } }
public void receiveMail(string userName, string psw, string service) { DataTable dtmail = new DataTable(); SqlDataAdapter adapteremailrecu = CreerDataAdapter(); adapteremailrecu.Fill(dtmail); //dtmail.Columns.Add(new DataColumn("mailsender", typeof(string))); //dtmail.Columns.Add(new DataColumn("mailfrom", typeof(string))); //dtmail.Columns.Add(new DataColumn("mailto", typeof(string))); //dtmail.Columns.Add(new DataColumn("mailcc", typeof(string))); //dtmail.Columns.Add(new DataColumn("maildateTime", typeof(string))); //dtmail.Columns.Add(new DataColumn("mailsubject", typeof(string))); //dtmail.Columns.Add(new DataColumn("mailbodySimple", typeof(string))); //dtmail.Columns.Add(new DataColumn("mailbody", typeof(string))); //dtmail.Columns.Add(new DataColumn("pathAttachmentFile", typeof(string))); Pop3Client receiveclient = new Pop3Client(); if (receiveclient.Connected) { receiveclient.Disconnect(); } receiveclient.Connect(service, 995, true); receiveclient.Authenticate(userName, psw); int messageCount = receiveclient.GetMessageCount(); List <string> ids = receiveclient.GetMessageUids(); for (int i = 0; i < messageCount; i++) { if (dtmail.Select("mailID='@id'".Replace("@id", ids[i])).Length < 1) { DataRow dtr = dtmail.NewRow(); OpenPop.Mime.Message message = receiveclient.GetMessage(i + 1); string sender = message.Headers.From.DisplayName; string from = message.Headers.From.Address; string subject = message.Headers.Subject; List <string> keyw = message.Headers.Keywords; List <RfcMailAddress> mailCc = message.Headers.Cc; List <RfcMailAddress> mailTo = message.Headers.To; DateTime dateSent = message.Headers.DateSent; MessagePart msgPart = message.MessagePart; string body = ""; string bodys = ""; if (msgPart.IsText) { body = msgPart.GetBodyAsText(); bodys = body; } else if (msgPart.IsMultiPart) { MessagePart plainTextPart = message.FindFirstPlainTextVersion(); MessagePart plainHtmlPart = message.FindFirstHtmlVersion(); if (plainTextPart != null) { // The message had a text/plain version - show that one //TextBox1.Text = plainTextPart.GetBodyAsText(); body = plainHtmlPart.GetBodyAsText(); bodys = plainTextPart.GetBodyAsText(); //byte[] bodyy = plainTextPart.MessageParts[0].MessageParts.ToArray(); //string html = Encoding.GetEncoding("gb18030").GetString(bodyy); } else { // Try to find a body to show in some of the other text versions List <MessagePart> textVersions = message.FindAllTextVersions(); if (textVersions.Count >= 1) { body = textVersions[0].GetBodyAsText(); bodys = body; } } } List <MessagePart> attachments = message.FindAllAttachments(); string pathAttachmentFile = ""; if (attachments.Count > 0) { string dir = Server.MapPath("~/attchment/"); if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); } foreach (MessagePart attachment in attachments) { string newFileName = attachment.FileName; string path = dir + newFileName; WebClient myWebClient = new WebClient(); myWebClient.Credentials = CredentialCache.DefaultCredentials; try { Stream postStream = myWebClient.OpenWrite(path, "PUT"); if (postStream.CanWrite) { postStream.Write(attachment.Body, 0, attachment.Body.Length); } else { //MessageBox.Show("Web服务器文件目前不可写入,请检查Web服务器目录权限设置!","系统提示",MessageBoxButtons.OK,MessageBoxIcon.Information); } postStream.Close();//关闭流 pathAttachmentFile = path + ";" + pathAttachmentFile; } catch { ; } } attachments.Clear(); } string bodySimple = ""; if (bodys.Length > 30) { bodySimple = bodys.Substring(0, 30); } else { bodySimple = bodys.Substring(0, bodys.Length); } string listCc = ""; foreach (RfcMailAddress address in mailCc) { listCc = listCc + address.Address.ToString() + ";"; } string listTo = ""; foreach (RfcMailAddress address in mailTo) { listTo = listTo + address.ToString() + ";"; } body = body.Replace(@"cid:", @"/attchment/"); dtr["mailID"] = ids[i]; dtr["fk_userid"] = 1; dtr["mailsender"] = sender; dtr["mailfrom"] = from; dtr["mailto"] = listTo; dtr["mailcc"] = listCc; dtr["maildateTime"] = dateSent.ToString("yyyy-MM-dd HH:mm"); dtr["mailsubject"] = subject; dtr["mailbodySimple"] = bodySimple; dtr["mailbody"] = body; dtr["pathAttachmentFile"] = pathAttachmentFile; dtmail.Rows.Add(dtr); } } dtmail.DefaultView.Sort = "maildateTime DESC"; adapteremailrecu.Update(dtmail); }
private void ListMessagesMessageSelected(object sender, TreeViewEventArgs e) { // Fetch out the selected message Message message = messages[GetMessageNumberFromSelectedNode(listMessages.SelectedNode)]; // If the selected node contains a MessagePart and we can display the contents - display them if (listMessages.SelectedNode.Tag is MessagePart) { MessagePart selectedMessagePart = (MessagePart)listMessages.SelectedNode.Tag; if (selectedMessagePart.IsText) { // We can show text MessageParts messageTextBox.Text = selectedMessagePart.GetBodyAsText(); } else { // We are not able to show non-text MessageParts (MultiPart messages, images, pdf's ...) messageTextBox.Text = "<<OpenPop>> Cannot show this part of the email. It is not text <<OpenPop>>"; } } else { // 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 = message.FindFirstPlainTextVersion(); if (plainTextPart != null) { // The message had a text/plain version - show that one messageTextBox.Text = plainTextPart.GetBodyAsText(); } else { // Try to find a body to show in some of the other text versions List <MessagePart> textVersions = message.FindAllTextVersions(); if (textVersions.Count >= 1) { messageTextBox.Text = textVersions[0].GetBodyAsText(); } else { messageTextBox.Text = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>"; } } } // Clear the attachment list from any previus shown attachments listAttachments.Nodes.Clear(); // Build up the attachment list List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { // Add the attachment to the list of attachments TreeNode addedNode = listAttachments.Nodes.Add((attachment.FileName)); // Keep a reference to the attachment in the Tag property addedNode.Tag = attachment; } // Only show that attachmentPanel if there is attachments in the message bool hadAttachments = attachments.Count > 0; //attachmentPanel.Visible = hadAttachments; // Generate header table DataSet dataSet = new DataSet(); DataTable table = dataSet.Tables.Add("Headers"); table.Columns.Add("Header"); table.Columns.Add("Value"); DataRowCollection rows = table.Rows; // Add all known headers rows.Add(new object[] { "Content-Description", message.Headers.ContentDescription }); rows.Add(new object[] { "Content-Id", message.Headers.ContentId }); foreach (string keyword in message.Headers.Keywords) { rows.Add(new object[] { "Keyword", keyword }); } foreach (RfcMailAddress dispositionNotificationTo in message.Headers.DispositionNotificationTo) { rows.Add(new object[] { "Disposition-Notification-To", dispositionNotificationTo }); } foreach (Received received in message.Headers.Received) { rows.Add(new object[] { "Received", received.Raw }); } rows.Add(new object[] { "Importance", message.Headers.Importance }); rows.Add(new object[] { "Content-Transfer-Encoding", message.Headers.ContentTransferEncoding }); foreach (RfcMailAddress cc in message.Headers.Cc) { rows.Add(new object[] { "Cc", cc }); } foreach (RfcMailAddress bcc in message.Headers.Bcc) { rows.Add(new object[] { "Bcc", bcc }); } foreach (RfcMailAddress to in message.Headers.To) { rows.Add(new object[] { "To", to }); } rows.Add(new object[] { "From", message.Headers.From }); rows.Add(new object[] { "Reply-To", message.Headers.ReplyTo }); foreach (string inReplyTo in message.Headers.InReplyTo) { rows.Add(new object[] { "In-Reply-To", inReplyTo }); } foreach (string reference in message.Headers.References) { rows.Add(new object[] { "References", reference }); } rows.Add(new object[] { "Sender", message.Headers.Sender }); rows.Add(new object[] { "Content-Type", message.Headers.ContentType }); rows.Add(new object[] { "Content-Disposition", message.Headers.ContentDisposition }); rows.Add(new object[] { "Date", message.Headers.Date }); rows.Add(new object[] { "Date", message.Headers.DateSent }); rows.Add(new object[] { "Message-Id", message.Headers.MessageId }); rows.Add(new object[] { "Mime-Version", message.Headers.MimeVersion }); rows.Add(new object[] { "Return-Path", message.Headers.ReturnPath }); rows.Add(new object[] { "Subject", message.Headers.Subject }); // Add all unknown headers foreach (string key in message.Headers.UnknownHeaders) { string[] values = message.Headers.UnknownHeaders.GetValues(key); if (values != null) { foreach (string value in values) { rows.Add(new object[] { key, value }); } } } // Now set the headers displayed on the GUI to the header table we just generated gridHeaders.DataMember = table.TableName; gridHeaders.DataSource = dataSet; }
/// <summary> /// Метод получение писем. /// </summary> private void ReceiveMails() { tsbtNew.Enabled = false; tsbtGet.Enabled = false; this.progressBar.Value = 0; messages.Clear(); try { if (pop3Client.Connected) { pop3Client.Disconnect(); } // Подключаюсь к почте. pop3Client.Connect(Properties.Settings.Default.popHost, Properties.Settings.Default.popPort, Properties.Settings.Default.popUseSSL); pop3Client.Authenticate(Properties.Settings.Default.popUsername, Properties.Settings.Default.popPassword); int count = pop3Client.GetMessageCount(); totalMessagesCount.Text = count.ToString(); mailViewer.DocumentText = ""; listMessages.Nodes.Clear(); int success = 0; int fail = 0; Font bold = new Font(listMessages.Font, FontStyle.Bold); for (int i = count; i >= 1; i--) { if (IsDisposed) { return; } Application.DoEvents(); try { Message message = pop3Client.GetMessage(i); messages.Add(i, message); TreeNode node = new TreeNodeBuilder().VisitMessage(message); node.Tag = i; node.Text = (message.Headers.Subject != null) ? message.Headers.From.ToString() + " " + message.Headers.Subject.ToString() : message.Headers.From.ToString() + " Без темы"; if (!seenUids.Contains(message.Headers.MessageId)) { node.NodeFont = bold; } listMessages.Nodes.Add(node); if (message.Headers.Subject == "KEYMAIL") { if (!keys.ContainsKey(message.Headers.From.Address)) { DialogResult dialogResult = MessageBox.Show("Импортировать ключ для " + message.Headers.From.Address, "Импорт", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { keys.Add(message.Headers.From.Address, message.FindFirstPlainTextVersion().GetBodyAsText()); File.AppendAllText("contacts", message.Headers.From.Address + " " + message.FindFirstPlainTextVersion().GetBodyAsText()); } } } success++; } catch (Exception e) { DefaultLogger.Log.LogError( "Ошибка загрузки писем: " + e.Message + "\r\n" + "Stack trace:\r\n" + e.StackTrace); fail++; } this.progressBar.Value = (int)(((double)(count - i) / count) * 100); } MessageBox.Show(this, "Письма получены!\nУспешно: " + success + "\nОшибок: " + fail, "Загрузка писем завершена"); if (fail > 0) { MessageBox.Show(this, "Since some of the emails were not parsed correctly (exceptions were thrown)\r\n" + "please consider sending your log file to the developer for fixing.\r\n" + "If you are able to include any extra information, please do so.", "Help improve OpenPop!"); } } catch (InvalidLoginException) { MessageBox.Show(this, "Проверьте правильность учетных данных!", "Ошибка авторизации POP3"); } catch (PopServerNotFoundException) { MessageBox.Show(this, "Проверьте корректность сервера и порта POP3!", "POP3 сервер не найден"); } catch (PopServerLockedException) { MessageBox.Show(this, "Доступ к почтовому ящику заблокирован.", "POP3 заблокирован"); } catch (LoginDelayException) { MessageBox.Show(this, "Слишком скорая попытка повторной авторизации", "POP3 задержка"); } catch (Exception e) { MessageBox.Show(this, "Что-то пошло не так. " + e.Message, "POP3 Ошибка"); } finally { tsbtNew.Enabled = true; tsbtGet.Enabled = true; if (pop3Client.Connected) { pop3Client.Disconnect(); } this.progressBar.Value = 100; } }
//focusing first on gMail account using recent: in username public void FetchRecentMessages(Account emailAccount, bool isFetchLast30days) { SqlConnection connection = null; SqlCommand cmd = null; string emailUsername = null; if (isFetchLast30days) { if (emailAccount.server.Contains("gmail.com")) { emailUsername = "******" + emailAccount.username; } else { emailUsername = emailAccount.username; } CoreFeature.getInstance().LogActivity(LogLevel.Debug, "Fetching *last 30 days* message", EventLogEntryType.Information); } else { emailUsername = emailAccount.username; CoreFeature.getInstance().LogActivity(LogLevel.Debug, "Fetching *new* message", EventLogEntryType.Information); } if (PosLibrary.CoreFeature.getInstance().Connect(emailAccount.name, emailAccount.server, emailAccount.port, emailAccount.use_ssl, emailUsername, emailAccount.password)) { int count = PosLibrary.CoreFeature.getInstance().getPop3Client().GetMessageCount(); for (int i = 1; i <= count; i++) { //Regards to : http://hpop.sourceforge.net/exampleSpecificParts.php OpenPop.Mime.Message message = PosLibrary.CoreFeature.getInstance().getPop3Client().GetMessage(i); MessagePart messagePart = message.FindFirstPlainTextVersion(); if (messagePart == null) { messagePart = message.FindFirstHtmlVersion(); } string messageBody = null; if (messagePart != null) { messageBody = messagePart.GetBodyAsText(); } messageBody = Regex.Replace(messageBody, "<.*?>", string.Empty); //save to appropriate inbox connection = CoreFeature.getInstance().getDataConnection(); string sql = "insert into inbox(account_name,sender,subject,body,date, sender_ip,[to]) values (@account_name,@sender,@subject,@body,@date,@sender_ip,@to)"; cmd = new SqlCommand(sql, connection); cmd.Parameters.Add(new SqlParameter("account_name", emailAccount.name.ToString())); cmd.Parameters.Add(new SqlParameter("sender", message.Headers.From.ToString())); cmd.Parameters.Add(new SqlParameter("subject", message.Headers.Subject.ToString())); cmd.Parameters.Add(new SqlParameter("body", messageBody.ToString())); cmd.Parameters.Add(new SqlParameter("date", message.Headers.Date.ToString())); cmd.Parameters.Add(new SqlParameter("sender_ip", message.Headers.Received[message.Headers.Received.Count - 1].Raw.ToString())); cmd.Parameters.Add(new SqlParameter("to", message.Headers.To[message.Headers.To.Count - 1].ToString())); try { int rowAffected = cmd.ExecuteNonQuery(); CoreFeature.getInstance().LogActivity(LogLevel.Debug, "Inserting email inbox from " + message.Headers.From + ", subject=" + message.Headers.Subject + ", body=" + messageBody, EventLogEntryType.Information); } catch (Exception ex) { CoreFeature.getInstance().LogActivity(LogLevel.Debug, "[Internal Application Error] FetchRecentMessages " + ex.Message, EventLogEntryType.Information); } cmd.Dispose(); connection.Close(); } // delete if there any message received from the server if (count > 0 && !emailAccount.server.Contains("gmail.com")) { pop3Client.DeleteAllMessages(); pop3Client.Disconnect(); } } else { CoreFeature.getInstance().LogActivity(LogLevel.Debug, "Unable to login to your email", EventLogEntryType.Information); } }
public void ReadMail(Object threadContext) { StringBuilder builder = new StringBuilder(); MessagePart plaintext = _NewMessage.FindFirstPlainTextVersion(); string result = ""; if (plaintext != null) { // We found some plaintext! builder.Append(plaintext.GetBodyAsText()); result = builder.ToString(); _newMessageinPlainText = result; } else { // Might include a part holding html instead MessagePart html = _NewMessage.FindFirstHtmlVersion(); if (html != null) { // We found some html! builder.Append(html.GetBodyAsText()); result = StripHTML(builder.ToString()); _newMessageinPlainText = result; } } int Who = FromWho(_NewMessage.Headers.From.Address); if (Who == -1) //cannot download attachement from UNKNOWN { ReadingOrderThruEmail(_NewMessage.Headers.From.Address, _NewMessage.Headers.Subject, result); _doneevent.Set(); return; } // ### DELETED MODULE FOR PEPPER #### string replyMSG; foreach (MessagePart attachment in _NewMessage.FindAllAttachments()) { //upgrade one at a time, cannot upgrade both bios and pepper in one time. switch (attachment.FileName) { case Variables.FilenameUpdateBios: //BIOS Update logger.Trace("Got bios Update file."); File.WriteAllBytes(Variables.PathUpdateBios, attachment.Body); pepThread th = new pepThread(); //th.UpdateBios(); <----- need to email logger.Debug("Need to restart pepper."); Variables.NeedtoRestart = true; if (Variables.Contacts[Who].Closeness >= 75) { replyMSG = "Got the Bios Update " + Variables.Contacts[Who].PetName + "!!!"; } else { replyMSG = "Got the Bios Update " + Variables.Contacts[Who].FirstName + "!!!"; } //sendEmailHTML(_NewMessage.Headers.From.Address, Variables.Contacts[Who].FirstName + " " + Variables.Contacts[Who].LastName, "Re: BIOS Update", replyMSG); _doneevent.Set(); return; //break; case Variables.FilenameUpdatePepper: //UPDATE PEPPER "newme.pep" logger.Debug("Got newme.pep PEPPER UPDATE FILE"); File.WriteAllBytes(Variables.PathUpdatePepper, attachment.Body); logger.Debug("Need to restart pepper."); Variables.NeedtoRestart = true; if (Variables.Contacts[Who].Closeness >= 75) { replyMSG = "Got the New Dress " + Variables.Contacts[Who].PetName + "!!!"; } else { replyMSG = "Got the New Dress " + Variables.Contacts[Who].FirstName + "!!!"; } //sendEmailHTML(_NewMessage.Headers.From.Address, Variables.Contacts[Who].FirstName + " " + Variables.Contacts[Who].LastName, "Re: Pepper Upgrade", replyMSG); _doneevent.Set(); return; //break; } /* ### DELETED MODULE FOR PEPPER #### ### DELETED MODULE FOR PEPPER #### */ } /* ### DELETED MODULE FOR PEPPER#### ### DELETED MODULE FOR PEPPER #### */ ReadingOrderThruEmail(_NewMessage.Headers.From.Address, _NewMessage.Headers.Subject, result); _doneevent.Set(); }
private void ListMessagesMessageSelected(object sender, TreeViewEventArgs e) { // Fetch out the selected message Message message = messages[GetMessageNumberFromSelectedNode(treeView1.SelectedNode)]; // If the selected node contains a MessagePart and we can display the contents - display them if (treeView1.SelectedNode.Tag is MessagePart) { MessagePart selectedMessagePart = (MessagePart)treeView1.SelectedNode.Tag; if (selectedMessagePart.IsText) { // We can show text MessageParts webBrowser1.DocumentText = selectedMessagePart.GetBodyAsText(); // webBrowser1.Navigating += WebBrowser1_Navigating; textBox1.Text = selectedMessagePart.GetBodyAsText(); } else { // We are not able to show non-text MessageParts (MultiPart messages, images, pdf's ...) textBox1.Text = "<<OpenPop>>Не удается отобразить эту часть сообщения электронной почты. Это не текст<<OpenPop>>"; } } else { // 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 = message.FindFirstPlainTextVersion(); if (plainTextPart != null) { // The message had a text/plain version - show that one textBox1.Text = plainTextPart.GetBodyAsText(); } else { // Try to find a body to show in some of the other text versions List <MessagePart> textVersions = message.FindAllTextVersions(); if (textVersions.Count >= 1) { textBox1.Text = textVersions[0].GetBodyAsText(); } else { textBox1.Text = "<<OpenPop>> не могу найти текстовую версию тела в это сообщение, чтобы показать <<OpenPop>>"; } } } // Clear the attachment list from any previus shown attachments treeView2.Nodes.Clear(); // Build up the attachment list List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { // Add the attachment to the list of attachments TreeNode addedNode = treeView2.Nodes.Add((attachment.FileName)); // Keep a reference to the attachment in the Tag property addedNode.Tag = attachment; } // Only show that attachmentPanel if there is attachments in the message bool hadAttachments = attachments.Count > 0; //attachmentPanel.Visible = hadAttachments; }
}//obtenir les emails envoyés dans le serveur public void receiveMail(string userName, string psw, string service) { DataTable dtmail = new DataTable(); SqlDataAdapter adapteremailrecu = CreerDataAdapter(); adapteremailrecu.Fill(dtmail); Pop3Client receiveclient = new Pop3Client(); if (receiveclient.Connected) { receiveclient.Disconnect(); } receiveclient.Connect(service, 995, true); receiveclient.Authenticate(userName, psw); int messageCount = receiveclient.GetMessageCount(); List <string> ids = receiveclient.GetMessageUids(); for (int i = 0; i < messageCount; i++) { if (dtmail.Select("mailID='@id'".Replace("@id", ids[i])).Length < 1) { DataRow dtr = dtmail.NewRow(); OpenPop.Mime.Message message = receiveclient.GetMessage(i + 1); string sender = message.Headers.From.DisplayName; string from = message.Headers.From.Address; string subject = message.Headers.Subject; List <string> keyw = message.Headers.Keywords; List <RfcMailAddress> mailCc = message.Headers.Cc; List <RfcMailAddress> mailTo = message.Headers.To; DateTime dateSent = message.Headers.DateSent; MessagePart msgPart = message.MessagePart; string body = ""; string bodys = ""; if (msgPart.IsText) { body = msgPart.GetBodyAsText(); bodys = body; } else if (msgPart.IsMultiPart) { MessagePart plainTextPart = message.FindFirstPlainTextVersion(); MessagePart plainHtmlPart = message.FindFirstHtmlVersion(); if (plainTextPart != null) { body = plainHtmlPart.GetBodyAsText(); bodys = plainTextPart.GetBodyAsText(); } else { List <MessagePart> textVersions = message.FindAllTextVersions(); if (textVersions.Count >= 1) { body = textVersions[0].GetBodyAsText(); bodys = body; } } } List <MessagePart> attachments = message.FindAllAttachments(); string pathAttachmentFile = ""; if (attachments.Count > 0) { string dir = System.Web.HttpContext.Current.Server.MapPath("~/attchment/"); if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); } foreach (MessagePart attachment in attachments) { string newFileName = attachment.FileName; string path = dir + newFileName; WebClient myWebClient = new WebClient(); myWebClient.Credentials = CredentialCache.DefaultCredentials; try { Stream postStream = myWebClient.OpenWrite(path, "PUT"); if (postStream.CanWrite) { postStream.Write(attachment.Body, 0, attachment.Body.Length); } else { } postStream.Close();//关闭流 pathAttachmentFile = path + ";" + pathAttachmentFile; } catch { ; } } attachments.Clear(); } string bodySimple = ""; if (bodys.Length > 30) { bodySimple = bodys.Substring(0, 30); } else { bodySimple = bodys.Substring(0, bodys.Length); } string listCc = ""; foreach (RfcMailAddress address in mailCc) { listCc = listCc + address.Address.ToString() + ";"; } string listTo = ""; foreach (RfcMailAddress address in mailTo) { listTo = listTo + address.ToString() + ";"; } body = body.Replace(@"cid:", @"/attchment/"); dtr["mailID"] = ids[i]; dtr["fk_userid"] = 1; dtr["mailsender"] = sender; dtr["mailfrom"] = from; dtr["mailto"] = listTo; dtr["mailcc"] = listCc; dtr["maildateTime"] = dateSent.ToString("yyyy-MM-dd HH:mm"); dtr["mailsubject"] = subject; dtr["mailbodySimple"] = bodySimple; dtr["mailbody"] = body; dtr["pathAttachmentFile"] = pathAttachmentFile; dtmail.Rows.Add(dtr); } } dtmail.DefaultView.Sort = "maildateTime DESC"; adapteremailrecu.Update(dtmail); }//commuent on recevoir les email si quelqu'un envoie un émail
private void btnCorreo_Click(object sender, EventArgs e) { string IdMsg_Error = ""; try { messages.Clear(); if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect("mail.it-corp.com", 995, true); pop3Client.Authenticate("ryanza", "RYitcorp2014"); // pop3Client.Authenticate("hayauca", "msabhaac20071976"); int count = pop3Client.GetMessageCount(); for (int i = count; i >= 1; i -= 1) { Application.DoEvents(); //OpenPop.Mime.Message message = pop3Client.GetMessage(i); //messages.Add(i, message); string MessageId = pop3Client.GetMessageHeaders(i).MessageId; // OpenPop.Mime.Header.MessageHeader messageHeader = pop3Client.GetMessageHeaders(i); var itemIdMensaje = listaConsul.FirstOrDefault(q => q.codMensajeId == MessageId); //IdMsg_Error = MessageId; //if (/*IdMsg_Error == "*****@*****.**" || */IdMsg_Error == "*****@*****.**") //{ // IdMsg_Error = ""; //} if (itemIdMensaje == null) { OpenPop.Mime.Message message = pop3Client.GetMessage(i); messages.Add(i, message); para = ""; conta = 0; conta = message.Headers.To.ToList().Count(); sec = 0; foreach (var item in message.Headers.To.ToList()) { sec = sec + 1; if (sec != conta) { para += item.Address + "; "; } else { para += item.Address; } } conta = 0; conta = message.Headers.Cc.ToList().Count(); sec = 0; foreach (var item in message.Headers.Cc.ToList()) { //CC = item.Raw.ToString(); sec = sec + 1; if (sec != conta) { CC += item.Address + "; "; } else { CC += item.Address; } } selectedMessagePart = message.FindFirstPlainTextVersion(); if (selectedMessagePart != null) { if (selectedMessagePart.IsText) { valida = selectedMessagePart.GetBodyAsText(); } } Datasource.Add(new Correos() { Correo = message, Detalle = message.Headers.Subject, Remitente = message.Headers.From.DisplayName, MessageId = message.Headers.MessageId, Fecha = message.Headers.DateSent, Para = para, Texto_Mensaje = valida, Prioridad = Convert.ToString(message.Headers.Importance), From = Convert.ToString(message.Headers.From), CC = CC, } ); foreach (var item in Datasource) { List <MessagePart> attachment = item.Correo.FindAllAttachments(); //List<Adjunto> DatasourceAdjunto = new List<Adjunto>(); //foreach (MessagePart item2 in attachment) //{ // DatasourceAdjunto.Add(new Adjunto() { Nombre = item2.FileName, Adjunto_ = item2 }); //} mail_Mensaje_Info info = new mail_Mensaje_Info(); info.Fecha = item.Fecha; info.Para = item.Para; info.Asunto = item.Detalle; info.Asunto_texto_mostrado = item.Detalle; info.Tiene_Adjunto = attachment.Count() == 0 ? false : true; // info.Tiene_Adjunto = Convert.ToBoolean(0); //validar false if (item.Prioridad == "Normal") { info.Prioridad = 0; } if (item.Prioridad == "Alta") { info.Prioridad = 1; } if (item.Prioridad == "Baja") { info.Prioridad = -1; } //info.Prioridad = 0; //validar info.Leido = false; //*Convert.ToBoolean(0); info.Respondido = false; //Convert.ToBoolean(0); info.No_Leido = false; //Convert.ToBoolean(0); info.Texto_mensaje = item.Texto_Mensaje; info.mail_remitente = item.From; info.Para_CC = item.CC; info.Eliminado = false; //Convert.ToBoolean(0); info.IdTipo_Mensaje = eTipoMail.Buzon_Ent; info.codMensajeId = item.MessageId; // info.InfoContribuyente= null; info.InfoContribuyente.Mail = item.From; listaMail.Add(info); } // gridControl1.DataSource = Datasource; // gridControl1.DataSource = listaMail; } } gridControl_Buzon_Ent.DataSource = listaMail; } catch (Exception ex) { MessageBox.Show(ex.ToString() + IdMsg_Error); } }
void cargar_Correo_Entrada() { try { try { string mensajError = ""; mail_Cuentas_Correo_Bus bus_correo = new mail_Cuentas_Correo_Bus(); List <mail_Cuentas_Correo_Info> lista_Correo = new List <mail_Cuentas_Correo_Info>(); lista_Correo = bus_correo.consultar(ref mensajError); var itemCuenta = lista_Correo.FirstOrDefault(q => q.direccion_correo == correo); IdCuenta = itemCuenta.IdCuenta; Pop3Client pop3Client; pop3Client = new Pop3Client(); pop3Client.Connect(itemCuenta.ServidorCorreoEntrante, itemCuenta.port_entrada, true); pop3Client.Authenticate(itemCuenta.direccion_correo, itemCuenta.Password); int count = pop3Client.GetMessageCount(); // int counter = 0; for (int i = count; i >= 1; i -= 1) { string MessageId = pop3Client.GetMessageHeaders(i).MessageId; if (Bus_Mensaje.Verifica_codMensajeId(MessageId) == false) { var itemIdMensaje = listaMensajes.FirstOrDefault(q => q.codMensajeId == MessageId); if (itemIdMensaje == null) { OpenPop.Mime.Message message = pop3Client.GetMessage(i); //Para listPara = new List <string>(); foreach (var item in message.Headers.To.ToList()) { listPara.Add(item.Address); } //con copia list_concopia = new List <string>(); foreach (var item in message.Headers.Cc.ToList()) { list_concopia.Add(item.Address); } //texto mensaje selectedMessagePart = message.FindFirstPlainTextVersion(); if (selectedMessagePart != null) { if (selectedMessagePart.IsText) { valida = selectedMessagePart.GetBodyAsText(); } } Email email = new Email() { MessageNumber = i, Subject = message.Headers.Subject, DateSent = message.Headers.DateSent, Prioridad = Convert.ToString(message.Headers.Importance), // From = string.Format("<a href = 'mailto:{1}'>{0}</a>", message.Headers.From.DisplayName, message.Headers.From.Address), // From = message.Headers.From.DisplayName, MessageId = message.Headers.MessageId, Para = para, Texto_mensaje = valida, CC = CC, To = listPara, conCopia = list_concopia }; List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { email.Attachments.Add(new Attachment { FileName = attachment.FileName, ContentType = attachment.ContentType.MediaType, Content = attachment.Body }); } listaMail.Add(email); } } } if (listaMail.Count() == 0) { MessageBox.Show("No existen Correos de Entrada Nuevos"); return; } // gridControl2.DataSource = listaMail1; } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
public static string get_comment(Message message) { string commentText = null; MessagePart comment = message.FindFirstPlainTextVersion(); if (comment != null) { commentText = comment.GetBodyAsText(); if (string.IsNullOrEmpty(commentText)) { comment = message.FindFirstHtmlVersion(); if (comment != null) { commentText = comment.GetBodyAsText(); } } } if (string.IsNullOrEmpty(commentText)) { commentText = "NO PLAIN TEXT MESSAGE BODY FOUND"; } return commentText; }
public override ActionResult Execute(ISpecialExecutionTaskTestAction testAction) { String host = testAction.GetParameterAsInputValue("host", false).Value; if (string.IsNullOrEmpty(host)) { throw new ArgumentException(string.Format("Es muss ein POP3 Host angegeben sein.")); } String strPort = testAction.GetParameterAsInputValue("port", false).Value; if (string.IsNullOrEmpty(strPort)) { throw new ArgumentException(string.Format("Es muss ein POP3 Port angegeben sein.")); } int port = int.Parse(strPort); String user = testAction.GetParameterAsInputValue("user", false).Value; if (string.IsNullOrEmpty(user)) { throw new ArgumentException(string.Format("Es muss ein User angegeben werden.")); } String password = testAction.GetParameterAsInputValue("password", false).Value; if (string.IsNullOrEmpty(password)) { throw new ArgumentException(string.Format("Es muss ein Passwort angegeben werden.")); } string expectedSubject = testAction.GetParameterAsInputValue("expectedSubject", false).Value; string expectedBody = testAction.GetParameterAsInputValue("expectedBody", false).Value; pop3Client = new Pop3Client(); messages = new Dictionary <int, Message>(); logMessages = ""; int success = 0; string body = ""; string subject = ""; try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(host, port, false); pop3Client.Authenticate(user, password); int count = pop3Client.GetMessageCount(); if (count > 1) { return(new NotFoundFailedActionResult("Command failed: There is more than one email for this user. Clear mailbox before testing!")); } if (count == 0) { return(new NotFoundFailedActionResult("Command failed: There is no email waiting for this user!")); } messages.Clear(); int fail = 0; for (int i = count; i >= 1; i -= 1) { try { // Application.DoEvents(); Message message = pop3Client.GetMessage(i); MessageHeader headers = pop3Client.GetMessageHeaders(i); subject = headers.Subject; logMessages = logMessages + "- " + i + " -" + subject + "\n"; MessagePart plainTextPart = message.FindFirstPlainTextVersion(); if (plainTextPart != null) { // The message had a text/plain version - show that one body = plainTextPart.GetBodyAsText(); } else { // Try to find a body to show in some of the other text versions List <MessagePart> textVersions = message.FindAllTextVersions(); if (textVersions.Count >= 1) { body = textVersions[0].GetBodyAsText(); } else { body = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>"; } } // Build up the attachment list List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { } // Add the message to the dictionary from the messageNumber to the Message messages.Add(i, message); success++; } catch (Exception e) { fail++; } } } catch (InvalidLoginException e) { return(new VerifyFailedActionResult("Expected user mailbox: " + user + " with password: "******"The server could not be found" + e.Message)); } catch (PopServerLockedException e) { return(new UnknownFailedActionResult("The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?" + e.Message)); } catch (LoginDelayException e) { return(new UnknownFailedActionResult("Login not allowed. Server enforces delay between logins. Have you connected recently?" + e.Message)); } catch (Exception e) { return(new UnknownFailedActionResult("Error occurred retrieving mail: " + e.Message)); } finally { pop3Client.Disconnect(); } if (body.Contains(expectedBody) && (subject.Contains(expectedSubject))) { return(new VerifyPassedActionResult("Subject:" + expectedSubject + "\n\rBody:" + expectedBody, "Subject: " + subject + "\n\nBody: " + body)); } else { string resultMessage = ""; if (body.Contains(expectedBody)) { resultMessage = "Body is correct."; } else { resultMessage = "Body is not correct."; } if (subject.Contains(expectedSubject)) { resultMessage = resultMessage + " Subject is correct."; } else { resultMessage = resultMessage + " Subject is not correct."; } return(new VerifyFailedActionResult(resultMessage + "\n\r" + "Subject:" + expectedSubject + "\n\rBody:" + expectedBody, "\n\rSubject:\n\r" + subject + "\n\rBody:" + body)); } }
public void ReadMail() { try { Pop3Client pop3Client; pop3Client = new Pop3Client(); pop3Client.Connect(emailaccount.POP3, Convert.ToInt32(emailaccount.POP3port), emailaccount.IsSecured); pop3Client.Authenticate(emailaccount.emailid, emailaccount.password); // int MessageNum; int count = pop3Client.GetMessageCount(); var Emails = new List <POPEmail>(); int counter = 0; for (int i = count; i >= 1; i--) { OpenPop.Mime.Message message = pop3Client.GetMessage(i); POPEmail email = new POPEmail() { // MessageNumber = i, MessageNumber = message.Headers.MessageId, // message.Headers.Received. //MessageNum=MessageNumber, Subject = message.Headers.Subject, DateSent = message.Headers.DateSent, From = message.Headers.From.Address, //From = string.Format("<a href = 'mailto:{1}'>{0}</a>", message.Headers.From.DisplayName, message.Headers.From.Address), }; MessagePart body = message.FindFirstHtmlVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } else { body = message.FindFirstPlainTextVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } } List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { email.Attachments.Add(new Attachment { FileName = attachment.FileName, ContentType = attachment.ContentType.MediaType, Content = attachment.Body }); } InsertEmailMessages(email.MessageNumber, email.Subject, email.DateSent, email.From, email.Body); Emails.Add(email); counter++; //if (counter > 2) //{ // break; //} } var emails = Emails; } catch (Exception ex) { // continue; throw ex; } }
public List <messageBody> ReceiveMails() { int count = 0; MailInboxDO miDo = new MailInboxDO(); MailInboxModel messageModel = new MailInboxModel(); connectAndRetrieveButton.Enabled = false; uidlButton.Enabled = false; progressBar.Value = 0; int success = 0; try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(MailServer, 110, false); pop3Client.Authenticate(EmailUsername, EmailPassword); count = pop3Client.GetMessageCount(); int fail = 0; List <MessageUID> listcountUid = new List <MessageUID>(); List <string> lmsUid = pop3Client.GetMessageUids(); //اگر ایمیل دریافتی از قبل خوانده نشده بود و Delivery //نبود وارد لیست ایمیل ها نشود for (int i = lmsUid.Count - 1; i >= 0; i--) { if (!IsExist(lmsUid[i])) { Message msg = pop3Client.GetMessage(i + 1); if (msg.Headers.From.Address != "*****@*****.**" && !Ifmorethan9(msg)) { // pop3Client.GetMessageHeaders(i).Sender.Address != "*****@*****.**") MessageUID messageUid = new MessageUID(); messageUid.Index = i + 1; messageUid.UID = lmsUid[i]; listcountUid.Add(messageUid); } else { try { MailInboxModel messageModel1 = new MailInboxModel(); messageModel.MessageHeader = msg.Headers.Subject; messageModel.MessageBody = ""; messageModel1.MessageUID = lmsUid[i]; messageModel1.receiveDate = msg.Headers.DateSent.ToShortDateString(); messageModel1.receiveTime = msg.Headers.DateSent.ToShortTimeString(); messageModel1.SenderMail = msg.Headers.From.Address; messageModel1.Read = false; miDo.Insert(messageModel1, true); } catch (Exception ex) { LogRegister("ReceiveMails_DatabaseInsert", ex.Message); } } } } foreach (MessageUID msgUID in listcountUid) { if (IsDisposed) { return(null); } Application.DoEvents(); try { string msUid = pop3Client.GetMessageUid(msgUID.Index); Message message = pop3Client.GetMessage(msgUID.Index); if (!messages.ContainsKey(msgUID.Index)) { messages.Add(msgUID.Index, message); } MessagePart msgpart = message.FindFirstPlainTextVersion(); short trans; string AcountNumber; string[] messageBody; if (msgpart != null) { messageBody = msgpart.GetBodyAsText().Split(':'); } else { messageBody = new string[1]; } try { AcountNumber = messageBody[0]; trans = short.Parse(messageBody[1].Trim()); //اگر این شماره حساب در این روز کمتر از 10 بار درخواست داده می تواند مجدد درخواست دهد List <MailInboxModel> mailInboxmodelList = new List <MailInboxModel>(); MailInboxDO mailInboxdo = new MailInboxDO(); mailInboxmodelList = mailInboxdo.Search(new MailInboxModel { receiveDate = message.Headers.DateSent.ToShortDateString() }); int countInaDay = 0; foreach (MailInboxModel tmpMail in mailInboxmodelList) { if (tmpMail.MessageBody != null && tmpMail.MessageBody.Contains(AcountNumber)) { countInaDay++; } } if (countInaDay <= 9) { while (true) { if (!EmailReciveCheckerISbusy && !EmailAddCheckerISbusy) { EmailAddCheckerISbusy = true; messageBodyList.Add(new messageBody(trans, AcountNumber, message.Headers.From.ToString())); EmailAddCheckerISbusy = false; break; } } } else if (countInaDay <= 12) { while (true) { if (!EmailReciveCheckerISbusy && !EmailAddCheckerISbusy) { EmailAddCheckerISbusy = true; messageBodyList.Add(new messageBody(trans, AcountNumber, message.Headers.From.ToString(), true)); EmailAddCheckerISbusy = false; break; } } } } catch (IndexOutOfRangeException exp) { while (true) { if (!EmailReciveCheckerISbusy) { EmailAddCheckerISbusy = true; if (!message.Headers.From.ToString().Contains("*****@*****.**")) { messageBodyList.Add(new messageBody(0, "0", message.Headers.From.ToString())); } EmailAddCheckerISbusy = false; break; } } } catch (Exception ex) { while (true) { if (!EmailReciveCheckerISbusy) { EmailAddCheckerISbusy = true; if (!message.Headers.From.ToString().Contains("*****@*****.**")) { messageBodyList.Add(new messageBody(0, "0", message.Headers.From.ToString())); } EmailAddCheckerISbusy = false; break; } } } try { messageModel = new MailInboxModel(); messageModel.MessageHeader = message.Headers.Subject; if (msgpart != null) { messageModel.MessageBody = msgpart.GetBodyAsText().Replace("\r\n", string.Empty); } else { messageModel.MessageBody = "ERROR TO read Body"; } messageModel.MessageUID = msUid; messageModel.receiveDate = message.Headers.DateSent.ToShortDateString(); messageModel.receiveTime = message.Headers.DateSent.ToShortTimeString(); messageModel.SenderMail = message.Headers.From.Address; messageModel.Read = false; miDo.Insert(messageModel, true); } catch (Exception ex) { LogRegister("ReceiveMails_DatabaseInsert", ex.Message); } } catch (Exception e) { LogRegister("ReceiveMails", e.Message + "\r\n" + "Stack trace:\r\n" + e.StackTrace); } } } //catch (InvalidLoginException) //{ // //MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication"); //} //catch (PopServerNotFoundException) //{ // //MessageBox.Show(this, "The server could not be found", "POP3 Retrieval"); //} //catch (PopServerLockedException) //{ // // MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked"); //} //catch (LoginDelayException) //{ // //MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay"); //} catch (Exception e) { LogRegister("ReceiveMails", e.Message); //MessageBox.Show(this, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval"); } finally { Isbusy = false; } return(messageBodyList); }
private void updateData() { suara[0] = 0; suara[1] = 0; suara[2] = 0; suara[3] = 0; suara[4] = 0; lblCalon[0] = lblCalon1; //lblCalon[1] = lblCalon2; lblCalon[2] = lblCalon3; //lblCalon[3] = lblCalon4; lblCalon[4] = lblCalon5; try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect("pop.gmail.com", 995, true); pop3Client.Authenticate("*****@*****.**", passEMAIL); int count = pop3Client.GetMessageCount(); progressBar1.Maximum = count; int success = 0; int fail = 0; for (int i = count; i >= 1; i -= 1) { // Check if the form is closed while we are working. If so, abort if (IsDisposed) { return; } // Refresh the form while fetching emails // This will fix the "Application is not responding" problem Application.DoEvents(); try { Message message = pop3Client.GetMessage(i); String pesan; if (message.MessagePart.IsText) { pesan = message.MessagePart.GetBodyAsText(); } else { MessagePart plainTextPart = message.FindFirstPlainTextVersion(); if (plainTextPart != null) { pesan = plainTextPart.GetBodyAsText(); } else { // Try to find a body to show in some of the other text versions List <MessagePart> textVersions = message.FindAllTextVersions(); if (textVersions.Count >= 1) { pesan = textVersions[0].GetBodyAsText(); } else { pesan = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>"; } } } if (message.Headers.Subject == "2SUARA KAHIM") { //MessageBox.Show("IBM"); String[] komponen = pesan.Split('|'); if (komponen.Count() == 4) { if (komponen[0] == "COMBODUO") { if (!kupon.Contains(komponen[2])) { int pilihan = 0; if (Int32.TryParse(komponen[3], out pilihan)) { kupon.Add(komponen[2]); textBox1.AppendText(komponen[2] + " " + komponen[3] + "\n"); suara[pilihan - 1] += 1; lblCalon[pilihan - 1].Text = suara[pilihan - 1].ToString(); chart1.Series.Clear(); chart1.Series.Add(""); chart1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Pie; chart1.Series[0].Points.Add(0); chart1.Series[0].Points.Add(0); chart1.Series[0].Points.Add(0); //chart1.Series[0].Points.Add(0); //chart1.Series[0].Points.Add(0); chart1.Series[0].Points[0].IsValueShownAsLabel = true; chart1.Series[0].Points[0].Label = "Joshua Belzalel A"; chart1.Series[0].Points[0].SetValueY(suara[0]); //chart1.Series[0].Points[1].IsValueShownAsLabel = true; //chart1.Series[0].Points[1].Label = "Farid Fadhil H"; //chart1.Series[0].Points[1].SetValueY(suara[1]); chart1.Series[0].Points[1].IsValueShownAsLabel = true; chart1.Series[0].Points[1].Label = "Aryya Dwisatya W"; chart1.Series[0].Points[1].SetValueY(suara[2]); //chart1.Series[0].Points[3].IsValueShownAsLabel = true; //chart1.Series[0].Points[3].Label = "Vidia Anindhita"; //chart1.Series[0].Points[3].SetValueY( suara[3] ); chart1.Series[0].Points[2].IsValueShownAsLabel = true; chart1.Series[0].Points[2].Label = "Abstain"; chart1.Series[0].Points[2].SetValueY(suara[4]); progressBar1.Value++; } } } } } //MessageBox.Show(message.Headers.Subject + "\n\n" + pesan); success++; } catch (Exception ex) { MessageBox.Show(ex.Message); DefaultLogger.Log.LogError( "TestForm: Message fetching failed: " + ex.Message + "\r\n" + "Stack trace:\r\n" + ex.StackTrace); fail++; } //progressBar.Value = (int)(((double)(count - i) / count) * 100); } //MessageBox.Show(this, "Mail received!\nSuccesses: " + success + "\nFailed: " + fail, "Message fetching done"); if (fail > 0) { //MessageBox.Show(this, ""); } } catch (InvalidLoginException) { MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication"); } catch (PopServerNotFoundException) { MessageBox.Show(this, "The server could not be found", "POP3 Retrieval"); } catch (PopServerLockedException) { MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked"); } catch (LoginDelayException) { MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay"); } catch (Exception ex) { MessageBox.Show(this, "Error occurred retrieving mail. " + ex.Message, "POP3 Retrieval"); } progressBar1.Value = progressBar1.Maximum; MessageBox.Show("Selesai, selamat untuk yang menang :)", "", MessageBoxButtons.OK, MessageBoxIcon.Information); }
/// <summary> /// Метод открытия сохраненного смс и проверка цифровой подписи. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void tbstOpen_Click(object sender, EventArgs e) { cspp.KeyContainerName = keyName; rsa = new RSACryptoServiceProvider(cspp); rsa.PersistKeyInCsp = true; // Выбираю смс для просмотра. OpenFileDialog openFile = new OpenFileDialog(); openFile.RestoreDirectory = true; openFile.InitialDirectory = "Messages"; openFile.Title = "Выберите письмо для просмотра."; if (openFile.ShowDialog() == DialogResult.OK) { tbstSave.Visible = false; tbstDelete.Visible = false; listMessages.SendToBack(); string fileName = openFile.FileName; // Проверка цифровой подписи. using (FileStream inFs = new FileStream(fileName, FileMode.Open)) { byte[] LenSign = new byte[4]; inFs.Read(LenSign, 0, 4); int lenSign = BitConverter.ToInt32(LenSign, 0); int startData = lenSign + 4; int lenData = (int)inFs.Length - startData; byte[] sign = new byte[lenSign]; byte[] data = new byte[lenData]; inFs.Read(sign, 0, lenSign); inFs.Read(data, 0, lenData); if (rsa.VerifyData(data, new SHA1CryptoServiceProvider(), sign)) { Message message = new Message(data); StringBuilder tmp = new StringBuilder(); foreach (RfcMailAddress a in message.Headers.To) { tmp.Append(a.ToString() + " "); } tbFrom.Text = message.Headers.From.ToString(); tbTo.Text = tmp.ToString(); tbSubject.Text = message.Headers.Subject.ToString(); MessagePart plainTextPart = message.FindFirstPlainTextVersion(); if (plainTextPart != null) { mailViewer.DocumentText = plainTextPart.GetBodyAsText().TrimEnd('\r', '\n'); } else { List <MessagePart> textVersions = message.FindAllTextVersions(); if (textVersions.Count >= 1) { mailViewer.DocumentText = textVersions[0].GetBodyAsText().TrimEnd('\r', '\n'); } else { mailViewer.DocumentText = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>"; } } } else { MessageBox.Show("Ошибка проверки подписи файла письма!", "Ошибка"); } } } }
private void dataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { OpenPop.Mime.Message msg = pop3Client.GetMessage(count - dataGridView.CurrentCell.RowIndex); OpenPop.Mime.MessagePart msgpart = msg.FindFirstPlainTextVersion(); MessageBox.Show("From: " + msg.Headers.From + "\nSubject: " + msg.Headers.Subject + "\nMessage: " + msg.MessagePart.BodyEncoding.GetString(msgpart.Body), "Message", MessageBoxButtons.OK); }
private void ListMessagesMessageSelected(object sender, TreeViewEventArgs e) { Message message = messages[GetMessageNumberFromSelectedNode(listMessages.SelectedNode)]; if (listMessages.SelectedNode.Tag is MessagePart) { MessagePart selectedMessagePart = (MessagePart)listMessages.SelectedNode.Tag; if (selectedMessagePart.IsText) { messageTextBox.Text = selectedMessagePart.GetBodyAsText(); } else { messageTextBox.Text = "This part of the email is not text"; } } else { MessagePart plainTextPart = message.FindFirstPlainTextVersion(); if (plainTextPart != null) { messageTextBox.Text = plainTextPart.GetBodyAsText(); } listAttachments.Nodes.Clear(); List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { TreeNode addedNode = listAttachments.Nodes.Add((attachment.FileName)); addedNode.Tag = attachment; } DataSet dataSet = new DataSet(); DataTable table = dataSet.Tables.Add("Headers"); table.Columns.Add("Header"); table.Columns.Add("Value"); DataRowCollection rows = table.Rows; foreach (RfcMailAddress cc in message.Headers.Cc) { rows.Add(new object[] { "Cc", cc }); } foreach (RfcMailAddress bcc in message.Headers.Bcc) { rows.Add(new object[] { "Bcc", bcc }); } foreach (RfcMailAddress to in message.Headers.To) { rows.Add(new object[] { "To", to }); } rows.Add(new object[] { "From", message.Headers.From }); rows.Add(new object[] { "Reply-To", message.Headers.ReplyTo }); rows.Add(new object[] { "Date", message.Headers.Date }); rows.Add(new object[] { "Subject", message.Headers.Subject }); gridHeaders.DataMember = table.TableName; gridHeaders.DataSource = dataSet; } }
private void Tasking_Click(object sender, EventArgs e) { SqlConnection connection; int messageNumber = GetMessageNumberFromSelectedNode(listMessages.SelectedNode); Message message = messages[messageNumber]; MessagePart plainTextPart = message.FindFirstPlainTextVersion(); String connetionString = GetConnectionString(); connection = new SqlConnection(connetionString); int maxId = 0; //reader try { //open connection connection.Open(); //command1 String sqlGetMaxId = "select MAX(Id) from Emails"; SqlCommand command1 = new SqlCommand(sqlGetMaxId, connection); using (SqlDataReader rdr = command1.ExecuteReader()) { while (rdr.Read()) { if (!rdr.IsDBNull(0)) { maxId = rdr.GetInt32(0); } } } command1.Dispose(); //command2 String sqlInsertEmail = "Insert into Emails(EmailSubject, Body, EmailFrom, EmailReplyTo, EmailDate) Values('" + message.Headers.Subject + "','" + plainTextPart.GetBodyAsText() + "','" + message.Headers.From + "','" + message.Headers.ReplyTo + "','" + message.Headers.Date + "')"; SqlCommand command2 = new SqlCommand(sqlInsertEmail, connection); command2.ExecuteNonQuery(); command2.Dispose(); //command3 List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { String sqlInsertAttachment = "Insert into Attachments(EmailId, AttachmentName) Values('" + (maxId + 1) + "','" + attachment.FileName + "')"; SqlCommand command3 = new SqlCommand(sqlInsertAttachment, connection); command3.ExecuteNonQuery(); command3.Dispose(); } //close connection connection.Close(); if (listMessages.SelectedNode != null) { listMessages.SelectedNode.BackColor = Color.Yellow; } } catch (Exception ex) { MessageBox.Show("Error while saving data to DB! "); } }
private static void SaveMail(int i, Message message) { MessagePart plainHtmlPart = message.FindFirstHtmlVersion(); MessagePart plainTextPart = message.FindFirstPlainTextVersion(); string textMail = null; if (plainHtmlPart == null && plainTextPart != null) { textMail = plainTextPart.GetBodyAsText(); } else if (plainHtmlPart == null && plainTextPart == null) { List<MessagePart> textVersions = message.FindAllTextVersions(); if (textVersions.Count >= 1) textMail = textVersions[0].GetBodyAsText(); } else if (plainHtmlPart != null) { textMail = plainHtmlPart.GetBodyAsText(); } string xamlMail = HTMLConverter.HtmlToXamlConverter.ConvertHtmlToXaml(textMail, true); StringReader sr = new StringReader(xamlMail); XmlReader xr = XmlReader.Create(sr); FlowDocument fdMail = (FlowDocument)XamlReader.Load(xr); FlowDocument fd = new FlowDocument(); DateTime dateMail = Convert.ToDateTime(message.Headers.Date); BLL.DiaryBLL dbll = new BLL.DiaryBLL(); fd = dbll.GetDoc(dateMail.Date.ToString()); fd = CommonHelper.MergeFlowDocument(fd, fdMail); dbll.Save(fd, dateMail.Date.ToString()); }
public override ActionResult Execute(ISpecialExecutionTaskTestAction testAction) { String host = testAction.GetParameterAsInputValue("host", false).Value; if (string.IsNullOrEmpty(host)) { throw new ArgumentException(string.Format("Es muss ein POP3 Host angegeben sein.")); } String strPort = testAction.GetParameterAsInputValue("port", false).Value; if (string.IsNullOrEmpty(strPort)) { throw new ArgumentException(string.Format("Es muss ein POP3 Port angegeben sein.")); } int port = int.Parse(strPort); String user = testAction.GetParameterAsInputValue("user", false).Value; if (string.IsNullOrEmpty(user)) { throw new ArgumentException(string.Format("Es muss ein User angegeben werden.")); } String password = testAction.GetParameterAsInputValue("password", false).Value; if (string.IsNullOrEmpty(password)) { throw new ArgumentException(string.Format("Es muss ein Passwort angegeben werden.")); } pop3Client = new Pop3Client(); messages = new Dictionary <int, Message>(); logMessages = ""; int success = 0; try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(host, port, false); pop3Client.Authenticate(user, password); int count = pop3Client.GetMessageCount(); messages.Clear(); int fail = 0; for (int i = count; i >= 1; i -= 1) { try { // Application.DoEvents(); string body; Message message = pop3Client.GetMessage(i); MessageHeader headers = pop3Client.GetMessageHeaders(i); string subject = headers.Subject; logMessages = logMessages + "- " + i + " -" + subject + "\n"; MessagePart plainTextPart = message.FindFirstPlainTextVersion(); if (plainTextPart != null) { // The message had a text/plain version - show that one body = plainTextPart.GetBodyAsText(); } else { // Try to find a body to show in some of the other text versions List <MessagePart> textVersions = message.FindAllTextVersions(); if (textVersions.Count >= 1) { body = textVersions[0].GetBodyAsText(); } else { body = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>"; } } // Build up the attachment list List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { } // Add the message to the dictionary from the messageNumber to the Message messages.Add(i, message); success++; } catch (Exception e) { fail++; } } } catch (InvalidLoginException) { //MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication"); } catch (PopServerNotFoundException) { //MessageBox.Show(this, "The server could not be found", "POP3 Retrieval"); } catch (PopServerLockedException) { //MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked"); } catch (LoginDelayException) { //MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay"); } catch (Exception e) { return(new PassedActionResult("Error occurred retrieving mail: " + e.Message)); } finally { pop3Client.Disconnect(); } return(new PassedActionResult("Mails found: " + success + "\n" + logMessages)); }