// 下载附件 private void btnDownLoad_Click(object sender, EventArgs e) { if (lstViewMailList.SelectedItems.Count == 0) { MessageBox.Show("请先选择阅读的邮件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } else if (lstViewMailList.SelectedItems[0].SubItems[3].Text == "无") { MessageBox.Show("该邮件没有附件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } int index = lstViewMailList.SelectedItems[0].Index; messageMail = popClient.GetMessage(index + 1); attachments = messageMail.FindAllAttachments(); for (int i = 0; i < attachments.Count; i++) { attachment = attachments[i]; string attachName = attachment.FileName; SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.FileName = attachName; saveFileDialog.Filter = "所有文件(*.*)|(*.*)"; if (saveFileDialog.ShowDialog() != DialogResult.OK) { continue; } string filepath = saveFileDialog.FileName; FileInfo fi = new FileInfo(filepath); attachment.Save(fi); MessageBox.Show("以保存:\r\n" + attachment.FileName, "下载完毕", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
// 刷新邮件列表 private void btnRefreshMailList_Click(object sender, EventArgs e) { // 实例化邮件接收类POP3Class popClient = new Pop3Client(); // 连接服务器 popClient.Connect(tbxPOP3Server.Text, int.Parse(tb_popPort.Text), false); popClient.Authenticate(tbxUserMail.Text, txbPassword.Text); if (popClient != null) { if (popClient.GetMessageCount() > 0) { lstViewMailList.Items.Clear(); tbxMailboxInfo.Text = "共" + popClient.GetMessageCount() + "封邮件"; for (int i = 0; i < popClient.GetMessageCount(); i++) { messageMail = popClient.GetMessage(i + 1); ListViewItem item = new ListViewItem(); item.SubItems.Add(messageMail.Headers.From.Address); item.SubItems.Add(messageMail.Headers.Subject); attachments = messageMail.FindAllAttachments(); if (attachments.Count > 0) { item.SubItems.Add(attachments.Count.ToString()); } else { item.SubItems.Add("无"); } item.SubItems.Add(messageMail.Headers.Date.ToString()); lstViewMailList.Items.Add(item); } } } }
public static void ReadEmail() { using (OpenPop.Pop3.Pop3Client client = new OpenPop.Pop3.Pop3Client()) { client.Connect("pop.gmail.com", 995, true); client.Authenticate("recent:[email protected]", "pass"); if (client.Connected) { Console.WriteLine("Checking inbox"); var count = client.GetMessageCount(); OpenPop.Mime.Message message = client.GetMessage(count); OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion(); builder.Append("Subject: " + message.Headers.Subject + "\n"); builder.Append("Date: " + message.Headers.Date + "\n"); builder.Append("Body: " + plainText.GetBodyAsText()); Console.WriteLine(builder.ToString()); //verifica se existem anexos e caso sim salva-os na pasta var att = message.FindAllAttachments(); foreach (var ado in att) { ado.Save(new System.IO.FileInfo(System.IO.Path.Combine(@"C:\Users\wviegas\Documents\will", ado.FileName))); } } } }
private void GetAttachmentsFromMessage(Dictionary <int, Message> messages, int index) { try { // Fetch out the selected message Message message = messages[index]; // Clear the attachment list from any previus shown attachments List <MessagePart> attachments = message.FindAllAttachments(); List <string> liAttachements = new List <string>(); foreach (MessagePart attachment in attachments) { string filepath = ConfigurationManager.AppSettings["AttachmentsPath"]; filepath = System.IO.Path.Combine(filepath, attachment.FileName); if (attachment != null) { // Now we want to save the attachment FileInfo file = new FileInfo(filepath);//need to change it to seleced path or from configuration // Check if the file already exists if (file.Exists) { // User was asked when he chose the file, if he wanted to overwrite it // Therefore, when we get to here, it is okay to delete the file file.Delete(); } // Lets try to save to the file try { attachment.Save(file); liAttachements.Add(attachment.FileName); } catch (Exception e) { MessageBox.Show(this, "Attachment saving failed. Exception message: " + e.Message, "Information!", MessageBoxButton.OK, MessageBoxImage.Information); } } else { MessageBox.Show(this, "Attachment object was null!", "Information!", MessageBoxButton.OK, MessageBoxImage.Information); } } lstattachments.ItemsSource = liAttachements; } catch (Exception ex) { } }
/// <summary> /// Метод скачивания вложения из сообщения. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btDownload_Click(object sender, EventArgs e) { if (cbAttachments.SelectedIndex >= 0) { Message message = messages[GetMessageNumberFromSelectedNode(listMessages.SelectedNode)]; MessagePart at = message.FindAllAttachments().ElementAt(cbAttachments.SelectedIndex); SaveFileDialog saveFile = new SaveFileDialog(); saveFile.FileName = cbAttachments.SelectedText; saveFile.Title = "Выберите, куда сохранить файл."; if (saveFile.ShowDialog() == DialogResult.OK) { at.Save(new FileInfo(saveFile.FileName)); } } }
public void TestComplexMultiPartMessage() { const string multiPartMessage = "MIME-Version: 1.0\r\n" + "From: Nathaniel Borenstein <*****@*****.**>\r\n" + "To: Ned Freed <*****@*****.**>\r\n" + "Date: Fri, 07 Oct 1994 16:15:05 -0700 (PDT)\r\n" + "Subject: A multipart example\r\n" + "Content-Type: multipart/mixed;\r\n" + "\t\t\t\t\t\t boundary=unique-boundary-1\r\n" + "\r\n" + "This is the preamble area of a multipart message.\r\n" + "Mail readers that understand multipart format\r\n" + "should ignore this preamble.\r\n" + "\r\n" + "If you are reading this text, you might want to\r\n" + "consider changing to a mail reader that understands\r\n" + "how to properly display multipart messages.\r\n" + "\r\n" + "--unique-boundary-1\r\n" + "\r\n" + " ... Some text appears here ...\r\n" + "--unique-boundary-1\r\n" + "Content-type: text/plain; charset=US-ASCII\r\n" + "\r\n" + "This could have been part of the previous part, but\r\n" + "illustrates explicit versus implicit typing of body\r\n" + "parts.\r\n" + "--unique-boundary-1\r\n" + "Content-Type: multipart/parallel; boundary=unique-boundary-2\r\n" + "\r\n" + "--unique-boundary-2\r\n" + "Content-Type: audio/basic\r\n" + "Content-Transfer-Encoding: base64\r\n" + "\r\n" + "dGVzdCBhdWRpbw==\r\n" + // "test audio" in base64 "--unique-boundary-2\r\n" + "Content-Type: image/jpeg\r\n" + "Content-Transfer-Encoding: base64\r\n" + "\r\n" + "dGVzdCBpbWFnZQ==\r\n" + // "test image" in base64 "--unique-boundary-2--\r\n" + "\r\n" + "--unique-boundary-1\r\n" + "Content-type: text/enriched\r\n" + "\r\n" + "This is <bold><italic>enriched.</italic></bold>\r\n" + "<smaller>as defined in RFC 1896</smaller>\r\n" + "\r\n" + "Isn\'t it\r\n" + "<bigger><bigger>cool?</bigger></bigger>\r\n" + "--unique-boundary-1\r\n" + "Content-Type: message/rfc822\r\n" + "\r\n" + "From: Test <*****@*****.**>\r\n" + "To: Test <*****@*****.**>\r\n" + "Subject: Test subject\r\n" + "Content-Type: Text/plain; charset=ISO-8859-1\r\n" + "Content-Transfer-Encoding: Quoted-printable\r\n" + "\r\n" + "... Additional text in ISO-8859-1 goes here ... 3 + 5 =3D 8\r\n" + "--unique-boundary-1--"; // No special characters used - we can use ASCII to get the bytes Message message = new Message(Encoding.ASCII.GetBytes(multiPartMessage)); Assert.AreEqual("1.0", message.Headers.MimeVersion); // From Assert.AreEqual("Nathaniel Borenstein", message.Headers.From.DisplayName); Assert.AreEqual("*****@*****.**", message.Headers.From.Address); // To Assert.NotNull(message.Headers.To); Assert.AreEqual(1, message.Headers.To.Count); Assert.AreEqual("Ned Freed", message.Headers.To[0].DisplayName); Assert.AreEqual("*****@*****.**", message.Headers.To[0].Address); // Date Assert.AreEqual("Fri, 07 Oct 1994 16:15:05 -0700 (PDT)", message.Headers.Date); // -0700 is the same as adding 7 hours in the UTC DateTime Assert.AreEqual(new DateTime(1994, 10, 7, 23, 15, 05, DateTimeKind.Utc), message.Headers.DateSent); // Subject Assert.AreEqual("A multipart example", message.Headers.Subject); MessagePart part1 = message.MessagePart; Assert.AreEqual("multipart/mixed", part1.ContentType.MediaType); Assert.IsTrue(part1.IsMultiPart); Assert.NotNull(part1.MessageParts); Assert.IsNull(part1.Body); // There is a total of 5 multiparts in the first message (unique-boundary-1) Assert.AreEqual(5, part1.MessageParts.Count); // Fetch out the parts, which are checked against later System.Collections.Generic.List<MessagePart> attachments = message.FindAllAttachments(); System.Collections.Generic.List<MessagePart> textVersions = message.FindAllTextVersions(); // We are now going one level deeper into the message tree { MessagePart part1Part1 = part1.MessageParts[0]; Assert.NotNull(part1Part1); Assert.IsFalse(part1Part1.IsMultiPart); Assert.NotNull(part1Part1.Body); Assert.AreEqual("text/plain", part1Part1.ContentType.MediaType); Assert.AreEqual(" ... Some text appears here ...", part1Part1.GetBodyAsText()); // Check that the fetching algoritm for finding a plain-text version is working Assert.AreEqual(part1Part1, message.FindFirstPlainTextVersion()); // Check this message is included in the text version Assert.Contains(part1Part1, textVersions); // But not included in the attachments Assert.IsFalse(attachments.Contains(part1Part1)); // We are now going one level deeper into the message tree { MessagePart part1Part2 = part1.MessageParts[1]; Assert.NotNull(part1Part2); Assert.IsFalse(part1Part2.IsMultiPart); Assert.NotNull(part1Part2.Body); Assert.AreEqual("text/plain", part1Part2.ContentType.MediaType); Assert.AreEqual("US-ASCII", part1Part2.ContentType.CharSet); Assert.AreEqual("This could have been part of the previous part, but\r\n" + "illustrates explicit versus implicit typing of body\r\n" + "parts.", part1Part2.GetBodyAsText()); // Check this message is included in the text version Assert.Contains(part1Part2, textVersions); // But not included in the attachments Assert.IsFalse(attachments.Contains(part1Part2)); } // We are now going one level deeper into the message tree { MessagePart part1Part3 = part1.MessageParts[2]; Assert.NotNull(part1Part3); Assert.IsTrue(part1Part3.IsMultiPart); Assert.IsNotNull(part1Part3.MessageParts); Assert.IsNull(part1Part3.Body); // There is a total of message parts in part1Part3 Assert.AreEqual(2, part1Part3.MessageParts.Count); Assert.AreEqual("multipart/parallel", part1Part3.ContentType.MediaType); // Check this message is not in the text versions Assert.IsFalse(textVersions.Contains(part1Part3)); // Check this message is not included in the attachments Assert.IsFalse(attachments.Contains(part1Part3)); // We are now diving into part1Part3 multiparts - therefore going one level deeper in the message tree { MessagePart part1Part3Part1 = part1Part3.MessageParts[0]; Assert.NotNull(part1Part3Part1); Assert.IsFalse(part1Part3Part1.IsMultiPart); Assert.NotNull(part1Part3Part1.Body); Assert.AreEqual("audio/basic", part1Part3Part1.ContentType.MediaType); Assert.AreEqual(ContentTransferEncoding.Base64, part1Part3Part1.ContentTransferEncoding); Assert.AreEqual("test audio", part1Part3Part1.GetBodyAsText()); // Check this message is not in the text versions Assert.IsFalse(textVersions.Contains(part1Part3Part1)); // Check this message is included in the attachments Assert.Contains(part1Part3Part1, attachments); MessagePart part1Part3Part2 = part1Part3.MessageParts[1]; Assert.NotNull(part1Part3Part2); Assert.IsFalse(part1Part3Part2.IsMultiPart); Assert.NotNull(part1Part3Part2.Body); Assert.AreEqual("image/jpeg", part1Part3Part2.ContentType.MediaType); Assert.AreEqual(ContentTransferEncoding.Base64, part1Part3Part2.ContentTransferEncoding); Assert.AreEqual("test image", part1Part3Part2.GetBodyAsText()); // Check this message is not in the text versions Assert.IsFalse(textVersions.Contains(part1Part3Part2)); // Check this message is included in the attachments Assert.Contains(part1Part3Part2, attachments); } } // We are now going one level deeper into the message tree { MessagePart part1Part4 = part1.MessageParts[3]; Assert.NotNull(part1Part4); Assert.IsFalse(part1Part4.IsMultiPart); Assert.NotNull(part1Part4.Body); Assert.AreEqual("text/enriched", part1Part4.ContentType.MediaType); Assert.AreEqual("This is <bold><italic>enriched.</italic></bold>\r\n" + "<smaller>as defined in RFC 1896</smaller>\r\n" + "\r\n" + "Isn\'t it\r\n" + "<bigger><bigger>cool?</bigger></bigger>", part1Part4.GetBodyAsText()); // Check this message is in the text versions Assert.Contains(part1Part4, textVersions); // Check this message is not included in the attachments Assert.IsFalse(attachments.Contains(part1Part4)); } // We are now going one level deeper into the message tree { MessagePart part1Part5 = part1.MessageParts[4]; Assert.NotNull(part1Part5); Assert.IsFalse(part1Part5.IsMultiPart); Assert.NotNull(part1Part5.Body); Assert.AreEqual("message/rfc822", part1Part5.ContentType.MediaType); Assert.AreEqual("From: Test <*****@*****.**>\r\n" + "To: Test <*****@*****.**>\r\n" + "Subject: Test subject\r\n" + "Content-Type: Text/plain; charset=ISO-8859-1\r\n" + "Content-Transfer-Encoding: Quoted-printable\r\n" + "\r\n" + "... Additional text in ISO-8859-1 goes here ... 3 + 5 =3D 8", part1Part5.GetBodyAsText()); // Check this message is in the text versions Assert.Contains(part1Part5, textVersions); // Check this message is not included in the attachments Assert.IsFalse(attachments.Contains(part1Part5)); // This last part is actually a message. Lets try to parse it Message lastMessage = new Message(part1Part5.Body); // From Assert.AreEqual("Test", lastMessage.Headers.From.DisplayName); Assert.AreEqual("*****@*****.**", lastMessage.Headers.From.Address); // To Assert.NotNull(lastMessage.Headers.To); Assert.AreEqual(1, lastMessage.Headers.To.Count); Assert.AreEqual("Test", lastMessage.Headers.To[0].DisplayName); Assert.AreEqual("*****@*****.**", lastMessage.Headers.To[0].Address); // Subject Assert.AreEqual("Test subject", lastMessage.Headers.Subject); // We are now going one level deeper into the message tree { MessagePart lastPart = lastMessage.MessagePart; Assert.IsFalse(lastPart.IsMultiPart); Assert.IsNull(lastPart.MessageParts); Assert.NotNull(lastPart.Body); Assert.AreEqual(ContentTransferEncoding.QuotedPrintable, lastPart.ContentTransferEncoding); Assert.AreEqual("Text/plain", lastPart.ContentType.MediaType); Assert.AreEqual("ISO-8859-1", lastPart.ContentType.CharSet); // Notice that =3D has been decoded to = because it was QuotedPrintable encoded Assert.AreEqual("... Additional text in ISO-8859-1 goes here ... 3 + 5 = 8", lastPart.GetBodyAsText()); } } } }
private MailMessage GetMailMessageFromMessage(Message msg) { var mailMessage = msg.ToMailMessage(); mailMessage.Attachments.Clear(); var attachParts = msg.FindAllAttachments(); foreach (var part in attachParts) { var attachment = new System.Net.Mail.Attachment(new MemoryStream(part.Body), part.FileName, part.ContentType.MediaType); mailMessage.Attachments.Add(attachment); } return mailMessage; }
private void treeViewEmails_AfterSelect(object sender, TreeViewEventArgs e) { // Console.WriteLine(e.Node.Index); //init email viewer string strEmail = treeViewAccounts.SelectedNode.Text; string dirPath =AppDomain.CurrentDomain.BaseDirectory + @"data\inbox\" + strEmail; string shortFile = m_dicEmails[strEmail][e.Node.Index].file; string strUrl = "file://" + dirPath + "\\" + shortFile + ".htm"; Console.WriteLine(strUrl); Uri uri = new Uri(strUrl); webBrowserMailContent.Url = uri; //init attachment Message message = new Message(File.ReadAllBytes(dirPath + "\\" + shortFile + ".eml")); // Build up the attachment list List < MessagePart > attachments = message.FindAllAttachments(); treeViewAttach.Nodes.Clear(); foreach (MessagePart attachment in attachments) { // Add the attachment to the list of attachments TreeNode addedNode = treeViewAttach.Nodes.Add((attachment.FileName)); // Keep a reference to the attachment in the Tag property addedNode.Tag = attachment; } }
public void ReadMail() { try { Pop3Client pop3Client; pop3Client = new Pop3Client(); pop3Client.Connect(emailaccount.POP3, Convert.ToInt32(emailaccount.POP3port), emailaccount.IsSecured); pop3Client.Authenticate(emailaccount.emailid, emailaccount.password); // int MessageNum; int count = pop3Client.GetMessageCount(); var Emails = new List <POPEmail>(); int counter = 0; for (int i = count; i >= 1; i--) { OpenPop.Mime.Message message = pop3Client.GetMessage(i); POPEmail email = new POPEmail() { // MessageNumber = i, MessageNumber = message.Headers.MessageId, // message.Headers.Received. //MessageNum=MessageNumber, Subject = message.Headers.Subject, DateSent = message.Headers.DateSent, From = message.Headers.From.Address, //From = string.Format("<a href = 'mailto:{1}'>{0}</a>", message.Headers.From.DisplayName, message.Headers.From.Address), }; MessagePart body = message.FindFirstHtmlVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } else { body = message.FindFirstPlainTextVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } } List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { email.Attachments.Add(new Attachment { FileName = attachment.FileName, ContentType = attachment.ContentType.MediaType, Content = attachment.Body }); } InsertEmailMessages(email.MessageNumber, email.Subject, email.DateSent, email.From, email.Body); Emails.Add(email); counter++; //if (counter > 2) //{ // break; //} } var emails = Emails; } catch (Exception ex) { // continue; throw ex; } }
public 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 void ListMessagesMessageSelected(object sender, TreeViewEventArgs e) { // Fetch out the selected message Message message = messages[GetMessageNumberFromSelectedNode(listMessages.SelectedNode)]; // If the selected node contains a MessagePart and we can display the contents - display them if (listMessages.SelectedNode.Tag is MessagePart) { MessagePart selectedMessagePart = (MessagePart)listMessages.SelectedNode.Tag; if (selectedMessagePart.IsText) { // We can show text MessageParts messageTextBox.Text = selectedMessagePart.GetBodyAsText(); } else { // We are not able to show non-text MessageParts (MultiPart messages, images, pdf's ...) messageTextBox.Text = "<<OpenPop>> Cannot show this part of the email. It is not text <<OpenPop>>"; } } else { // If the selected node is not a subnode and therefore does not // have a MessagePart in it's Tag property, we genericly find some content to show // Find the first text/plain version MessagePart plainTextPart = message.FindFirstPlainTextVersion(); if (plainTextPart != null) { // The message had a text/plain version - show that one messageTextBox.Text = plainTextPart.GetBodyAsText(); } else { // Try to find a body to show in some of the other text versions List <MessagePart> textVersions = message.FindAllTextVersions(); if (textVersions.Count >= 1) { messageTextBox.Text = textVersions[0].GetBodyAsText(); } else { messageTextBox.Text = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>"; } } } // Clear the attachment list from any previus shown attachments listAttachments.Nodes.Clear(); // Build up the attachment list List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { // Add the attachment to the list of attachments TreeNode addedNode = listAttachments.Nodes.Add((attachment.FileName)); // Keep a reference to the attachment in the Tag property addedNode.Tag = attachment; } // Only show that attachmentPanel if there is attachments in the message bool hadAttachments = attachments.Count > 0; //attachmentPanel.Visible = hadAttachments; // Generate header table DataSet dataSet = new DataSet(); DataTable table = dataSet.Tables.Add("Headers"); table.Columns.Add("Header"); table.Columns.Add("Value"); DataRowCollection rows = table.Rows; // Add all known headers rows.Add(new object[] { "Content-Description", message.Headers.ContentDescription }); rows.Add(new object[] { "Content-Id", message.Headers.ContentId }); foreach (string keyword in message.Headers.Keywords) { rows.Add(new object[] { "Keyword", keyword }); } foreach (RfcMailAddress dispositionNotificationTo in message.Headers.DispositionNotificationTo) { rows.Add(new object[] { "Disposition-Notification-To", dispositionNotificationTo }); } foreach (Received received in message.Headers.Received) { rows.Add(new object[] { "Received", received.Raw }); } rows.Add(new object[] { "Importance", message.Headers.Importance }); rows.Add(new object[] { "Content-Transfer-Encoding", message.Headers.ContentTransferEncoding }); foreach (RfcMailAddress cc in message.Headers.Cc) { rows.Add(new object[] { "Cc", cc }); } foreach (RfcMailAddress bcc in message.Headers.Bcc) { rows.Add(new object[] { "Bcc", bcc }); } foreach (RfcMailAddress to in message.Headers.To) { rows.Add(new object[] { "To", to }); } rows.Add(new object[] { "From", message.Headers.From }); rows.Add(new object[] { "Reply-To", message.Headers.ReplyTo }); foreach (string inReplyTo in message.Headers.InReplyTo) { rows.Add(new object[] { "In-Reply-To", inReplyTo }); } foreach (string reference in message.Headers.References) { rows.Add(new object[] { "References", reference }); } rows.Add(new object[] { "Sender", message.Headers.Sender }); rows.Add(new object[] { "Content-Type", message.Headers.ContentType }); rows.Add(new object[] { "Content-Disposition", message.Headers.ContentDisposition }); rows.Add(new object[] { "Date", message.Headers.Date }); rows.Add(new object[] { "Date", message.Headers.DateSent }); rows.Add(new object[] { "Message-Id", message.Headers.MessageId }); rows.Add(new object[] { "Mime-Version", message.Headers.MimeVersion }); rows.Add(new object[] { "Return-Path", message.Headers.ReturnPath }); rows.Add(new object[] { "Subject", message.Headers.Subject }); // Add all unknown headers foreach (string key in message.Headers.UnknownHeaders) { string[] values = message.Headers.UnknownHeaders.GetValues(key); if (values != null) { foreach (string value in values) { rows.Add(new object[] { key, value }); } } } // Now set the headers displayed on the GUI to the header table we just generated gridHeaders.DataMember = table.TableName; gridHeaders.DataSource = dataSet; }
public void receiveMail(string userName, string psw, string service) { DataTable dtmail = new DataTable(); SqlDataAdapter adapteremailrecu = CreerDataAdapter(); adapteremailrecu.Fill(dtmail); //dtmail.Columns.Add(new DataColumn("mailsender", typeof(string))); //dtmail.Columns.Add(new DataColumn("mailfrom", typeof(string))); //dtmail.Columns.Add(new DataColumn("mailto", typeof(string))); //dtmail.Columns.Add(new DataColumn("mailcc", typeof(string))); //dtmail.Columns.Add(new DataColumn("maildateTime", typeof(string))); //dtmail.Columns.Add(new DataColumn("mailsubject", typeof(string))); //dtmail.Columns.Add(new DataColumn("mailbodySimple", typeof(string))); //dtmail.Columns.Add(new DataColumn("mailbody", typeof(string))); //dtmail.Columns.Add(new DataColumn("pathAttachmentFile", typeof(string))); Pop3Client receiveclient = new Pop3Client(); if (receiveclient.Connected) { receiveclient.Disconnect(); } receiveclient.Connect(service, 995, true); receiveclient.Authenticate(userName, psw); int messageCount = receiveclient.GetMessageCount(); List <string> ids = receiveclient.GetMessageUids(); for (int i = 0; i < messageCount; i++) { if (dtmail.Select("mailID='@id'".Replace("@id", ids[i])).Length < 1) { DataRow dtr = dtmail.NewRow(); OpenPop.Mime.Message message = receiveclient.GetMessage(i + 1); string sender = message.Headers.From.DisplayName; string from = message.Headers.From.Address; string subject = message.Headers.Subject; List <string> keyw = message.Headers.Keywords; List <RfcMailAddress> mailCc = message.Headers.Cc; List <RfcMailAddress> mailTo = message.Headers.To; DateTime dateSent = message.Headers.DateSent; MessagePart msgPart = message.MessagePart; string body = ""; string bodys = ""; if (msgPart.IsText) { body = msgPart.GetBodyAsText(); bodys = body; } else if (msgPart.IsMultiPart) { MessagePart plainTextPart = message.FindFirstPlainTextVersion(); MessagePart plainHtmlPart = message.FindFirstHtmlVersion(); if (plainTextPart != null) { // The message had a text/plain version - show that one //TextBox1.Text = plainTextPart.GetBodyAsText(); body = plainHtmlPart.GetBodyAsText(); bodys = plainTextPart.GetBodyAsText(); //byte[] bodyy = plainTextPart.MessageParts[0].MessageParts.ToArray(); //string html = Encoding.GetEncoding("gb18030").GetString(bodyy); } else { // Try to find a body to show in some of the other text versions List <MessagePart> textVersions = message.FindAllTextVersions(); if (textVersions.Count >= 1) { body = textVersions[0].GetBodyAsText(); bodys = body; } } } List <MessagePart> attachments = message.FindAllAttachments(); string pathAttachmentFile = ""; if (attachments.Count > 0) { string dir = Server.MapPath("~/attchment/"); if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); } foreach (MessagePart attachment in attachments) { string newFileName = attachment.FileName; string path = dir + newFileName; WebClient myWebClient = new WebClient(); myWebClient.Credentials = CredentialCache.DefaultCredentials; try { Stream postStream = myWebClient.OpenWrite(path, "PUT"); if (postStream.CanWrite) { postStream.Write(attachment.Body, 0, attachment.Body.Length); } else { //MessageBox.Show("Web服务器文件目前不可写入,请检查Web服务器目录权限设置!","系统提示",MessageBoxButtons.OK,MessageBoxIcon.Information); } postStream.Close();//关闭流 pathAttachmentFile = path + ";" + pathAttachmentFile; } catch { ; } } attachments.Clear(); } string bodySimple = ""; if (bodys.Length > 30) { bodySimple = bodys.Substring(0, 30); } else { bodySimple = bodys.Substring(0, bodys.Length); } string listCc = ""; foreach (RfcMailAddress address in mailCc) { listCc = listCc + address.Address.ToString() + ";"; } string listTo = ""; foreach (RfcMailAddress address in mailTo) { listTo = listTo + address.ToString() + ";"; } body = body.Replace(@"cid:", @"/attchment/"); dtr["mailID"] = ids[i]; dtr["fk_userid"] = 1; dtr["mailsender"] = sender; dtr["mailfrom"] = from; dtr["mailto"] = listTo; dtr["mailcc"] = listCc; dtr["maildateTime"] = dateSent.ToString("yyyy-MM-dd HH:mm"); dtr["mailsubject"] = subject; dtr["mailbodySimple"] = bodySimple; dtr["mailbody"] = body; dtr["pathAttachmentFile"] = pathAttachmentFile; dtmail.Rows.Add(dtr); } } dtmail.DefaultView.Sort = "maildateTime DESC"; adapteremailrecu.Update(dtmail); }
/// <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(); }
//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 ReadMail(Object threadContext) { StringBuilder builder = new StringBuilder(); MessagePart plaintext = _NewMessage.FindFirstPlainTextVersion(); string result = ""; if (plaintext != null) { // We found some plaintext! builder.Append(plaintext.GetBodyAsText()); result = builder.ToString(); _newMessageinPlainText = result; } else { // Might include a part holding html instead MessagePart html = _NewMessage.FindFirstHtmlVersion(); if (html != null) { // We found some html! builder.Append(html.GetBodyAsText()); result = StripHTML(builder.ToString()); _newMessageinPlainText = result; } } int Who = FromWho(_NewMessage.Headers.From.Address); if (Who == -1) //cannot download attachement from UNKNOWN { ReadingOrderThruEmail(_NewMessage.Headers.From.Address, _NewMessage.Headers.Subject, result); _doneevent.Set(); return; } // ### DELETED MODULE FOR PEPPER #### string replyMSG; foreach (MessagePart attachment in _NewMessage.FindAllAttachments()) { //upgrade one at a time, cannot upgrade both bios and pepper in one time. switch (attachment.FileName) { case Variables.FilenameUpdateBios: //BIOS Update logger.Trace("Got bios Update file."); File.WriteAllBytes(Variables.PathUpdateBios, attachment.Body); pepThread th = new pepThread(); //th.UpdateBios(); <----- need to email logger.Debug("Need to restart pepper."); Variables.NeedtoRestart = true; if (Variables.Contacts[Who].Closeness >= 75) { replyMSG = "Got the Bios Update " + Variables.Contacts[Who].PetName + "!!!"; } else { replyMSG = "Got the Bios Update " + Variables.Contacts[Who].FirstName + "!!!"; } //sendEmailHTML(_NewMessage.Headers.From.Address, Variables.Contacts[Who].FirstName + " " + Variables.Contacts[Who].LastName, "Re: BIOS Update", replyMSG); _doneevent.Set(); return; //break; case Variables.FilenameUpdatePepper: //UPDATE PEPPER "newme.pep" logger.Debug("Got newme.pep PEPPER UPDATE FILE"); File.WriteAllBytes(Variables.PathUpdatePepper, attachment.Body); logger.Debug("Need to restart pepper."); Variables.NeedtoRestart = true; if (Variables.Contacts[Who].Closeness >= 75) { replyMSG = "Got the New Dress " + Variables.Contacts[Who].PetName + "!!!"; } else { replyMSG = "Got the New Dress " + Variables.Contacts[Who].FirstName + "!!!"; } //sendEmailHTML(_NewMessage.Headers.From.Address, Variables.Contacts[Who].FirstName + " " + Variables.Contacts[Who].LastName, "Re: Pepper Upgrade", replyMSG); _doneevent.Set(); return; //break; } /* ### DELETED MODULE FOR PEPPER #### ### DELETED MODULE FOR PEPPER #### */ } /* ### DELETED MODULE FOR PEPPER#### ### DELETED MODULE FOR PEPPER #### */ ReadingOrderThruEmail(_NewMessage.Headers.From.Address, _NewMessage.Headers.Subject, result); _doneevent.Set(); }
private void ListMessagesMessageSelected(object sender, TreeViewEventArgs e) { // Fetch out the selected message Message message = messages[GetMessageNumberFromSelectedNode(treeView1.SelectedNode)]; // If the selected node contains a MessagePart and we can display the contents - display them if (treeView1.SelectedNode.Tag is MessagePart) { MessagePart selectedMessagePart = (MessagePart)treeView1.SelectedNode.Tag; if (selectedMessagePart.IsText) { // We can show text MessageParts webBrowser1.DocumentText = selectedMessagePart.GetBodyAsText(); // webBrowser1.Navigating += WebBrowser1_Navigating; textBox1.Text = selectedMessagePart.GetBodyAsText(); } else { // We are not able to show non-text MessageParts (MultiPart messages, images, pdf's ...) textBox1.Text = "<<OpenPop>>Не удается отобразить эту часть сообщения электронной почты. Это не текст<<OpenPop>>"; } } else { // If the selected node is not a subnode and therefore does not // have a MessagePart in it's Tag property, we genericly find some content to show // Find the first text/plain version MessagePart plainTextPart = message.FindFirstPlainTextVersion(); if (plainTextPart != null) { // The message had a text/plain version - show that one textBox1.Text = plainTextPart.GetBodyAsText(); } else { // Try to find a body to show in some of the other text versions List <MessagePart> textVersions = message.FindAllTextVersions(); if (textVersions.Count >= 1) { textBox1.Text = textVersions[0].GetBodyAsText(); } else { textBox1.Text = "<<OpenPop>> не могу найти текстовую версию тела в это сообщение, чтобы показать <<OpenPop>>"; } } } // Clear the attachment list from any previus shown attachments treeView2.Nodes.Clear(); // Build up the attachment list List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { // Add the attachment to the list of attachments TreeNode addedNode = treeView2.Nodes.Add((attachment.FileName)); // Keep a reference to the attachment in the Tag property addedNode.Tag = attachment; } // Only show that attachmentPanel if there is attachments in the message bool hadAttachments = attachments.Count > 0; //attachmentPanel.Visible = hadAttachments; }
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; } }
}//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
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 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; } }
public void GetAttach(DateTime date)//получение аттачментов { string s = @"Data Source=.\NO;AttachDbFilename=C:\Users\User\Documents\GitHub\kurs_project\myDataBase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; DataSet ds = new DataSet(); SqlDataAdapter daBranch = new SqlDataAdapter("Select * from Branch", s); SqlDataAdapter daProv = new SqlDataAdapter("Select * from Provisioner", s); daBranch.Fill(ds, "Branch"); daProv.Fill(ds, "Provisioner"); DataTable dtBranch = ds.Tables["Branch"]; DataTable dtProv = ds.Tables["Provisioner"]; var emailBrach = dtBranch.AsEnumerable() .Select(t => t.Field <string>("email")); /*foreach (var i in emailBrach) * System.Windows.Forms.MessageBox.Show(i.ToString());*/ var emailProv = dtProv.AsEnumerable() .Select(t => t.Field <string>("email")); using (Pop3Client client = new Pop3Client()) { client.Connect("pop3.mail.ru", 110, false); client.Authenticate("*****@*****.**", "mag17012014"); List <string> listIdMsg = client.GetMessageUids();//получаем список id всех писем for (int i = 1; i <= listIdMsg.Count(); i++) { OpenPop.Mime.Message msg = client.GetMessage(i); //получаум письмо по Id; string address = msg.Headers.From.Address.ToString(); //получаем адрес отправителя DateTime dateMsg = DateTime.Parse(msg.Headers.Date); //получаем дату сообщения List <MessagePart> listAttach = msg.FindAllAttachments(); //получаем все аттачменты сообщения foreach (var elem in emailBrach) { if (address.Substring(0, address.Length) == elem && dateMsg.ToString().Substring(0, 10) == date.ToString().Substring(0, 10)) { if (listAttach.Count > 0) { foreach (MessagePart attach in listAttach) { string filePath = Path.Combine(@"D:\MailBranch", attach.FileName); attach.Save(new FileInfo(filePath)); } } } } foreach (var elem in emailProv) { if (address.Substring(0, address.Length) == elem && dateMsg.ToString().Substring(0, 10) == date.ToString().Substring(0, 10)) { if (listAttach.Count > 0) { foreach (MessagePart attach in listAttach) { string filePath = Path.Combine(@"D:\MailProvisioner", attach.FileName); attach.Save(new FileInfo(filePath)); } } } } } } }
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! "); } }
/////////////////////////////////////////////////////////////////////// public static void add_attachments(Message message, int bugid, int parent_postid, IIdentity identity) { foreach (MessagePart attachment in message.FindAllAttachments()) { add_attachment(attachment.FileName, attachment, bugid, parent_postid, identity); } }
public override ActionResult Execute(ISpecialExecutionTaskTestAction testAction) { String host = testAction.GetParameterAsInputValue("host", false).Value; if (string.IsNullOrEmpty(host)) { throw new ArgumentException(string.Format("Es muss ein POP3 Host angegeben sein.")); } String strPort = testAction.GetParameterAsInputValue("port", false).Value; if (string.IsNullOrEmpty(strPort)) { throw new ArgumentException(string.Format("Es muss ein POP3 Port angegeben sein.")); } int port = int.Parse(strPort); String user = testAction.GetParameterAsInputValue("user", false).Value; if (string.IsNullOrEmpty(user)) { throw new ArgumentException(string.Format("Es muss ein User angegeben werden.")); } String password = testAction.GetParameterAsInputValue("password", false).Value; if (string.IsNullOrEmpty(password)) { throw new ArgumentException(string.Format("Es muss ein Passwort angegeben werden.")); } pop3Client = new Pop3Client(); messages = new Dictionary <int, Message>(); logMessages = ""; int success = 0; try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(host, port, false); pop3Client.Authenticate(user, password); int count = pop3Client.GetMessageCount(); messages.Clear(); int fail = 0; for (int i = count; i >= 1; i -= 1) { try { // Application.DoEvents(); string body; Message message = pop3Client.GetMessage(i); MessageHeader headers = pop3Client.GetMessageHeaders(i); string subject = headers.Subject; logMessages = logMessages + "- " + i + " -" + subject + "\n"; MessagePart plainTextPart = message.FindFirstPlainTextVersion(); if (plainTextPart != null) { // The message had a text/plain version - show that one body = plainTextPart.GetBodyAsText(); } else { // Try to find a body to show in some of the other text versions List <MessagePart> textVersions = message.FindAllTextVersions(); if (textVersions.Count >= 1) { body = textVersions[0].GetBodyAsText(); } else { body = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>"; } } // Build up the attachment list List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { } // Add the message to the dictionary from the messageNumber to the Message messages.Add(i, message); success++; } catch (Exception e) { fail++; } } } catch (InvalidLoginException) { //MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication"); } catch (PopServerNotFoundException) { //MessageBox.Show(this, "The server could not be found", "POP3 Retrieval"); } catch (PopServerLockedException) { //MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked"); } catch (LoginDelayException) { //MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay"); } catch (Exception e) { return(new PassedActionResult("Error occurred retrieving mail: " + e.Message)); } finally { pop3Client.Disconnect(); } return(new PassedActionResult("Mails found: " + success + "\n" + logMessages)); }