Esempio n. 1
0
 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;
     }
 }
Esempio n. 2
0
 public void Receive(string mailUser, string mailUserPwd, DataGridView dataGrid)
 {
     try
     {
         Pop3Client    client  = new Pop3Client();
         StringBuilder builder = new StringBuilder();
         client.Connect("pop-mail.outlook.com", 995, true);
         client.Authenticate(mailUser, mailUserPwd);
         var       count = client.GetMessageCount();
         DataTable dt    = new DataTable("Inbox");
         dt.Columns.Add("Subject", typeof(string));
         dt.Columns.Add("Sender", typeof(string));
         dt.Columns.Add("Date", typeof(DateTime));
         dt.Columns.Add("Body", typeof(string));
         for (int i = 1; i <= count; i++)
         {
             Application.DoEvents();
             string      body;
             Message     message   = client.GetMessage(i);
             MessagePart planeText = message.FindFirstHtmlVersion();
             if (planeText != null)
             {
                 // The message had a text/plain version - show that one
                 body = planeText.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>>";
                 }
             }
             dt.Rows.Add(message.Headers.Subject, message.Headers.From, message.Headers.DateSent, body);
         }
         dataGrid.DataSource = dt;
         dataGrid.Sort(dataGrid.Columns[2], ListSortDirection.Descending);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Esempio n. 3
0
        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());
        }
Esempio n. 4
0
        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);
        }
Esempio n. 6
0
        public void TestContentTypeWithLargeCharactersCanStillBeFound()
        {
            const string messagePartContent =
                "Content-Type: TEXT/PLAIN\r\n" +
                "\r\n" + // End of message headers
                "foo";

            Message message = new Message(Encoding.ASCII.GetBytes(messagePartContent));

            // Cna be found
            MessagePart textHtml = message.FindFirstPlainTextVersion();
            Assert.NotNull(textHtml);

            Assert.AreEqual("foo", textHtml.GetBodyAsText());

            // Can still be found
            System.Collections.Generic.List<MessagePart> messageParts = message.FindAllTextVersions();
            Assert.IsNotEmpty(messageParts);
            Assert.AreEqual(1, messageParts.Count);
            Assert.AreEqual(textHtml, messageParts[0]);
        }
Esempio n. 7
0
        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());
                    }
                }
            }
        }
Esempio n. 8
0
        /// <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("Ошибка проверки подписи файла письма!", "Ошибка");
                    }
                }
            }
        }
Esempio n. 9
0
        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);
        }
Esempio n. 10
0
        /// <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();
        }
Esempio n. 11
0
        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;
        }
Esempio n. 12
0
        }//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
Esempio n. 13
0
        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));
            }
        }
Esempio n. 14
0
        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));
        }