public static string MessageToString(Message message) { using (var stream = new MemoryStream()) { message.Save(stream); stream.Position = 0; var reader = new StreamReader(stream); return reader.ReadToEnd(); } }
public void ParsingMediaTypeOctetStream() { const string base64 = "JVBERi0xLjUNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBlL0NhdGFsb2cvUGFnZXMgMiAwIFIv\r\n" + "TGFuZyhkYS1ESykgL1N0cnVjdFRyZWVSb290IDE1IDAgUi9NYXJrSW5mbzw8L01hcmtlZCB0\r\n" + "cnVlPj4+Pg0KZW5kb2JqDQoyIDAgb2JqDQo8PC9UeXBlL1BhZ2VzL0NvdW50IDEvS2lkc1sg\r\n" + "MyAwIFJdID4+DQplbmRvYmoNCjMgMCBvYmoNCjw8L1R5cGUvUGFnZS9QYXJlbnQgMiAwIFIv\r\n" + "UmVzb3VyY2VzPDwvRm9udDw8L0YxIDUgMCBSL0YyIDcgMCBSL0YzIDkgMCBSPj4vUHJvY1Nl\r\n" + "dFsvUERGL1RleHQvSW1hZ2VCL0ltYWdlQy9JbWFnZUldID4+L01lZGlhQm94WyAwIDAgNTk0\r\n" + "Ljk2IDg0Mi4wNF0gL0NvbnRlbnRzIDQgMCBSL0dyb3VwPDwvVHlwZS9Hcm91cC9TL1RyYW5z\r\n" + "cGFyZW5jeS9DUy9EZXZpY2VSR0I+Pi9UYWJzL1MvU3RydWN0UGFyZW50cyAwPj4NCmVuZG9i"; const string partPDF = "Content-Type: application/pdf;\r\n" + " name=\"=?ISO-8859-1?Q?=D8nskeliste=2Epdf?=\"\r\n" + "Content-Transfer-Encoding: base64\r\n" + "\r\n" + base64; // Base 64 is only in ASCII Message message = new Message(Encoding.ASCII.GetBytes(partPDF)); MessagePart messagePart = message.MessagePart; // Check the headers Assert.AreEqual("application/pdf", messagePart.ContentType.MediaType); Assert.AreEqual(ContentTransferEncoding.Base64, messagePart.ContentTransferEncoding); Assert.AreEqual("Ønskeliste.pdf", messagePart.ContentType.Name); // This will fail if US-ASCII is assumed on the bytes when decoded from base64 to bytes Assert.AreEqual(Convert.FromBase64String(base64), messagePart.Body); }
private string FindPlainTextInMessage(Message message) { OpenPop.Mime.Header.MessageHeader msgheader = message.Headers; string sender = msgheader.From.Address; string LinkExtracted = ""; if (sender == cSender) { List<MessagePart> list = message.FindAllTextVersions(); string str = ""; foreach (MessagePart part in list) { if (part != null) { try { //string pattern = @"http://www.gutefrage.net/registrierungsbestaetigung.*(?=\042)"; linkpattern //part.Save(new FileInfo("temp")); //string str2 = File.ReadAllText("temp"); string str2 = part.GetBodyAsText(); int startIndex = 0; int num2 = 0; startIndex = str2.IndexOf(linkpattern, startIndex); while (startIndex != -1) { startIndex = startIndex + ShiftBy; char[] anyOf = new char[] { ' ', '"', '>', '<', '\r', '\n', '\\', ')' }; num2 = str2.IndexOfAny(anyOf, startIndex); string str3 = str2.Substring(startIndex, num2 - startIndex); if (str == str3) { startIndex = str2.IndexOf(linkpattern, num2); } else { // File.AppendAllText("links.txt", str3 + "\r\n"); LinkExtracted = str3; str = str3; startIndex = str2.IndexOf(linkpattern, num2); } } return LinkExtracted; } catch (Exception) { // Console.WriteLine("Pizdets!"); return null; } } } } if (LinkExtracted != "") { return LinkExtracted; } else { return null; } }
/// <summary> /// Example showing: /// - how to find a html version in a Message /// - how to save MessageParts to file /// </summary> /// <param name="message">The message to examine for html</param> public static void FindHtmlInMessage(Message message) { MessagePart html = message.FindFirstHtmlVersion(); if (html != null) { // Save the plain text to a file, database or anything you like html.Save(new FileInfo("html.txt")); } }
public void TestContentDisposition() { const string messagePartContent = "Content-Disposition: attachment\r\n" + "\r\n"; // End of message headers MessagePart messagePart = new Message(Encoding.ASCII.GetBytes(messagePartContent)).MessagePart; Assert.IsFalse(messagePart.ContentDisposition.Inline); }
public void Setup() { _stubEmailSubject = "Stub Email Subject"; _stubEmailBody = "Stub Email Body"; _stubEmail = MessageGenerator.GenerateMessage(_stubEmailSubject, _stubEmailBody); _translator = new MessageTranslator(); }
public void TestIsAttachmentApplicationPdf() { const string messagePartContent = "Content-Type: application/pdf\r\n" + "\r\n"; // End of message headers MessagePart messagePart = new Message(Encoding.ASCII.GetBytes(messagePartContent)).MessagePart; Assert.IsTrue(messagePart.IsAttachment); }
public void TestContentTypeWithMissingSemicolonAndTabs() { const string messagePartContent = "Content-Type: text/plain;\r\n\tcharset=\"Windows-1252\"\r\n\tname=\"ALERTA_1.txt\"\r\n" + "\r\n"; // End of message headers MessagePart messagePart = new Message(Encoding.ASCII.GetBytes(messagePartContent)).MessagePart; Assert.AreEqual(Encoding.GetEncoding(1252), messagePart.BodyEncoding); }
public void TestIsTextMessageRfc822() { const string messagePartContent = "Content-Type: message/rfc822\r\n" + "\r\n"; // End of message headers MessagePart messagePart = new Message(Encoding.ASCII.GetBytes(messagePartContent)).MessagePart; Assert.IsTrue(messagePart.IsText); }
public void TestIsTextTextPlain() { const string messagePartContent = "Content-Type: text/plain\r\n" + "\r\n"; // End of message headers MessagePart messagePart = new Message(Encoding.ASCII.GetBytes(messagePartContent)).MessagePart; Assert.IsTrue(messagePart.IsText); }
public void TestContentDescriptionTwo() { const string messagePartContent = "Content-Description: This is some OTHER human readable text\r\n" + "\r\n"; // End of message headers MessagePart messagePart = new Message(Encoding.ASCII.GetBytes(messagePartContent)).MessagePart; const string expectedDescription = "This is some OTHER human readable text"; string actualDescription = messagePart.ContentDescription; Assert.AreEqual(expectedDescription, actualDescription); }
public void TestContentTypeCharsetWithLargeFirstChar() { const string messagePartContent = "Content-Type: TEXT/PLAIN; Charset=\"US-ASCII\"\r\n" + "\r\n" + // End of message headers "foo"; MessagePart messagePart = new Message(Encoding.ASCII.GetBytes(messagePartContent)).MessagePart; Assert.AreEqual(Encoding.ASCII, messagePart.BodyEncoding); Assert.AreEqual("foo", messagePart.GetBodyAsText()); }
public static string get_subject(Message message) { string subject = message.Headers.Subject; if (string.IsNullOrWhiteSpace(subject)) { subject = "[No Subject]"; } return subject; }
public void ParseContentDispositionFilenameWithEncoding() { const string messageHeaders = "Content-Disposition: attachment;\r\n" + " filename*=ISO-8859-1\'\'%D8%6E%73%6B%65%6C%69%73%74%65%2E%70%64%66\r\n" + "\r\n"; MessageHeader headers = new Message(Encoding.ASCII.GetBytes(messageHeaders), false).Headers; // Tests that the ContentDisposition header correctly decoded the filename Assert.NotNull(headers.ContentDisposition.FileName); Assert.AreEqual("Ønskeliste.pdf", headers.ContentDisposition.FileName); }
public void TestLineEndingsNotStrippedAwayAtStart() { const string input = "Content-Type: text/plain; charset=iso-8859-1\r\n" + "Content-Transfer-Encoding: 7bit\r\n" + "\r\n" + // Headers end "\r\nHello"; // This is where the first \r\n should not be removed const string expectedOutput = "\r\nHello"; string output = new Message(Encoding.ASCII.GetBytes(input)).MessagePart.GetBodyAsText(); Assert.AreEqual(expectedOutput, output); }
public void TestLineEndingsNotStrippedAwayAtEndUsingQuotedPrintable() { const string input = "Content-Type: text/plain; charset=iso-8859-1\r\n" + "Content-Transfer-Encoding: quoted-printable\r\n" + "\r\n" + // Headers end "Hello=\r\n"; // This is where the last \r\n should not be removed // The QP encoding would have decoded Hello=\r\n into Hello, since =\r\n is a soft line break const string expectedOutput = "Hello"; string output = new Message(Encoding.ASCII.GetBytes(input)).MessagePart.GetBodyAsText(); Assert.AreEqual(expectedOutput, output); }
public void TestAllFirstMessagesWithMediaTypeSimpleNotFound() { const string rfcExample = "Content-type: text/plain; charset=us-ascii\r\n" + "\r\n" + "This is explicitly typed plain US-ASCII text"; Message message = new Message(Encoding.ASCII.GetBytes(rfcExample)); System.Collections.Generic.List<MessagePart> parts = message.FindAllMessagePartsWithMediaType("text/html"); // We should not be able to find such a MessagePart Assert.NotNull(parts); Assert.IsEmpty(parts); }
public void TestISO88599CharacterSet() { const string Iso88599SpecialChars = "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"; const string input = "Content-Type: text/plain; charset=iso-8859-9\r\n" + "Content-Transfer-Encoding: 7bit\r\n" + "\r\n" + // Headers end Iso88599SpecialChars; const string expectedOutput = Iso88599SpecialChars; string output = new Message(Encoding.GetEncoding("ISO-8859-9").GetBytes(input)).MessagePart.GetBodyAsText(); Assert.AreEqual(expectedOutput, output); }
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; }
//-------------------------------------------------------------------> // http://hpop.sourceforge.net/ protected void Recieve_Email_Click_Only_Pop_abv(object sender, EventArgs e) { // Disable buttons while working //connectAndRetrieveButton.Enabled = false; //uidlButton.Enabled = false; //progressBar.Value = 0; Pop3Client pop3Client = new Pop3Client(); try { //if (pop3Client.Connected) // pop3Client.Disconnect(); //pop3Client.Connect(popServerTextBox.Text, int.Parse(portTextBox.Text), useSslCheckBox.Checked); pop3Client.Connect("pop3.abv.bg", 995, true); //pop3Client.Authenticate(loginTextBox.Text, passwordTextBox.Text); pop3Client.Authenticate("*****@*****.**", "test.stanev2801"); int count = pop3Client.GetMessageCount(); //totalMessagesTextBox.Text = count.ToString(); //messageTextBox.Text = ""; //messages.Clear(); //listMessages.Nodes.Clear(); //listAttachments.Nodes.Clear(); DataTable dt = InitializeDataTable(); int success = 0; int fail = 0; int countNum = 1; 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 { OpenPop.Mime.Message message = pop3Client.GetMessage(i); string strBody = String.Empty; if ((message.MessagePart.Body != null)) { strBody = System.Text.Encoding.UTF8.GetString(message.MessagePart.Body); } dt.Rows.Add(new object[] { countNum, message.Headers.DateSent.ToString(), message.Headers.From.Address, message.Headers.Subject, message.Headers.From.DisplayName, strBody }); dataGrid.DataSource = dt; dataGrid.DataBind(); // Add the message to the dictionary from the messageNumber to the Message // messages.Add(i, message); // Create a TreeNode tree that mimics the Message hierarchy // TreeNode node = new TreeNodeBuilder().VisitMessage(message); // Set the Tag property to the messageNumber // We can use this to find the Message again later // node.Tag = i; // Show the built node in our list of messages // listMessages.Nodes.Add(node); success++; } catch (Exception ex) { 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, // "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) { return; //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 //{ // // Enable the buttons again // connectAndRetrieveButton.Enabled = true; // uidlButton.Enabled = true; // progressBar.Value = 100; //} }
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 static string get_cc(Message message) { string cc = string.Join("; ", message.Headers.Cc.Select(c => c.Address)); return cc; }
public static string get_from_addr(Message message) { return message.Headers.From.Address; }
//List Messages on click private void listMessages_AfterSelect(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 }); } } } }
/// <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("Ошибка проверки подписи файла письма!", "Ошибка"); } } } }
/// <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; } }
}//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
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; } }
private void SendButton_Click(object sender, EventArgs e) { SendMessage(); headlin.Clear(); Message.Clear(); }
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 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 ReceiveMails() { connectButton.Enabled = false; progressBar.Value = 0; try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(popServerTextBox.Text, int.Parse(portTextBox.Text), useSslCheckBox.Checked); pop3Client.Authenticate(loginTextBox.Text, passwordTextBox.Text, AuthenticationMethod.UsernameAndPassword); int count = pop3Client.GetMessageCount(); totalMessagesTextBox.Text = count.ToString(); messageTextBox.Text = ""; messages.Clear(); listMessages.Nodes.Clear(); listAttachments.Nodes.Clear(); int s = 0; int f = 0; for (int i = count; i >= 1; i -= 1) { Application.DoEvents(); try { Message message = pop3Client.GetMessage(i); messages.Add(i, message); TreeNode node = new TreeNodeBuilder().VisitMessage(message); node.Tag = i; listMessages.Nodes.Add(node); s++; } catch (Exception e) { DefaultLogger.Log.LogError( "Retrieving Emails: Message fetching failed: " + e.Message); f++; } progressBar.Value = (int)(((double)(count - 1) / count) * 100); } MessageBox.Show(this, "Mail received! \n Succesfully: " + s + "\nFailed: " + f, "Messages Retrieved."); if (f > 0) { MessageBox.Show("Some messages were not parsed correctly"); } } catch (InvalidLoginException) { MessageBox.Show(this, "The server did not accept the username and password."); } catch (PopServerNotFoundException) { MessageBox.Show(this, "The server couldnt be found"); } catch (PopServerLockedException) { MessageBox.Show(this, "The mailbox is locked and seems to be in use."); } catch (LoginDelayException) { MessageBox.Show(this, "You tried to log in too quickly between two logins."); } catch (Exception e) { MessageBox.Show(this, "Error ocurred retrieveing mail " + e.Message); } finally { connectButton.Enabled = true; 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 NewMail(ManualResetEvent doneevent, Message newMessage) { _doneevent = doneevent; _NewMessage = newMessage; }
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()); } }
//private SaveFileDialog saveFile; private void ReceiveMails() { // Disable buttons while working //connectAndRetrieveButton.Enabled = false; //uidlButton.Enabled = false; //progressBar.Value = 0; try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(Con.Pop, int.Parse(Con.Portpop), true); pop3Client.Authenticate(Con.Mail, Con.password); int count = pop3Client.GetMessageCount(); //totalMessagesTextBox.Text = count.ToString(); //messageTextBox.Text = ""; messages.Clear(); treeView1.Nodes.Clear(); // listAttachments.Nodes.Clear(); 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); // Add the message to the dictionary from the messageNumber to the Message messages.Add(i, message); // Create a TreeNode tree that mimics the Message hierarchy TreeNode node = new OpenPop.TestApplication.TreeNodeBuilder().VisitMessage(message); // Set the Tag property to the messageNumber // We can use this to find the Message again later node.Tag = i; // Show the built node in our list of messages treeView1.Nodes.Add(node); success++; } catch (Exception e) { DefaultLogger.Log.LogError( "TestForm: Message fetching failed: " + e.Message + "\r\n" + "Stack trace:\r\n" + e.StackTrace); fail++; } //progressBar.Value = (int)(((double)(count - i) / count) * 100); } MessageBox.Show(this, "Почта получена!\nУспешно: " + success + "\nПровалено: " + 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) { MessageBox.Show(this, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval"); } }
private void ReceiveMails() { // Disable buttons while working connectAndRetrieveButton.Enabled = false; uidlButton.Enabled = false; progressBar.Value = 0; try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(popServerTextBox.Text, int.Parse(portTextBox.Text), useSslCheckBox.Checked); pop3Client.Authenticate(loginTextBox.Text, passwordTextBox.Text); int count = pop3Client.GetMessageCount(); totalMessagesTextBox.Text = count.ToString(); messageTextBox.Text = ""; messages.Clear(); listMessages.Nodes.Clear(); listAttachments.Nodes.Clear(); 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); // Add the message to the dictionary from the messageNumber to the Message messages.Add(i, message); // Create a TreeNode tree that mimics the Message hierarchy TreeNode node = new TreeNodeBuilder().VisitMessage(message); // Set the Tag property to the messageNumber // We can use this to find the Message again later node.Tag = i; // Show the built node in our list of messages listMessages.Nodes.Add(node); success++; } catch (Exception e) { DefaultLogger.Log.LogError( "TestForm: Message fetching failed: " + e.Message + "\r\n" + "Stack trace:\r\n" + e.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, "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, "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 { // Enable the buttons again connectAndRetrieveButton.Enabled = true; uidlButton.Enabled = true; progressBar.Value = 100; } }
/// <summary> /// Список сообщений. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ListMessagesMessageSelected(object sender, TreeViewEventArgs e) { Message message = messages[GetMessageNumberFromSelectedNode(listMessages.SelectedNode)]; List <MessagePart> att = message.FindAllAttachments(); cbAttachments.Items.Clear(); if (message.FindAllAttachments().Count > 0) { foreach (MessagePart at in att) { cbAttachments.Items.Add(at.FileName); } btDownload.Enabled = true; lbAttachmentsCount.Text = cbAttachments.Items.Count.ToString(); } else { lbAttachmentsCount.Text = "0"; btDownload.Enabled = false; } 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(); if (message.Headers.Subject != null) { tbSubject.Text = message.Headers.Subject.ToString(); } else { tbSubject.Text = "Без темы"; } changeButtonsState(); if (seenUids.Contains(message.Headers.MessageId)) { listMessages.SelectedNode.NodeFont = listMessages.Font; } else { listMessages.SelectedNode.NodeFont = listMessages.Font; seenUids.Add(message.Headers.MessageId); File.AppendAllText("ids", message.Headers.MessageId + "\n"); } if (listMessages.SelectedNode.Tag is MessagePart) { MessagePart selectedMessagePart = (MessagePart)listMessages.SelectedNode.Tag; mailViewer.DocumentText = selectedMessagePart.GetBodyAsText(); } else { MessagePart plainTextPart = message.FindFirstHtmlVersion(); if (plainTextPart != null) { mailViewer.DocumentText = plainTextPart.GetBodyAsText(); } else { List <MessagePart> textVersions = message.FindAllTextVersions(); if (textVersions.Count >= 1) { mailViewer.DocumentText = textVersions[0].GetBodyAsText(); } else { mailViewer.DocumentText = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>"; } } } listMessages.Refresh(); }
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)); } }
private string ReceiveMailsfromPOPServer(string passcode) { try { // Get message Unique ID from the database using the Passcode mapped. //SQL call DataSet ds = FileController.GETMessagesByPassCode(passcode); foreach (DataRow dr in ds.Tables[0].Rows) { if (dr["Active"].ToString().ToUpper() == "FALSE") { return("Invalid Passcode"); } } string messageID = ""; if (ds.Tables[0].Rows.Count > 0) { messageID = ds.Tables[0].Rows[0][1].ToString(); if (messageID != "") { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(ConfigurationManager.AppSettings["Server"], int.Parse(ConfigurationManager.AppSettings["Port"]), Convert.ToBoolean(ConfigurationManager.AppSettings["SSL"])); pop3Client.Authenticate(ConfigurationManager.AppSettings["Login"], ConfigurationManager.AppSettings["Password"]); int count = pop3Client.GetMessageCount(); messages.Clear(); for (int i = count; i >= 1; i -= 1) { try { Message message = pop3Client.GetMessage(i); if (message.Headers.MessageId == messageID) { messages.Add(i, message); GetAttachmentsFromMessage(messages, i); FileController.UpdByPassCode(passcode); pop3Client.DeleteMessage(i); break; } } catch (Exception e) { MessageBox.Show("Exception occured while reading emails", "Information!", MessageBoxButton.OK, MessageBoxImage.Information); } } return("Attachments for the given passcode has been downloaded in the Standard path"); } else { return(""); } } else { return(""); } } catch (Exception e) { return(""); } }
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 TestQuotedPrintableDoesNotDecodeUnderscoresInBody() { const string messagePartContent = "Content-Transfer-Encoding: quoted-printable\r\n" + "\r\n" + // End of message headers "a_a"; MessagePart messagePart = new Message(Encoding.ASCII.GetBytes(messagePartContent)).MessagePart; // QuotedPrintable, when used as Content-Transfer-Encoding does not decode _ to spaces const string expectedBody = "a_a"; string actualBody = messagePart.GetBodyAsText(); Assert.AreEqual(expectedBody, actualBody); }
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; }
public void TestFileOverwriteTruncatesFileCorrectly() { const string longMessage = "Content-Type: text/plain\r\n" + "Content-Disposition: attachment\r\n" + "\r\n" + "Testing very long..."; const string smallMessage = "Content-Type: text/plain\r\n" + "Content-Disposition: attachment\r\n" + "\r\n" + "Testing"; const string filename = "test_message_part_save_truncate.testFile"; FileInfo longTestFile = new FileInfo(filename); MessagePart messageLong = new Message(Encoding.ASCII.GetBytes(longMessage)).MessagePart; messageLong.Save(longTestFile); long longFileSize = longTestFile.Length; FileInfo smallTestFile = new FileInfo(filename); MessagePart messageSmall = new Message(Encoding.ASCII.GetBytes(smallMessage)).MessagePart; messageSmall.Save(smallTestFile); long smallFileSize = smallTestFile.Length; smallTestFile.Delete(); Assert.AreNotEqual(longFileSize, smallFileSize); }
/////////////////////////////////////////////////////////////////////// public static string get_headers_for_comment(Message message) { string headers = ""; string subject = get_subject(message); if (!string.IsNullOrEmpty(subject)) { headers = "Subject: " + subject + "\n"; } string to = get_to(message); if (!string.IsNullOrEmpty(to)) { headers += "To: " + to + "\n"; } string cc = get_cc(message); if (!string.IsNullOrEmpty(cc)) { headers += "Cc: " + cc + "\n"; } return headers; }
private void btnConnect_Click(object sender, EventArgs e) { if (!client.Connected) { btnConnect.Text = "Disconnect"; // Connect to the server try { client.Connect(txtServer.Text, Convert.ToInt32(txtPort.Text), SSL_bx.Checked); txtLog.AppendText(DateTime.Now.ToLongTimeString() + " 39. Server connected.\r\n\r\n"); txtLog.Update(); // Authenticate ourselves towards the server try { client.Authenticate(txtUser.Text, txtPass.Text); txtLog.AppendText(DateTime.Now.ToLongTimeString() + " 44. Server Authenticated.\r\n\r\n"); txtLog.Update(); // Get the number of messages in the inbox List <string> mssgs = client.GetMessageUids(); int messageCount = mssgs.Count; txtLog.AppendText(DateTime.Now.ToLongTimeString() + " 51. Total messages: " + messageCount.ToString() + "\r\n\r\n"); txtLog.Update(); // We want to download all messages allMessages = new List <OpenPop.Mime.Message>(messageCount); // Messages are numbered in the interval: [1, messageCount] // Ergo: message numbers are 1-based. // Most servers give the latest message the highest number for (int i = messageCount; i > (messageCount - 10); i--) { OpenPop.Mime.Message curr_mssg = client.GetMessage(i); allMessages.Add(curr_mssg); this.mail_gridview.Rows.Add(curr_mssg.Headers.From.MailAddress.ToString(), (messageCount - i)); } } catch (Exception ex) { txtLog.AppendText(DateTime.Now.ToLongTimeString() + " 69. Error: " + ex.Message + "\r\n\r\n"); txtLog.Update(); client.Disconnect(); btnConnect.Text = "Connect"; txtLog.AppendText(DateTime.Now.ToLongTimeString() + " 73. Disconnected.\r\n\r\n"); return; } } catch (Exception ex) { txtLog.AppendText(DateTime.Now.ToLongTimeString() + " 79. Error: " + ex.Message + "\r\n\r\n"); txtLog.Update(); btnConnect.Text = "Connect"; return; } } else { btnConnect.Text = "Connect"; client.Disconnect(); txtLog.AppendText(DateTime.Now.ToLongTimeString() + " 89. Disconnected.\r\n\r\n"); } }
private void ReceiveMails() { //取得昨天的日期 string v_yesterday = DateTime.Now.AddDays(-2).ToString("yyyy/MM/dd"); //取得今天的日期 string v_today = DateTime.Now.AddHours(-6).ToString("yyyy/MM/dd"); // Disable buttons while working connectAndRetrieveButton.Enabled = false; //uidlButton.Enabled = false; progressBar.Value = 0; string v_sender, v_mailTo, v_subject, v_attachment; //讀取CRM_SALES_EMAIL 帳號、密碼 //EMP_NO 0, EMP_NAME 1, EMAIL_ADDR 2, LOGIN_ID 3, PASSWORD 4 OleDbDataReader dr2 = GetDr(); //沒有EMAIL清單,就跳出 if (!dr2.HasRows) { return; } try { totalSuccess = 0; while (dr2.Read()) { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(popServerTextBox.Text, int.Parse(portTextBox.Text), useSslCheckBox.Checked); pop3Client.Authenticate(dr2[3].ToString(), dr2[4].ToString()); int count = pop3Client.GetMessageCount(); counterLabel.Text = count.ToString(); IDlabel.Text = dr2[3].ToString(); nameLabel.Text = dr2[1].ToString(); messages.Clear(); mailListTB.Clear(); 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); success++; //寄件者 v_sender = message.Headers.From.ToString().Replace("'", ""); if (v_sender.Trim().Equals("")) { v_sender = "no sender"; } if (v_sender.Length > 200) { v_sender = v_sender.Substring(0, 200); } //收件者資料 v_mailTo = ""; foreach (RfcMailAddress to in message.Headers.To) { if (v_mailTo.Trim().Equals("")) { v_mailTo = to.ToString(); } else { v_mailTo += ";" + to.ToString(); } } v_mailTo = v_mailTo.Replace("'", ""); if (v_mailTo.Equals("")) { v_mailTo = "no recevie"; } if (v_mailTo.Length > 100) { v_mailTo = v_mailTo.Substring(0, 100); } //主旨 v_subject = Regex.Replace(message.Headers.Subject, @"<[^>]*>", "NO SUBJECT"); v_subject = v_subject.Replace("'", "").Replace("&", " and "); if (v_subject.Trim().Equals("")) { v_subject = "no subject"; } if (v_subject.Length > 500) { v_subject = v_subject.Substring(0, 500); } //附件資料 v_attachment = ""; List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { if (v_attachment.Equals("")) { v_attachment = attachment.FileName; } else { v_attachment += ";" + attachment.FileName; } } if (v_attachment.Length > 200) { v_attachment = v_attachment.Substring(0, 200); } //v_attachment = v_attachment.Replace("'", ""); bool hadAttachments = attachments.Count > 0; if (hadAttachments == false) { v_attachment = ""; } //接收日 string v_receiveDate = message.Headers.DateSent.ToString("yyyy/MM/dd"); //比對日期,今天的郵件才寫入資料庫 DateTime recevDate = DateTime.ParseExact(v_receiveDate, "yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture); DateTime beforeDate = DateTime.ParseExact(v_yesterday, "yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture); if (recevDate >= beforeDate) //if (v_recevice_date.Equals(v_today)) { //寫入資料庫 //檢查是否已有資料 if (chk_data_exist(v_sender, v_mailTo, v_subject, v_receiveDate)) { bool v_flag = insertDB(dr2[0].ToString(), dr2[1].ToString(), v_sender, v_mailTo, v_subject, v_attachment, v_receiveDate); //有成功寫入資料庫才紀錄 if (v_flag) { totalSuccess++; mailListTB.Text += dr2[1].ToString() + "," + v_sender + "," + v_subject + "," + v_receiveDate + "\r\n"; } } } counter2Label.Text = success.ToString(); counter3Label.Text = totalSuccess.ToString(); } catch (Exception e) { //工號、姓名、帳號、密碼、郵件編號 HeadersFromAndSubject(dr2[0].ToString(), dr2[1].ToString(), dr2[3].ToString(), dr2[4].ToString(), i); //errorTB.Text += "sn:"+i.ToString()+","+e.Message + "\r\n"; DefaultLogger.Log.LogError( "TestForm: Message fetching failed: " + e.Message + "\r\n" + "Stack trace:\r\n" + e.StackTrace); fail++; System.Threading.Thread.Sleep(100); } progressBar.Value = (int)(((double)(count - i) / count) * 100); counter4Label.Text = fail.ToString(); } //MessageBox.Show(this, "Mail received!\nSuccesses: " + success + "\nFailed: " + fail, "Message fetching done"); //counter3Label.Text = fail.ToString(); } } catch (InvalidLoginException) { errorTB.Text += "POP3 Server Authentication:The server did not accept the user credentials!\r\n"; //MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication"); } catch (PopServerNotFoundException) { errorTB.Text += "POP3 Retrieval。The server could not be found.\r\n"; //MessageBox.Show(this, "The server could not be found", "POP3 Retrieval"); } catch (PopServerLockedException) { errorTB.Text += "POP3 Account Locked。The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?\r\n"; //MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked"); } catch (LoginDelayException) { errorTB.Text += "POP3 Account Login Delay。Login not allowed. Server enforces delay between logins. Have you connected recently?\r\n"; //MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay"); } catch (Exception) { errorTB.Text += "POP3 Retrieval。Error occurred retrieving mail.\r\n "; //MessageBox.Show(this, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval"); } finally { dr2.Close(); conn.Close(); toolStripStatusLabel1.Text = "掃描已結束:" + DateTime.Now.ToString("hh:mm:ss"); // Enable the buttons again connectAndRetrieveButton.Enabled = true; //uidlButton.Enabled = true; progressBar.Value = 100; } }
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); } }
public static string get_to(Message message) { return string.Join("; ", message.Headers.To.Select(c => c.Address)); }
//try making this a static void gpc 2016-12-7 private void ReceiveMails() { // Disable buttons while working connectAndRetrieveButton.Enabled = false; uidlButton.Enabled = false; progressBar.Value = 0; try { if (pop3Client.Connected) { pop3Client.Disconnect(); } string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string file = Path.Combine(myDocs, "OpenPopLogin.txt"); if (File.Exists(file)) { using (StreamReader reader = new StreamReader(File.OpenRead(file))) { // //GPC Modified to read values into variables as well as the textboxes on the form 2016-12-06 //This describes how the OpenPOPLogin.txt file should look like // string popServer = reader.ReadLine(); // Hostname popServerTextBox.Text = popServer; string porttoUse = reader.ReadLine(); // Port portTextBox.Text = porttoUse; bool useSsl = bool.Parse(reader.ReadLine() ?? "true"); // Whether to use SSL or not useSslCheckBox.Checked = useSsl; string longinID = reader.ReadLine(); // Username loginTextBox.Text = longinID; string password = reader.ReadLine(); // Password passwordTextBox.Text = password; //} //} //GPC Edited to use variables read from file, not from form controls 2016-12-06 pop3Client.Connect(popServer, int.Parse(porttoUse), useSsl); pop3Client.Authenticate(longinID, password); } } // pop3Client.Connect(popServerTextBox.Text, int.Parse(portTextBox.Text), useSslCheckBox.Checked); //pop3Client.Authenticate(loginTextBox.Text, passwordTextBox.Text); int count = pop3Client.GetMessageCount(); totalMessagesTextBox.Text = count.ToString(); messageTextBox.Text = ""; messages.Clear(); listMessages.Nodes.Clear(); listAttachments.Nodes.Clear(); 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); // Add the message to the dictionary from the messageNumber to the Message messages.Add(i, message); // Create a TreeNode tree that mimics the Message hierarchy TreeNode node = new TreeNodeBuilder().VisitMessage(message); // Set the Tag property to the messageNumber // We can use this to find the Message again later node.Tag = i; // Show the built node in our list of messages listMessages.Nodes.Add(node); success++; } catch (Exception e) { DefaultLogger.Log.LogError( "TestForm: Message fetching failed: " + e.Message + "\r\n" + "Stack trace:\r\n" + e.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, "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, "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 { // Enable the buttons again connectAndRetrieveButton.Enabled = true; uidlButton.Enabled = true; progressBar.Value = 100; } }
public void TestIsAttachmentImageJpeg() { const string messagePartContent = "Content-Type: image/jpeg\r\n" + "\r\n"; // End of message headers MessagePart messagePart = new Message(Encoding.ASCII.GetBytes(messagePartContent)).MessagePart; Assert.IsTrue(messagePart.IsAttachment); }
//private void DepartSent_SMS() //{ // DataTable dtDepartmentSMSSent = new DataTable(); // dtDepartmentSMSSent = DataAccessManager.GetSMSSent( Convert.ToString(Session["DeptID"]), Convert.ToInt32(Session["CampusID"])); // Session["dtDepartmentSMSSent"] = dtDepartmentSMSSent; // rgvDepartmentSent.DataSource = (DataTable)Session["dtDepartmentSMSSent"]; //} //protected void rgvDepartmentSent_SortCommand(object sender, GridSortCommandEventArgs e) //{ // this.rgvDepartmentSent.MasterTableView.AllowNaturalSort = true; // this.rgvDepartmentSent.MasterTableView.Rebind(); //} //protected void rgvDepartmentSent_PageIndexChanged(object sender, GridPageChangedEventArgs e) //{ // try // { // rgvDepartmentSent.DataSource = (DataTable)Session["dtDepartmentSMSSent"]; // } // catch (Exception ex) // { // } //} #endregion public void fetchmail(string DeptID, int CampusID) { try { DataTable dtEmailConfig = DataAccessManager.GetEmailConfigDetail(DeptID, CampusID); if (dtEmailConfig.Rows.Count > 0) { Pop3Client pop3Client; pop3Client = new Pop3Client(); pop3Client.Connect(dtEmailConfig.Rows[0]["Pop3"].ToString(), Convert.ToInt32(dtEmailConfig.Rows[0]["PortIn"]), Convert.ToBoolean(dtEmailConfig.Rows[0]["SSL"])); pop3Client.Authenticate(dtEmailConfig.Rows[0]["DeptEmail"].ToString(), dtEmailConfig.Rows[0]["Pass"].ToString(), AuthenticationMethod.UsernameAndPassword); if (pop3Client.Connected) { int count = pop3Client.GetMessageCount(); int progressstepno; if (count == 0) { } else { progressstepno = 100 - count; this.Emails = new List <Email>(); for (int i = 1; i <= count; i++) { OpenPop.Mime.Message message = pop3Client.GetMessage(i); Email email = new Email() { MessageNumber = i, messageId = message.Headers.MessageId, Subject = message.Headers.Subject, DateSent = message.Headers.DateSent, From = message.Headers.From.Address }; MessagePart body = message.FindFirstHtmlVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } else { body = message.FindFirstHtmlVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } } email.IsAttached = false; this.Emails.Add(email); //Attachment Process List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { email.IsAttached = true; string FolderName = string.Empty; FolderName = Convert.ToString(Session["CampusName"]); String path = Server.MapPath("~/InboxAttachment/" + FolderName); if (!Directory.Exists(path)) { // Try to create the directory. DirectoryInfo di = Directory.CreateDirectory(path); } string ext = attachment.FileName.Split('.')[1]; // FileInfo file = new FileInfo(Server.MapPath("InboxAttachment\\") + attachment.FileName.ToString()); FileInfo file = new FileInfo(Server.MapPath("InboxAttachment\\" + FolderName + "\\") + attachment.FileName.ToString()); attachment.SaveToFile(file); Attachment att = new Attachment(); att.messageId = message.Headers.MessageId; att.FileName = attachment.FileName; attItem.Add(att); } //System.Threading.Thread.Sleep(500); } //Insert into database Inbox table DataTable dtStudentNo = new DataTable(); bool IsReadAndSave = false; foreach (var ReadItem in Emails) { string from = string.Empty, subj = string.Empty, messId = string.Empty, Ebody = string.Empty; from = Convert.ToString(ReadItem.From); subj = Convert.ToString(ReadItem.Subject); messId = Convert.ToString(ReadItem.messageId); Ebody = Convert.ToString(ReadItem.Body); if (Ebody != string.Empty && Ebody != null) { Ebody = Ebody.Replace("'", " "); } DateTime date = ReadItem.DateSent; bool IsAtta = ReadItem.IsAttached; //Student Email if (Source.SOrL(Convert.ToString(Session["StudentNo"]), Convert.ToString(Session["leadID"]))) { dtStudentNo = DyDataAccessManager.GetStudentNo(from, from); if (dtStudentNo.Rows.Count == 0) { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabase("0", Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } else { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabase(dtStudentNo.Rows[0]["StudentNo"].ToString(), Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } } //Leads Email if (Source.SOrL(Convert.ToString(Session["ParamStudentNo"]), Convert.ToString(Session["ParamleadID"])) == false) { dtStudentNo = DyDataAccessManager.GetLeadsID(from, from); if (dtStudentNo.Rows.Count == 0) { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabaseLead("0", Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } else { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabaseLead(dtStudentNo.Rows[0]["LeadsID"].ToString(), Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } } // } //Insert into database Attachment table foreach (var attachItem in attItem) { bool success; string Filname = attachItem.FileName; string MssID = attachItem.messageId; success = DataAccessManager.ReadEmailAttachmentAndSaveDatabase(MssID, Filname); } Emails.Clear(); // attItem.Clear(); pop3Client.DeleteAllMessages(); //StartNotification(count); } } pop3Client.Disconnect(); } } catch (Exception ex) { } }
public void TestHeaderWhiteSpace() { const string messagePartContent = "Content-Disposition: attachment; filename=Attach2.txt; modification-date=\"21\r\n" + " Feb 2011 17:09:47 +0000\"; read-date=\"21 Feb 2011 17:09:47 +0000\";\r\n" + " creation-date=\"21 Feb 2011 12:59:07 +0000\"\r\n" + "\r\n"; // End of message headers MessagePart messagePart = new Message(Encoding.ASCII.GetBytes(messagePartContent)).MessagePart; Assert.IsFalse(messagePart.ContentDisposition.Inline); DateTime modificationDate = new DateTime(2011, 2, 21, 17, 09, 47, DateTimeKind.Utc); Assert.AreEqual(modificationDate, messagePart.ContentDisposition.ModificationDate); DateTime readDate = modificationDate; Assert.AreEqual(readDate, messagePart.ContentDisposition.ReadDate); DateTime creationDate = new DateTime(2011, 2, 21, 12, 59, 07, DateTimeKind.Utc); Assert.AreEqual(creationDate, messagePart.ContentDisposition.CreationDate); Assert.AreEqual("Attach2.txt", messagePart.ContentDisposition.FileName); }
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); }
public void TestEmptyPartInMultipartMessage() { const string messagePartContent = "Content-Type: multipart/mixed;\r\n" + "\tboundary=\"----=_NextPart_000_012A_01CDF7CD.431E54B0\"\r\n" + "\r\n" + "------=_NextPart_000_012A_01CDF7CD.431E54B0\r\n" + "------=_NextPart_000_012A_01CDF7CD.431E54B0\r\n" + "\r\n" + "------=_NextPart_000_012A_01CDF7CD.431E54B0\r\n" + "Content-Type: text/plain;\r\n" + "\r\n" + "foo\r\n" + "------=_NextPart_000_012A_01CDF7CD.431E54B0\r\n" + "------=_NextPart_000_012A_01CDF7CD.431E54B0--\r\n" + "\r\n" + "\r\n" ; MessagePart messagePart = new Message(Encoding.ASCII.GetBytes(messagePartContent)).MessagePart; Assert.AreEqual(1, messagePart.MessageParts.Count); Assert.AreEqual("foo", messagePart.MessageParts[0].GetBodyAsText()); }
public async void load(int numberMail) { IProgress <int> progress = new Progress <int>(value => { progressBar1.Value = value; }); progressBar1.Visible = true; progressBar1.Minimum = 0; progressBar1.Step = 1; Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); var client = new Pop3Client(); client.Connect("pop.gmail.com", 995, true); client.Authenticate("recent:[email protected]", "vnfkfkxlcgpnebra"); List <string> uids = client.GetMessageUids(); List <OpenPop.Mime.Message> AllMsgReceived = new List <OpenPop.Mime.Message>(); SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Alexandre\Source\Repos\MailApplication\MailManager\DB\database1.mdf;Integrated Security=True"); ManageDB.RemoveMail(con); List <string> seenUids = new List <string>(); int messageCount = client.GetMessageCount(); progressBar1.Maximum = numberMail; await Task.Run(() => { firstkeer = false; for (int i = messageCount; i >= (messageCount - numberMail); i--) { progress.Report(messageCount - i); OpenPop.Mime.Message unseenMessage = client.GetMessage(i); AllMsgReceived.Add(unseenMessage); } var mails = new List <Mail>(); MessagePart plainTextPart = null, HTMLTextPart = null; string pattern = @"[A-Za-z0-9]*[@]{1}[A-Za-z0-9]*[.\]{1}[A-Za-z]*"; int a = 0; foreach (var msg in AllMsgReceived) { //Check you message is not null if (msg != null) { plainTextPart = msg.FindFirstPlainTextVersion(); //HTMLTextPart = msg.FindFirstHtmlVersion(); //mail.Html = (HTMLTextPart == null ? "" : HTMLTextPart.GetBodyAsText().Trim()); //ajouter au serveur //mails.Add(new Mail { From = Regex.Match(msg.Headers.From.ToString(), pattern).Value, Subject = msg.Headers.Subject, Date = msg.Headers.DateSent.ToString(), msg = (plainTextPart == null ? "" : plainTextPart.GetBodyAsText().Trim()), Attachment = msg.FindAllAttachments() }); ManageDB.AddMailToDB( new Mail { From = Regex.Match(msg.Headers.From.ToString(), pattern).Value, Subject = msg.Headers.Subject, Date = msg.Headers.DateSent.ToString(), msg = (plainTextPart == null ? "" : plainTextPart.GetBodyAsText().Trim()), Attachment = msg.FindAllAttachments(), Reference = a += 1 }, con); } } ManageDB.AddNewContact(con); //LoadApp.mail = mails; successLoad = true; }); label1.Text = ""; button1.Show(); }
private void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e) { //####################### Get Attachment from Email ########################################### ListBox listBox1 = new ListBox(); var client = new Pop3Client(); int Port_Number = 995; Boolean UseSSL = true; string sendBack = string.Empty; string returnSubject = string.Empty; try { client.Connect("pop.gmail.com", Port_Number, UseSSL); client.Authenticate("*****@*****.**", "XXXXXXX"); var messageCount = client.GetMessageCount(); var header = client.GetMessageInfos(); var Messages = new List<OpenPop.Mime.Message>(messageCount); var Headers = new List<MessageHeader>(messageCount); for (int i = 0; i < messageCount; i++) { OpenPop.Mime.Message getMessage = client.GetMessage(i + 1); Messages.Add(getMessage); } for (int i = 0; i < messageCount; i++) { OpenPop.Mime.Header.MessageHeader getHeader = client.GetMessageHeaders(i + 1); Headers.Add(getHeader); } foreach (OpenPop.Mime.Message msg in Messages) { foreach (var attachment in msg.FindAllAttachments()) { string filePath = Path.Combine(@"C:\Users\colin\Desktop\File.txt"); if (attachment.FileName.Equals("EditCode.txt")) { FileStream Stream = new FileStream(filePath, FileMode.Create); BinaryWriter BinaryStream = new BinaryWriter(Stream); BinaryStream.Write(attachment.Body); BinaryStream.Close(); foreach (var s in Headers) { string Reply = s.ReturnPath.ToString(); sendBack = Reply.ToString(); string Subby = s.Subject.ToString(); returnSubject = Subby.ToString(); } if (client.Connected) client.Dispose(); } else { if (client.Connected) client.Dispose(); break; } } } } catch (Exception ex) { MessageBox.Show("", ex.Message); } //####################### Edit File ########################################### if (System.IO.File.Exists(@"C:\Users\colin\Desktop\File.txt")) { using (StreamReader sr = new StreamReader(@"C:\Users\colin\Desktop\File.txt")) { { string line; while ((line = sr.ReadLine()) != null) { if (line.Contains("<div")) { string s = "<div{value here}>"; int start = s.IndexOf("<div"); int end = s.IndexOf(">"); line = line.Remove(start); } if (line.Contains("</div>")) { line = line.Replace("</div>", ""); } if (line.Contains("h1")) { line = line.Replace("h1", "h4"); } if (line.Contains("h2")) { line = line.Replace("h2", "h4"); } if (line.Contains("h3")) { line = line.Replace("h3", "h4"); } if (line.Contains(" ")) { line = line.Replace(" ", ""); } if (line.Contains("’")) { line = line.Replace("’", "'"); } if (line.Contains(" –")) { line = line.Replace(" –", "."); } if (line.Contains("â€")) { line = line.Replace("â€", ""); } if (line.Contains("“")) { line = line.Replace("“", ""); } if (line.Contains("œ")) { line = line.Replace("œ", ""); } if (line.Contains(""")) { line = line.Replace(""", ""); } if (line.Contains("&")) { line = line.Replace("&", ""); } if (line.Contains("'")) { line = line.Replace("'", "'"); } if (line.Contains("class=\"note\"")) { line = line.Replace("class=\"note\"", ""); } if (line.Contains("class=\"first\"")) { line = line.Replace("class=\"first\"", ""); } if (line.Contains("class=\"last\"")) { line = line.Replace("class=\"last\"", ""); } if (line.Contains("class=\"odd\"")) { line = line.Replace("class=\"odd\"", ""); } if (line.Contains("class=\"even\"")) { line = line.Replace("class=\"even\"", ""); } if (line.Contains("class=\"bot\"")) { line = line.Replace("class=\"bot\"", ""); } if (line.Contains("class=\"data-table data-table-simple\"")) { line = line.Replace("class=\"data-table data-table-simple\"", "class=\"content-table\""); } if (line.Contains("class=\"data-table data-table-advanced\"")) { line = line.Replace("class=\"data-table data-table-advanced\"", "class=\"content-table\""); } if (line.Contains("<tr style=\"height:")) { line = line.Replace("<tr style=\"height: 10px;\">", "<tr>"); line = line.Replace("<tr style=\"height:10px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 20px;\">", "<tr>"); line = line.Replace("<tr style=\"height:20px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 30px;\">", "<tr>"); line = line.Replace("<tr style=\"height:30px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 40px;\">", "<tr>"); line = line.Replace("<tr style=\"height:40px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 50px;\">", "<tr>"); line = line.Replace("<tr style=\"height:50px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 60px;\">", "<tr>"); line = line.Replace("<tr style=\"height:60px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 70px;\">", "<tr>"); line = line.Replace("<tr style=\"height:70px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 80px;\">", "<tr>"); line = line.Replace("<tr style=\"height:80px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 90px;\">", "<tr>"); line = line.Replace("<tr style=\"height:90px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 100px;\">", "<tr>"); line = line.Replace("<tr style=\"height:100px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 110px;\">", "<tr>"); line = line.Replace("<tr style=\"height:110px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 120px;\">", "<tr>"); line = line.Replace("<tr style=\"height:120px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 10px\">", "<tr>"); line = line.Replace("<tr style=\"height:10px\">", "<tr>"); line = line.Replace("<tr style=\"height: 20px\">", "<tr>"); line = line.Replace("<tr style=\"height:20px\">", "<tr>"); line = line.Replace("<tr style=\"height: 30px\">", "<tr>"); line = line.Replace("<tr style=\"height:30px\">", "<tr>"); line = line.Replace("<tr style=\"height: 40px\">", "<tr>"); line = line.Replace("<tr style=\"height:40px\">", "<tr>"); line = line.Replace("<tr style=\"height: 50px\">", "<tr>"); line = line.Replace("<tr style=\"height:50px\">", "<tr>"); line = line.Replace("<tr style=\"height: 60px\">", "<tr>"); line = line.Replace("<tr style=\"height:60px\">", "<tr>"); line = line.Replace("<tr style=\"height: 70px\">", "<tr>"); line = line.Replace("<tr style=\"height:70px\">", "<tr>"); line = line.Replace("<tr style=\"height: 80px\">", "<tr>"); line = line.Replace("<tr style=\"height:80px\">", "<tr>"); line = line.Replace("<tr style=\"height: 90px\">", "<tr>"); line = line.Replace("<tr style=\"height:90px\">", "<tr>"); line = line.Replace("<tr style=\"height: 100px\">", "<tr>"); line = line.Replace("<tr style=\"height:100px\">", "<tr>"); line = line.Replace("<tr style=\"height: 110px\">", "<tr>"); line = line.Replace("<tr style=\"height:110px\">", "<tr>"); line = line.Replace("<tr style=\"height: 120px\">", "<tr>"); line = line.Replace("<tr style=\"height:120px\">", "<tr>"); } if (line.Contains("<th style=\"height:")) { line = line.Replace("<th style=\"height: 10px;\">", "<th>"); line = line.Replace("<th style=\"height:10px;\">", "<th>"); line = line.Replace("<th style=\"height: 20px;\">", "<th>"); line = line.Replace("<th style=\"height:20px;\">", "<th>"); line = line.Replace("<th style=\"height: 30px;\">", "<th>"); line = line.Replace("<th style=\"height:30px;\">", "<th>"); line = line.Replace("<th style=\"height: 40px;\">", "<th>"); line = line.Replace("<th style=\"height:40px;\">", "<th>"); line = line.Replace("<th style=\"height: 50px;\">", "<th>"); line = line.Replace("<th style=\"height:50px;\">", "<th>"); line = line.Replace("<th style=\"height: 60px;\">", "<th>"); line = line.Replace("<th style=\"height:60px;\">", "<th>"); line = line.Replace("<th style=\"height: 70px;\">", "<th>"); line = line.Replace("<th style=\"height:70px;\">", "<th>"); line = line.Replace("<th style=\"height: 80px;\">", "<th>"); line = line.Replace("<th style=\"height:80px;\">", "<th>"); line = line.Replace("<th style=\"height: 90px;\">", "<th>"); line = line.Replace("<th style=\"height:90px;\">", "<th>"); line = line.Replace("<th style=\"height: 100px;\">", "<th>"); line = line.Replace("<th style=\"height:100px;\">", "<th>"); line = line.Replace("<th style=\"height: 110px;\">", "<th>"); line = line.Replace("<th style=\"height:110px;\">", "<th>"); line = line.Replace("<th style=\"height: 120px;\">", "<th>"); line = line.Replace("<th style=\"height:120px;\">", "<th>"); line = line.Replace("<th style=\"height: 10px\">", "<th>"); line = line.Replace("<th style=\"height:10px\">", "<th>"); line = line.Replace("<th style=\"height: 20px\">", "<th>"); line = line.Replace("<th style=\"height:20px\">", "<th>"); line = line.Replace("<th style=\"height: 30px\">", "<th>"); line = line.Replace("<th style=\"height:30px\">", "<th>"); line = line.Replace("<th style=\"height: 40px\">", "<th>"); line = line.Replace("<th style=\"height:40px\">", "<th>"); line = line.Replace("<th style=\"height: 50px\">", "<th>"); line = line.Replace("<th style=\"height:50px\">", "<th>"); line = line.Replace("<th style=\"height: 60px\">", "<th>"); line = line.Replace("<th style=\"height:60px\">", "<th>"); line = line.Replace("<th style=\"height: 70px\">", "<th>"); line = line.Replace("<th style=\"height:70px\">", "<th>"); line = line.Replace("<th style=\"height: 80px\">", "<th>"); line = line.Replace("<th style=\"height:80px\">", "<th>"); line = line.Replace("<th style=\"height: 90px\">", "<th>"); line = line.Replace("<th style=\"height:90px\">", "<th>"); line = line.Replace("<th style=\"height: 100px\">", "<th>"); line = line.Replace("<th style=\"height:100px\">", "<th>"); line = line.Replace("<th style=\"height: 110px\">", "<th>"); line = line.Replace("<th style=\"height:110px\">", "<th>"); line = line.Replace("<th style=\"height: 120px\">", "<th>"); line = line.Replace("<th style=\"height:120px\">", "<th>"); } if (line.Contains("<td style=\"height:")) { line = line.Replace("<td style=\"height: 10px;\">", "<td>"); line = line.Replace("<td style=\"height:10px;\">", "<td>"); line = line.Replace("<td style=\"height: 20px;\">", "<td>"); line = line.Replace("<td style=\"height:20px;\">", "<td>"); line = line.Replace("<td style=\"height: 30px;\">", "<td>"); line = line.Replace("<td style=\"height:30px;\">", "<td>"); line = line.Replace("<td style=\"height: 40px;\">", "<td>"); line = line.Replace("<td style=\"height:40px;\">", "<td>"); line = line.Replace("<td style=\"height: 50px;\">", "<td>"); line = line.Replace("<td style=\"height:50px;\">", "<td>"); line = line.Replace("<td style=\"height: 60px;\">", "<td>"); line = line.Replace("<td style=\"height:60px;\">", "<td>"); line = line.Replace("<td style=\"height: 70px;\">", "<td>"); line = line.Replace("<td style=\"height:70px;\">", "<td>"); line = line.Replace("<td style=\"height: 80px;\">", "<td>"); line = line.Replace("<td style=\"height:80px;\">", "<td>"); line = line.Replace("<td style=\"height: 90px;\">", "<td>"); line = line.Replace("<td style=\"height:90px;\">", "<td>"); line = line.Replace("<td style=\"height: 100px;\">", "<td>"); line = line.Replace("<td style=\"height:100px;\">", "<td>"); line = line.Replace("<td style=\"height: 110px;\">", "<td>"); line = line.Replace("<td style=\"height:110px;\">", "<td>"); line = line.Replace("<td style=\"height: 120px;\">", "<td>"); line = line.Replace("<td style=\"height:120px;\">", "<td>"); line = line.Replace("<td style=\"height: 10px\">", "<td>"); line = line.Replace("<td style=\"height:10px\">", "<td>"); line = line.Replace("<td style=\"height: 20px\">", "<td>"); line = line.Replace("<td style=\"height:20px\">", "<td>"); line = line.Replace("<td style=\"height: 30px\">", "<td>"); line = line.Replace("<td style=\"height:30px\">", "<td>"); line = line.Replace("<td style=\"height: 40px\">", "<td>"); line = line.Replace("<td style=\"height:40px\">", "<td>"); line = line.Replace("<td style=\"height: 50px\">", "<td>"); line = line.Replace("<td style=\"height:50px\">", "<td>"); line = line.Replace("<td style=\"height: 60px\">", "<td>"); line = line.Replace("<td style=\"height:60px\">", "<td>"); line = line.Replace("<td style=\"height: 70px\">", "<td>"); line = line.Replace("<td style=\"height:70px\">", "<td>"); line = line.Replace("<td style=\"height: 80px\">", "<td>"); line = line.Replace("<td style=\"height:80px\">", "<td>"); line = line.Replace("<td style=\"height: 90px\">", "<td>"); line = line.Replace("<td style=\"height:90px\">", "<td>"); line = line.Replace("<td style=\"height: 100px\">", "<td>"); line = line.Replace("<td style=\"height:100px\">", "<td>"); line = line.Replace("<td style=\"height: 110px\">", "<td>"); line = line.Replace("<td style=\"height:110px\">", "<td>"); line = line.Replace("<td style=\"height: 120px\">", "<td>"); line = line.Replace("<td style=\"height:120px\">", "<td>"); } if (line.Contains("style=\"text-align:left") || line.Contains("style=\"text-align: left") || line.Contains("style= \"text-align:left") || line.Contains("style=\" text-align: left")) { line = line.Replace("style=\"text-align:left\"", ""); line = line.Replace("style=\"text-align: left\"", ""); line = line.Replace("style=\"text-align:left;\"", ""); line = line.Replace("style=\"text-align: left;\"", ""); line = line.Replace("style=\" text-align:left\"", ""); line = line.Replace("style=\" text-align: left\"", ""); line = line.Replace("style=\" text-align:left;\"", ""); line = line.Replace("style=\" text-align: left;\"", ""); line = line.Replace("style= \"text-align:left\"", ""); line = line.Replace("style= \"text-align: left\"", ""); line = line.Replace("style= \"text-align:left;\"", ""); line = line.Replace("style= \"text-align: left;\"", ""); } if (line.Contains("<td>") || line.Contains("<td >") || line.Contains("<td >")) { line = line.Replace("<td>", "<td style=\"text-align:center\">"); line = line.Replace("<td >", "<td style=\"text-align:center\">"); line = line.Replace("<td >", "<td style=\"text-align:center\">"); } if (line.Contains("<th>") || line.Contains("<th >") || line.Contains("<th >")) { line = line.Replace("<th>", "<th style=\"text-align:center\">"); line = line.Replace("<th >", "<th style=\"text-align:center\">"); line = line.Replace("<th >", "<th style=\"text-align:center\">"); } if (line.Contains("<h4") || line.Contains("< h4") && line.Contains("<br") || line.Contains("< br")) { line = line.Replace("<br/>", ""); line = line.Replace("< br/>", ""); line = line.Replace("<br/ >", ""); line = line.Replace("< br/ >", ""); line = line.Replace("<br />", ""); line = line.Replace("< br />", ""); line = line.Replace("<br / >", ""); line = line.Replace("< br / >", ""); line = line.Replace("< br/ >", ""); line = line.Replace("< br/ >", ""); } if (line.Contains("<table")) { line = line.Replace("<table", "<table border=\"1\""); } if (line.Contains("<ol>")) { line = line.Replace("<ol>", "<ol style=\"list-style-type:lower-alpha\">"); } if (line.Contains("<strong>note") || line.Contains("<strong>Note")) { listBox1.Items.Add("<br/><br/>"); } if (line.Contains("<strong>important") || line.Contains("<strong>Important")) { listBox1.Items.Add("<br/><br/>"); } if (line.Contains("<strong>result") || line.Contains("<strong>Result")) { listBox1.Items.Add("<br/><br/>"); } if (line.Contains("<h4>") || line.Contains("<h4 >")) { listBox1.Items.Add("</div>"); listBox1.Items.Add("<div class=\"content-box\">"); listBox1.Items.Add("<div class=\"information-box\">"); listBox1.Items.Add("<div class=\"meatball\"></div>"); } listBox1.Items.Add(line); if (line.Contains("</h4>") || line.Contains("</h4 >")) { string p = "</h4>"; int start = p.IndexOf("</h4>"); listBox1.Items.Add("</div>"); } } string look = listBox1.Items[0].ToString(); if (look.Contains("</div>") == false) { listBox1.Items.Insert(0, "</div>"); listBox1.Items.Insert(0, "<p>SUMMARY</p>"); listBox1.Items.Insert(0, "<div class=\"meatball\"></div>"); listBox1.Items.Insert(0, "<div class=\"information-box\">"); listBox1.Items.Insert(0, "<div class=\"content-box\">"); listBox1.Items.Insert(0, "<div id=\"general\">"); } if (look.Contains("</div>")) { listBox1.Items.Remove("</div>"); listBox1.Items.Insert(0, "<div id=\"general\">"); } listBox1.Items.Add("</div> </div>"); } } } else { Application.Restart(); } //####################### Save Attachment ########################################### string sPath = @"C:\Users\colin\Desktop\EditFile.txt"; System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath); foreach (var item in listBox1.Items) { SaveFile.WriteLine(item); } SaveFile.Close(); if (System.IO.File.Exists(@"C:\Users\colin\Desktop\File.txt")) { System.IO.File.Delete(@"C:\Users\colin\Desktop\File.txt"); } else { Application.Restart(); } //####################### Send Back Edited File ########################################### try { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); mail.From = new MailAddress("*****@*****.**"); mail.To.Add(sendBack); mail.Subject = returnSubject; mail.Body = "Have a Nice Day!!"; System.Net.Mail.Attachment newAttachment; newAttachment = new System.Net.Mail.Attachment(@"C:\Users\colin\Desktop\EditFile.txt"); mail.Attachments.Add(newAttachment); SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "caiken121"); SmtpServer.EnableSsl = true; SmtpServer.Send(mail); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
/// <summary> /// Crea un formato mail /// </summary> /// <param name="pMensaje">Mensaje obtenido</param> /// <returns></returns> private Mail CrearMail(OpenPop.Mime.Message pMensaje) { //Remiente del Mail string _remitente = pMensaje.Headers.From.Address; string _destinatario = String.Empty; //Si hay 1 o mas destinatarios if (pMensaje.Headers.To.Count >= 1) { //Recorre la lista para ir agregando los destinatarios separados por una coma for (int j = 0; j < pMensaje.Headers.To.Count; j++) { _destinatario += pMensaje.Headers.To[j].Address + ","; } } //Fecha del Mail string _fecha = pMensaje.Headers.Date.ToString(); string _cc = string.Empty; //Si hay 1 o mas CC if (pMensaje.Headers.Cc.Count >= 1) { //Recorre la lista para ir agregando los CC separados por una coma for (int j = 0; j < pMensaje.Headers.Cc.Count; j++) { _cc = pMensaje.Headers.Cc[j].Address + ","; } } string _cco = string.Empty; //Si hay 1 o mas CCO if (pMensaje.Headers.Bcc.Count >= 1) { //Recorre la lista para ir agregando los CCO separados por una coma for (int j = 0; j < pMensaje.Headers.Bcc.Count; j++) { _cco = pMensaje.Headers.Bcc[j].Address + ","; } } string _mensaje = string.Empty; //Verifica si el Mail tiene mas de una parte if (pMensaje.MessagePart.IsMultiPart) { foreach (MessagePart _msgPart in pMensaje.MessagePart.MessageParts) { _mensaje += _msgPart.GetBodyAsText(); } } else if (pMensaje.MessagePart.IsText) { foreach (MessagePart _msgPart in pMensaje.MessagePart.MessageParts) { _mensaje += _msgPart.GetBodyAsText(); } } //Asunto del mail string _asunto = pMensaje.Headers.Subject; string _mailBox = ConvertirMailBox(MailBox.Recibidos); Mail _mail = new Mail(_remitente, _destinatario, _asunto, _cc, _cco, _fecha, _mensaje, _mailBox, false); return(_mail); }
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()); }
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); }