示例#1
0
        // 下载附件
        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);
            }
        }
示例#2
0
        private void listAttachments_AfterSelect(object sender, TreeViewEventArgs e)
        {
            MessagePart attachment = (MessagePart)listAttachments.SelectedNode.Tag;

            if (attachment != null)
            {
                saveFile.FileName = attachment.FileName;
                DialogResult result = saveFile.ShowDialog();
                if (result != DialogResult.OK)
                {
                    return;
                }
                FileInfo file = new FileInfo(saveFile.FileName);

                if (file.Exists)
                {
                    file.Delete();
                }
                try
                {
                    attachment.Save(file);

                    MessageBox.Show(this, "Attachment saved successfully");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "Attachment saving failed. Exception message: " + ex.Message);
                }
            }
            else
            {
                MessageBox.Show(this, "Attachment object was null!");
            }
        }
示例#3
0
        /// <summary>
        /// Example showing:
        ///  - how to a find plain text version in a Message
        ///  - how to save MessageParts to file
        /// </summary>
        /// <param name="message">The message to examine for plain text</param>
        public static void GetDataWithTypeInMessage(Message message, MessageTypes type)
        {
            MessagePart messagePart = null;

            if (type == MessageTypes.PlainText)
            {
                messagePart = message.FindFirstPlainTextVersion();
            }
            else if (type == MessageTypes.Html)
            {
                messagePart = message.FindFirstHtmlVersion();
            }
            else if (type == MessageTypes.XmlDocument)
            {
                messagePart = message.FindFirstMessagePartWithMediaType("text/xml");
            }

            if (messagePart != null)
            {
                if (type == MessageTypes.XmlDocument)
                {
                    string xmlString           = messagePart.GetBodyAsText();
                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.LoadXml(xmlString);
                    doc.Save("test.xml");
                }
                else
                {
                    // Save the plain text to a file, database or anything you like
                    messagePart.Save(new FileInfo("text.txt"));
                }
            }
        }
示例#4
0
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        List <string>  seenUids = new List <string>();
        List <Message> allmes   = new List <Message>();

        allmes = FetchUnseenMessages("pop.gmail.com", 995, true, "*****@*****.**", "vizitrace", seenUids);
        int i     = 0;
        int count = allmes.Count();

        if (allmes.Count == 0)
        {
            Label1.Text = "Waiting For Email";
        }
        else
        {
            Timer1.Enabled = false;
            string      dirname = dattime();
            MessagePart html    = allmes[allmes.Count() - 1].FindFirstHtmlVersion();
            if (html != null)
            {
                Label1.Text = "Measurement Recieved";
                html.Save(new FileInfo(Server.MapPath("~/App_Data/Email" + dirname + ".txt")));
                string emaildir = "~/App_Data/Email" + dirname + ".txt";
                i++;
                livertr(emaildir);
            }
        }
    }
示例#5
0
		/// <summary>
		/// Example showing:
		///  - how to a find plain text version in a Message
		///  - how to save MessageParts to file
		/// </summary>
		/// <param name="message">The message to examine for plain text</param>
		public static void FindPlainTextInMessage(Message message)
		{
			MessagePart plainText = message.FindFirstPlainTextVersion();
			if(plainText != null)
			{
				// Save the plain text to a file, database or anything you like
				plainText.Save(new FileInfo("plainText.txt"));
			}
		}
示例#6
0
		/// <summary>
		/// Example showing:
		///  - how to find a html version in a Message
		///  - how to save MessageParts to file
		/// </summary>
		/// <param name="message">The message to examine for html</param>
		public static void FindHtmlInMessage(Message message)
		{
			MessagePart html = message.FindFirstHtmlVersion();
			if (html != null)
			{
				// Save the plain text to a file, database or anything you like
				html.Save(new FileInfo("html.txt"));
			}
		}
示例#7
0
        private void FindPlainTextInMessage(OpenPop.Mime.Message message)
        {
            MessagePart plainText = message.FindFirstPlainTextVersion();

            if (plainText != null)
            {
                // Save the plain text to a file, database or anything you like
                plainText.Save(new FileInfo(@"Texter.txt"));
                FileStream   reder  = new FileStream(@"Texter.txt", FileMode.Open);
                StreamReader reader = new StreamReader(reder);
                string       bufs   = reader.ReadToEnd();
                BufferMailText = bufs;
                reder.Close();
                File.Delete(@"Texter.txt");
                FlowDocument document  = new FlowDocument();
                Paragraph    paragraph = new Paragraph();
                paragraph.Inlines.Add(new Bold(new Run(bufs)));
                document.Blocks.Add(paragraph);
                TextMessag.Document = document;
            }
            else
            {
                plainText = message.FindFirstHtmlVersion();
                plainText.Save(new FileInfo(@"Texter.txt"));
                FileStream   reder  = new FileStream(@"Texter.txt", FileMode.Open);
                StreamReader reader = new StreamReader(reder);
                string       bufs   = reader.ReadToEnd();
                bufs           = bufs.Replace("<br>", "\n");
                bufs           = bufs.Replace("<HTML>", ""); bufs = bufs.Replace("</HTML>", "");
                bufs           = bufs.Replace("<BODY>", ""); bufs = bufs.Replace("</BODY>", "");
                bufs           = bufs.Replace("<p>", ""); bufs = bufs.Replace("</p>", "");
                bufs           = bufs.Replace("<div>", ""); bufs = bufs.Replace("</div>", "");
                BufferMailText = bufs;
                reder.Close();
                File.Delete(@"Texter.txt");
                FlowDocument document  = new FlowDocument();
                Paragraph    paragraph = new Paragraph();
                paragraph.Inlines.Add(new Bold(new Run(bufs)));
                document.Blocks.Add(paragraph);
                TextMessag.Document = document;
            }
        }
示例#8
0
        public void downloadFile(MessagePart ado)
        {
            string attachmentdirectory = @"c:\temp\mail\attachments";

            Directory.CreateDirectory(attachmentdirectory);
            //overwrites MessagePart.Body with attachment
            File.WriteAllBytes(ado.FileName.Trim(), ado.Body);
            // Console.WriteLine(ado.GetBodyAsText());
            // Save the file
            ado.Save(new System.IO.FileInfo(System.IO.Path.Combine(attachmentdirectory, ado.FileName.Trim())));
        }
    /// <summary>
    /// This method is the heavy lifter to get all email messages from a POP3 account. This is called by the GetAllEmailsFromAnEmailAccount method
    /// in the Core.cs
    /// </summary>
    /// <param name="hostname">Domain</param>
    /// <param name="port">Usually always 110 for Pop3</param>
    /// <param name="useSsl">SSL true or false</param>
    /// <param name="username">Email Account</param>
    /// <param name="password">Password for the account</param>
    /// <param name="delete">Delete all emails from the account after the account's emails are saved.</param>
    /// <returns></returns>
    public static List <Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password, bool delete = false)
    {
        using (Pop3Client client = new Pop3Client())
        {
            client.Connect(hostname, port, useSsl);
            client.Authenticate(username, password);
            int messageCount = client.GetMessageCount();

            List <Message> allMessages = new List <Message>(messageCount);

            // Messages are numbered in the interval: [1, messageCount]
            // Ergo: message numbers are 1-based.
            // Most servers give the latest message the highest number
            for (int i = messageCount; i > 0; i--)
            {
                allMessages.Add(client.GetMessage(i));
            }

            int number = 1;

            // Now return the fetched messages
            foreach (var emailText in allMessages)
            {
                DateTime date = DateTime.Today;
                var      dir  = $@"c:\Automation Logs\{date:MM.dd.yyyy}\Emails\";

                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                MessagePart plainText = emailText.FindFirstPlainTextVersion();
                plainText.Save(new FileInfo(dir + $"\\Email {number}.txt"));
                number++;
            }

            // Delete all messages from the account
            if (delete == true)
            {
                try
                {
                    client.DeleteAllMessages();
                }
                catch (Exception _ex)
                {
                    Console.WriteLine("Error occured trying to delete with FetchAllMessages method." + Environment.NewLine + _ex);
                }
            }

            return(allMessages);
        }
    }
示例#10
0
 /// <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));
         }
     }
 }
示例#11
0
        //private void WebBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        //{
        //    System.Windows.Forms.HtmlDocument document =
        //    this.webBrowser1.Document;

        //    if (document != null && document.All["userName"] != null &&
        //    String.IsNullOrEmpty(
        //    document.All["userName"].GetAttribute("value")))
        //    {
        //        e.Cancel = true;
        //        System.Windows.Forms.MessageBox.Show(
        //        "You must enter your name before you can navigate to " +
        //        e.Url.ToString());
        //    }
        //}

        private void ListAttachmentsAttachmentSelected(object sender, TreeViewEventArgs e)
        {
            // Fetch the attachment part which is currently selected
            MessagePart attachment = (MessagePart)treeView2.SelectedNode.Tag;

            if (attachment != null)
            {
                SaveFileDialog sav = new SaveFileDialog();
                sav.FileName = attachment.FileName;
                DialogResult result = sav.ShowDialog();
                if (result != DialogResult.OK)
                {
                    return;
                }

                // Now we want to save the attachment
                FileInfo file = new FileInfo(sav.FileName);

                // 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);

                    MessageBox.Show(this, "Вложение успешно сохранено");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "Ошибка сохранения вложения: " + ex.Message);
                }
            }
            else
            {
                MessageBox.Show(this, "Вложения нет");
            }
        }
示例#12
0
        private void ListAttachmentsAttachmentSelected(object sender, TreeViewEventArgs args)
        {
            // Fetch the attachment part which is currently selected
            MessagePart attachment = (MessagePart)listAttachments.SelectedNode.Tag;

            if (attachment != null)
            {
                saveFile.FileName = attachment.FileName;
                DialogResult result = saveFile.ShowDialog();
                if (result != DialogResult.OK)
                {
                    return;
                }

                // Now we want to save the attachment
                FileInfo file = new FileInfo(saveFile.FileName);

                // 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);

                    MessageBox.Show(this, "Attachment saved successfully");
                }
                catch (Exception e)
                {
                    MessageBox.Show(this, "Attachment saving failed. Exception message: " + e.Message);
                }
            }
            else
            {
                MessageBox.Show(this, "Attachment object was null!");
            }
        }
示例#13
0
        public void TestSaveToFile()
        {
            const string base64 =
                "JVBERi0xLjUNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBlL0NhdGFsb2cvUGFnZXMgMiAwIFIv\r\n" +
                "TGFuZyhkYS1ESykgL1N0cnVjdFRyZWVSb290IDE1IDAgUi9NYXJrSW5mbzw8L01hcmtlZCB0\r\n" +
                "cnVlPj4+Pg0KZW5kb2JqDQoyIDAgb2JqDQo8PC9UeXBlL1BhZ2VzL0NvdW50IDEvS2lkc1sg\r\n" +
                "MyAwIFJdID4+DQplbmRvYmoNCjMgMCBvYmoNCjw8L1R5cGUvUGFnZS9QYXJlbnQgMiAwIFIv\r\n" +
                "UmVzb3VyY2VzPDwvRm9udDw8L0YxIDUgMCBSL0YyIDcgMCBSL0YzIDkgMCBSPj4vUHJvY1Nl\r\n" +
                "dFsvUERGL1RleHQvSW1hZ2VCL0ltYWdlQy9JbWFnZUldID4+L01lZGlhQm94WyAwIDAgNTk0\r\n" +
                "Ljk2IDg0Mi4wNF0gL0NvbnRlbnRzIDQgMCBSL0dyb3VwPDwvVHlwZS9Hcm91cC9TL1RyYW5z\r\n" +
                "cGFyZW5jeS9DUy9EZXZpY2VSR0I+Pi9UYWJzL1MvU3RydWN0UGFyZW50cyAwPj4NCmVuZG9i";

            const string partPdf =
                "Content-Type: application/pdf;\r\n" +
                " name=\"=?ISO-8859-1?Q?=D8nskeliste=2Epdf?=\"\r\n" +
                "Content-Transfer-Encoding: base64\r\n" +
                "\r\n" +
                base64;

            // Base 64 is only in ASCII
            Message message = new Message(Encoding.ASCII.GetBytes(partPdf));

            MessagePart messagePart = message.MessagePart;

            // Check the headers
            Assert.AreEqual("application/pdf", messagePart.ContentType.MediaType);
            Assert.AreEqual(ContentTransferEncoding.Base64, messagePart.ContentTransferEncoding);
            Assert.AreEqual("Ønskeliste.pdf", messagePart.ContentType.Name);

            byte[] correctBytes = Convert.FromBase64String(base64);
            // This will fail if US-ASCII is assumed on the bytes when decoded from base64 to bytes
            Assert.AreEqual(correctBytes, messagePart.Body);

            FileInfo testFile = new FileInfo("test_message_save_.testFile");

            messagePart.Save(testFile);

            byte[] fileBytes = File.ReadAllBytes(testFile.ToString());
            testFile.Delete();

            Assert.AreEqual(correctBytes, fileBytes);
        }
 public void Execute(object parameter)
 {
     try {
         var       tempPath = Path.GetTempPath();
         const int a        = 1;
         var       fileName = _part.FileName;
         while (File.Exists(tempPath + fileName))
         {
             fileName = _part.FileName.Insert(_part.FileName.LastIndexOf(".", StringComparison.Ordinal) - 1, string.Format("{0}", a));
         }
         _part.Save(new FileInfo(fileName));
         var process = new Process {
             StartInfo = new ProcessStartInfo(fileName)
         };
         process.Start();
         process.Exited += (sender, e) => File.Delete(fileName);
     } catch (Exception ex) {
         MessageBox.Show("something went wrong\n" + ex);
     }
 }
示例#15
0
        static void SaveMessages(Account acc, List <Message> messages)
        {
            if (Directory.Exists("Mailbox") == false)
            {
                Directory.CreateDirectory("Mailbox");
            }


            foreach (var msg in messages)
            {
                string senderMail = CreateDirectory(msg, acc.Login);

                string filePath = $"Mailbox/{acc.Login}/{senderMail}/" +
                                  msg.Headers.DateSent.Day + "_" +
                                  msg.Headers.DateSent.Month + "_" +
                                  msg.Headers.DateSent.Year + "-" +
                                  msg.Headers.DateSent.Hour + "_" +
                                  msg.Headers.DateSent.Minute + "_" +
                                  msg.Headers.DateSent.Second;



                if (File.Exists(filePath + ".txt") == true || File.Exists(filePath + ".html") || File.Exists(filePath + ".xml"))
                {
                    filePath = NormalizeCloneName(filePath);
                }

                MessagePart plainText = msg.FindFirstPlainTextVersion();
                if (plainText != null)
                {
                    plainText.Save(new FileInfo($"{filePath}.txt"));
                }

                MessagePart html = msg.FindFirstHtmlVersion();
                if (html != null)
                {
                    html.Save(new FileInfo($"{filePath}.html"));
                    continue;
                }

                MessagePart xml = msg.FindFirstMessagePartWithMediaType("text/xml");
                if (xml != null)
                {
                    string xmlString           = xml.GetBodyAsText();
                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.LoadXml(xmlString);
                    doc.Save($"{filePath}.xml");
                    continue;
                }

                try
                {
                    File.WriteAllText($"{filePath}.txt", Encoding.ASCII.GetString(msg.RawMessage));
                }
                catch
                {
                    Utils.WriteLog($"Cannot save message with ID {msg.Headers.MessageId}", Form1.LogControl);
                }
            }

            Utils.WriteLog($"Сохранено {messages.Count} писем", Form1.LogControl);
        }