Esempio n. 1
0
        public static void ConnectToGmailAccountAndGetOrUpdateMails()
        {
            // Gmail IMAP4 server is "imap.gmail.com"
            MailServer oServer = new MailServer("imap.gmail.com", "*****@*****.**", "maker2018", ServerProtocol.Imap4);
            MailClient oClient = new MailClient("TryIt");

            // Set SSL connection,
            oServer.SSLConnection = true;

            // Set 993 IMAP4 port
            oServer.Port = 993;


            try
            {
                oClient.Connect(oServer);
                MailInfo[] infos = oClient.GetMailInfos();
                lastMailsKnownNumber = infos.Length;



                //si le tableau des emails est vide telecharger tout les emails maintenant dans un tabelau et une liste
                if (listMails.Count == 0)
                {
                    //mails = oClient.FetchMails(false);
                    for (int i = 0; i < infos.Length; i++)
                    {
                        Mail tempMail = oClient.GetMail(infos[i]);
                        //tempMail.Subject = tempMail.Subject.Replace("(Trial Version)", "");
                        tempMail.HtmlBody.Remove(0, 25);
                        // tempMail.Tag =i;
                        //tempMail.HtmlBody.Replace("</body></html>", "");
                        listMails.Add(oClient.GetMail(infos[i]));
                    }
                }
                else // sinon , telecharger seulement les nouveau mails et les ajouter dans le tableau et la liste
                {
                    for (int i = listMails.Count; i < infos.Length; i++)
                    {
                        //mails[i] = oClient.GetMail(infos[i]);
                        Mail newMail = oClient.GetMail(infos[i]);
                        //newMail.Subject =newMail.Subject.Replace("(Trial Version)", "");
                        newMail.HtmlBody.Remove(0, 25);
                        //newMail.Tag = i;
                        // newMail.HtmlBody.Replace("</body></html>", "");
                        listMails.Add(newMail);
                        System.Console.WriteLine("New mail From=" + newMail.From + " Subject=" + newMail.Subject + " Body=" + newMail.TextBody);
                    }
                }
            }
            catch (Exception e)
            { }
        }
Esempio n. 2
0
        private void btnGetMail_Click(object sender, EventArgs e)
        {
            txtTrangthai.Text = "Đang Get Mail....";
            mailbox           = String.Format("{0}\\inbox", curpath);
            try
            {
                oClient.Connect(oServer);

                MailInfo[] infos = oClient.GetMailInfos();
                for (int i = 0; i < 5; i++)
                {
                    MailInfo info = infos[i];

                    /* Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
                     *   info.Index, info.Size, info.UIDL);*/

                    // Download email from GMail IMAP4 server
                    Mail oMail = oClient.GetMail(info);


                    /*  Console.WriteLine("From: {0}", oMail.From.ToString());
                     * Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
                     * Console.WriteLine("Body Text: {0}\r\n", oMail.TextBody);
                     */

                    ListViewItem lstinfo = new ListViewItem();
                    lstinfo.Text = oMail.Subject;
                    lstEmail.Items.Add(lstinfo);

                    // Generate an email file name based on date time.
                    System.DateTime d = System.DateTime.Now;
                    System.Globalization.CultureInfo cur = new
                                                           System.Globalization.CultureInfo("en-US");
                    string sdate    = d.ToString("yyyyMMddHHmmss", cur);
                    string fileName = String.Format("{0}\\{1}{2}{3}.eml",
                                                    mailbox, sdate, d.Millisecond.ToString("d3"), i);

                    // Save email to local disk
                    oMail.SaveAs(fileName, true);

                    // Mark email as deleted in GMail account.
                    //oClient.Delete(info);
                    oClient.MarkAsRead(info, true);
                }
                txtTrangthai.Text = "Get mail Thành Công...";
                // Quit and pure emails marked as deleted from Gmail IMAP4 server.
                oClient.Quit();
            }
            catch (Exception ep)
            {
                txtTrangthai.Text = ep.Message;
            }
        }
Esempio n. 3
0
        private void Form1_Load(object sender, EventArgs e)
        {
            string curpath = Directory.GetCurrentDirectory();
            string mailbox = String.Format("{0}\\inbox", curpath);

            // If the folder is not existed, create it.
            if (!Directory.Exists(mailbox))
            {
                Directory.CreateDirectory(mailbox);
            }

            MailServer oServer = new MailServer("pop.gmail.com",
                                                "*****@*****.**", "jarvis99", ServerProtocol.Pop3);
            MailClient oClient = new MailClient("TryIt");

            // If your POP3 server requires SSL connection,
            // Please add the following codes:
            oServer.SSLConnection = true;
            oServer.Port          = 995;
            MessageBox.Show("Connection opened");
            try
            {
                oClient.Connect(oServer);
                MailInfo[] infos = oClient.GetMailInfos();
                MessageBox.Show("Mail information received");
                MessageBox.Show(infos.ToString());
                for (int i = 0; i < infos.Length; i++)
                {
                    MailInfo info = infos[i];
                    //Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
                    //  info.Index, info.Size, info.UIDL);

                    // Receive email from POP3 server
                    Mail oMail = oClient.GetMail(info);
                    MessageBox.Show("From: " + oMail.From.ToString());
                    MessageBox.Show("Subject: \r\n" + oMail.Subject);
                    MessageBox.Show("inside1");
                    // Generate an email file name based on date time.
                    System.DateTime d = System.DateTime.Now;
                    System.Globalization.CultureInfo cur = new
                                                           System.Globalization.CultureInfo("en-US");
                    string sdate    = d.ToString("yyyyMMddHHmmss", cur);
                    string fileName = String.Format("{0}\\{1}{2}{3}.eml",
                                                    mailbox, sdate, d.Millisecond.ToString("d3"), i);
                    MessageBox.Show("inside4");
                    // Save email to local disk
                    oMail.SaveAs(fileName, true);

                    // Mark email as deleted from POP3 server.
                    oClient.Delete(info);
                }

                // Quit and pure emails marked as deleted from POP3 server.
                oClient.Quit();
            }
            catch (Exception ep)
            {
                MessageBox.Show("error" + ep.Message);
            }
        }
Esempio n. 4
0
        public DataTable CaptureMessages()
        {
            MailClient oClient = new MailClient("TryIt");
            MailServer oServer = CreateMailServer();

            oClient.Connect(oServer);
            MailInfo[] infos = oClient.GetMailInfos();
            DataTable emailTable = new DataTable();
            emailTable.Columns.Add("From", typeof(string));
            emailTable.Columns.Add("Body", typeof(string));
            string mailBox = CreateInbox();

            for (int i = 0; i < infos.Length; i++)
            {
                MailInfo info = infos[i];
                Mail oMail = oClient.GetMail(info);

                System.DateTime d = System.DateTime.Now;
                System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US");
                string sDate = d.ToString("yyyyMMddHHmmss", cur);
                string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailBox, sDate, d.Millisecond.ToString("d3"), i);
                oMail.SaveAs(fileName, true);
                string from = oMail.From.ToString();
                string displayFrom = from.Substring(1, 10);
                emailTable.Rows.Add(displayFrom, oMail.TextBody);
            }

            return emailTable;
        }
Esempio n. 5
0
        private void BtnUpdateMessages_Click(object sender, RoutedEventArgs e)
        {
            listBoxMessages.Items.Clear();

            MailServer server = new MailServer(
                textServer.Text,
                textEmail.Text,
                textPassword.Password,
                EAGetMail.ServerProtocol.Imap4)
            {
                SSLConnection = true,
                Port          = 993
            };

            MailClient client = new MailClient("TryIt");

            try
            {
                client.Connect(server);

                var messages = client.GetMailInfos();

                foreach (var m in messages)
                {
                    Mail message = client.GetMail(m);

                    listBoxMessages.Items.Add($"From: {message.From}\n\n\t{message.Subject}\n");
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);
            }
        }
        public void TestInterOp()
        {
            MailServer oServer = new MailServer("outlook.office365.com",
                                                "*****@*****.**", "Password!", ServerProtocol.Imap4);
            MailClient oClient = new MailClient("TryIt");

            oServer.Port          = 993;
            oServer.SSLConnection = true;

            oClient.Connect(oServer);
            MailInfo[] infos = oClient.GetMailInfos();

            for (int i = 0; i < infos.Length; i++)
            {
                MailInfo info = infos[i];
                Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
                                  info.Index, info.Size, info.UIDL);

                // Receive email from IMAP4 server
                Mail oMail = oClient.GetMail(info);

                Console.WriteLine("From: {0}", oMail.From.ToString());
                Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
            }
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            // Create a folder named "inbox" under current directory
            string curpath = Directory.GetCurrentDirectory();
            string mailbox = String.Format("{0}\\inbox", curpath);

            // If the folder is not existed, create it.
            if (!Directory.Exists(mailbox))
            {
                Directory.CreateDirectory(mailbox);
            }

            MailServer oServer = new MailServer("pop3.live.com", "email", "pass", ServerProtocol.Pop3);
            MailClient oClient = new MailClient("TryIt");

            // Enable SSL connection.
            oServer.SSLConnection = true;

            // Set 995 SSL port
            oServer.Port = 995;

            try
            {
                oClient.Connect(oServer);
                MailInfo[] infos = oClient.GetMailInfos();
                for (int i = 0; i < infos.Length; i++)
                {
                    MailInfo info = infos[i];
                    Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", info.Index, info.Size, info.UIDL);

                    // Receive email from POP3 server
                    Mail oMail = oClient.GetMail(info);

                    Console.WriteLine("From: {0}", oMail.From.ToString());
                    Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

                    // Generate an email file name based on date time.
                    System.DateTime d = System.DateTime.Now;
                    System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("pt-PT");
                    string sdate    = d.ToString("yyyyMMddHHmmss", cur);
                    string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailbox, sdate, d.Millisecond.ToString("d3"), i);

                    // Save email to local disk
                    oMail.SaveAs(fileName, true);
                    Console.Write("Novo email\n");
                    Console.Write("");

                    // Mark email as deleted from POP3 server.
                    //oClient.Delete(info);
                }
                oClient.Quit();
            }
            catch (Exception ep)
            {
                Console.WriteLine(ep.Message);
            }
        }
        static void Main(string[] args)
        {
            // Create a folder named "inbox" under current directory
            // to save the email retrie enter code here ved.
            string curpath = Directory.GetCurrentDirectory();
            string mailbox = String.Format("{0}\\inbox", curpath);

            // If the folder is not existed, create it.
            if (!Directory.Exists(mailbox))
            {
                Directory.CreateDirectory(mailbox);
            }
            // Gmail IMAP4 server is "imap.gmail.com"
            MailServer oServer = new MailServer("imap.gmail.com",
                                                "*****@*****.**", "yourpassword", ServerProtocol.Imap4);
            MailClient oClient = new MailClient("TryIt");

            // Set SSL connection,
            oServer.SSLConnection = true;
            // Set 993 IMAP4 port
            oServer.Port = 993;
            try
            {
                oClient.Connect(oServer);
                MailInfo[] infos = oClient.GetMailInfos();
                for (int i = 0; i < infos.Length; i++)
                {
                    MailInfo info = infos[i];
                    Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
                                      info.Index, info.Size, info.UIDL);
                    // Download email from GMail IMAP4 server
                    Mail oMail = oClient.GetMail(info);
                    Console.WriteLine("From: {0}", oMail.From.ToString());
                    Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
                    // Generate an email file name based on date time.
                    System.DateTime d = System.DateTime.Now;
                    System.Globalization.CultureInfo cur = new
                                                           System.Globalization.CultureInfo("en-US");
                    string sdate    = d.ToString("yyyyMMddHHmmss", cur);
                    string fileName = String.Format("{0}\\{1}{2}{3}.eml",
                                                    mailbox, sdate, d.Millisecond.ToString("d3"), i);
                    // Save email to local disk
                    oMail.SaveAs(fileName, true);
                    // Mark email as deleted in GMail account.
                    oClient.Delete(info);
                }
                // Quit and purge emails marked as deleted from Gmail IMAP4 server.
                oClient.Quit();
            }
            catch (Exception ep)
            {
                Console.WriteLine(ep.Message);
            }
        }
Esempio n. 9
0
        public Mail GetMailDetail(MailInfo mailInfo)
        {
            MailServer server = new MailServer("imap.gmail.com", eMailAddress, passWord, ServerProtocol.Imap4);
            MailClient client = new MailClient("TryIt");

            server.SSLConnection = true;
            server.Port          = 993;

            client.Connect(server);

            return(client.GetMail(mailInfo));
        }
Esempio n. 10
0
        public List <Mail> retrieveNewMailFromGmail(/*int userId*/ string adrMail, string password)
        {
            List <Mail> newMails = new List <Mail>();

            try
            {
                // Gmail IMAP4 server is "imap.gmail.com"
                MailServer mailServer = new MailServer(
                    "imap.gmail.com",
                    adrMail,
                    password,
                    ServerProtocol.Imap4);
                // Enable SSL connection.
                mailServer.SSLConnection = true;
                mailServer.Port          = 993;

                MailClient mailClient = new MailClient("TryIt");
                mailClient.Connect(mailServer);

                // retrieve unread/new email only
                mailClient.GetMailInfosParam.Reset();
                mailClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfosOptionType.NewOnly;
                MailInfo[] infos = mailClient.GetMailInfos();
                Console.WriteLine("Total {0} unread email(s)\r\n", infos.Length);

                // Receive email list from IMAP4 server
                for (int i = 0; i < infos.Length; i++)
                {
                    MailInfo info = infos[i];
                    Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
                                      info.Index, info.Size, info.UIDL);

                    //// Receive email from IMAP4 server
                    Mail oMail = mailClient.GetMail(info);
                    newMails.Add(oMail);

                    // mark unread email as read, next time this email won't be retrieved again
                    if (!info.Read)
                    {
                        mailClient.MarkAsRead(info, true);
                    }
                }

                // Quit and expunge emails marked as deleted from IMAP4 server.
                mailClient.Quit();
                Console.WriteLine("Completed!");
            }
            catch (Exception ep)
            {
                Console.WriteLine(ep.Message);
            }
            return(newMails);
        }
Esempio n. 11
0
        private void pictureBox2_Click(object sender, EventArgs e)
        {
            MailServer oServer = new MailServer("pop.gmail.com", "*****@*****.**", "nourbess", true, ServerAuthType.AuthLogin, ServerProtocol.Pop3);
            MailClient oClient = new MailClient("TryIt");

            oClient.Connect(oServer);
            MailInfo[] infos = oClient.GetMailInfos();
            for (int i = 0; i < infos.Length; i++)
            {
                MailInfo info  = infos[i];                   // Receive email from POP3 server
                Mail     oMail = oClient.GetMail(info);

                String[] substrings = oMail.TextBody.Split('\n');

                String[] substrings2 = substrings[0].Split(':');
                String[] substrings3 = substrings[1].Split(':');
                String[] substrings4 = substrings[2].Split(':');
                String[] substrings5 = substrings[3].Split(':');
                String[] substrings6 = substrings[4].Split(':');

                //FAX
                String[] substrings7 = substrings[5].Split(':');

                //Responsable
                String[] substrings8 = substrings[6].Split(':');
                //  Console.WriteLine(substrings8[substrings8.Length - 1]);
                String[] X = substrings8[substrings8.Length - 1].Split(' ');
                Debug.WriteLine(X[0]);
                //Type d'intervention
                String[] substrings9 = substrings[7].Split(':');

                //delai
                String[] substrings10 = substrings[8].Split(':');

                //mail
                String[] substrings11 = substrings[9].Split(':');

                //Reclamation
                String[] substrings12 = substrings[10].Split(':');


                using (SqlConnection conn = Get_Connection())
                {
                    conn.Open();
                    String req = "INSERT INTO tickets(nom, prenom,raison_Sociale,contrat_Id,tel,type_Intervention,delai,mail,reclamation,date_deb) VALUES ('" + substrings2[substrings2.Length - 1] + "','" + substrings3[substrings3.Length - 1] + "','" + substrings4[substrings4.Length - 1] + "','" + substrings5[substrings5.Length - 1] + "','" + substrings6[substrings6.Length - 1] + "','" + substrings9[substrings9.Length - 1] + "','" + substrings10[substrings10.Length - 1] + "','" + substrings11[substrings11.Length - 1] + "','" + substrings12[substrings12.Length - 1] + "','" + oMail.SentDate + "')";
                    using (SqlCommand cmd = new SqlCommand(req, conn))
                    {
                        cmd.ExecuteNonQuery();
                    }
                }
            }
        }
Esempio n. 12
0
        private void FoldersList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            messagesList.Items.Clear();
            mClient.SelectFolder(mClient.Imap4Folders[1].SubFolders[FoldersList.SelectedIndex]);
            var messages = mClient.GetMailInfos();

            foreach (var item in messages)
            {
                Mail m = mClient.GetMail(item);
                m.Subject = (m.Subject.Replace("(Trial Version)", ""));
                messagesList.Items.Add(m);
            }
        }
Esempio n. 13
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (!Send.IsValidEmail(textBox1.Text))
            {
                MessageBox.Show("Invalid email format! Please introduce email orrectly!", "Warning !"); return;
            }
            textBox3.Visible = true;
            textBox3.Text    = string.Empty;
            try
            {
                MailServer oServer = new MailServer("pop.gmail.com", textBox1.Text, textBox2.Text, EAGetMail.ServerProtocol.Imap4);

                oServer.Port          = 993;
                oServer.SSLConnection = true;

                MailClient oClient = new MailClient("TryIt");
                oClient.Connect(oServer);

                MailInfo[] infos = oClient.GetMailInfos();
                textBox3.Text += "Total ";
                textBox3.Text += infos.Length;
                textBox3.Text += " email(s)\r\n";


                for (int i = 0; i < infos.Length; i++)
                {
                    MailInfo info = infos[i];

                    textBox3.Text += info.Index;
                    textBox3.Text += ". ";
                    // Receive email from POP3 server
                    Mail oMail = oClient.GetMail(info);

                    textBox3.AppendText(Environment.NewLine);
                    textBox3.Text += "\nFrom: ";
                    textBox3.Text += oMail.From.ToString();
                    textBox3.AppendText(Environment.NewLine);
                    textBox3.Text += "\nSubject: ";
                    textBox3.Text += oMail.Subject;

                    textBox3.Text += "\r\n";
                }

                oClient.Quit();
            }
            catch (Exception ep)
            {
                textBox3.Visible = false;
                MessageBox.Show("Email or password incorrect", "Warning!");
            }
        }
Esempio n. 14
0
        private void bodymessegeText_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            messegeText.Items.Clear();

            client.SelectFolder(client.Imap4Folders[folderText.SelectedIndex].SubFolders[bodymessegeText.SelectedIndex]);
            // get mails in selected folder
            var messages = client.GetMailInfos();

            foreach (var m in messages)
            {
                Mail message = client.GetMail(m);
                messegeText.Items.Add($"Index: {m.Index}{Environment.NewLine}Size: {m.Size}\n From: {message.From}\n\t{message.Subject} Date: {message.SentDate}\tAttachments: {message.Attachments.Count()}Body: {(message.TextBody)}");
            }
        }
Esempio n. 15
0
        private void Init()
        {
            var messages = client.u_GetMailInfos();

            foreach (var mailinfo in messages)
            {
                Mail tmpMail = client.GetMail(mailinfo);
                tmpMail.Subject = tmpMail.Subject.Replace("(Trial Version)", "");
                lbMail.Dispatcher.Invoke(() =>
                {
                    lbMail.Items.Add(new MyLetter(mailinfo, tmpMail));
                });
            }
        }
Esempio n. 16
0
        private void LbMail_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            MailInfo m       = (MailInfo)(sender as ListBox).SelectedItem;
            Mail     message = client.GetMail(m);

            tbFrom.Text    = message.From.ToString();
            tbTo.Text      = tbLogin.Text;
            tbSubject.Text = message.Subject;
            tbBody.Text    = message.TextBody;
            foreach (var item in message.Attachments)
            {
                lbAttach.Items.Add(item);
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(EmailTextBox.Text) || string.IsNullOrEmpty(PasswordBox.Password))
            {
                return;
            }

            MailServer server = new MailServer(
                "",
                EmailTextBox.Text,
                PasswordBox.Password,
                ServerProtocol.Imap4)
            {
                SSLConnection = true,
            };

            if (GoogleRadioButton.IsChecked == true)
            {
                server.Server = "imap.gmail.com";
                server.Port   = 993;
            }
            else if (UkrRadioButton.IsChecked == true)
            {
                server.Server = "imap.ukr.net";
                server.Port   = 993;
            }
            MailClient client = new MailClient("TryIt"); // trial version

            try
            {
                client.Connect(server);
                var messages = client.GetMailInfos();

                foreach (var m in messages)
                {
                    Mail message = client.GetMail(m);

                    mailMessages.Add(new MyMailMessage()
                    {
                        From = message.From.ToString(), Subject = message.Subject, AllText = message.TextBody, Text = new string(message.TextBody.Take(80).ToArray()).Replace("\n", "").Replace("\r", "") + "...", Date = message.ReceivedDate
                    });
                }
                isConnected = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 18
0
        private void leerCorreos()
        {
            // Create a folder named "inbox" under current directory
            // to save the email retrieved.
            string curpath = Directory.GetCurrentDirectory();
            string mailbox = String.Format("{0}\\inbox", curpath);

            // If the folder is not existed, create it.
            if (!Directory.Exists(mailbox))
            {
                Directory.CreateDirectory(mailbox);
            }
            MailServer oServer = new MailServer("imap.gmail.com", "*****@*****.**", "correocs", ServerProtocol.Imap4);
            MailClient oClient = new MailClient("TryIt");

            oServer.SSLConnection = true;
            oServer.Port          = 993;
            try
            {
                string json;
                oClient.Connect(oServer);
                infos = oClient.GetMailInfos();
                for (int i = 0; i < infos.Length; i++)
                {
                    MailInfo info  = infos[i];
                    Mail     oMail = oClient.GetMail(info);

                    if (!info.Read)
                    {
                        json = oMail.TextBody;
                        Formu jsonObj = new Formu();
                        jsonObj = JsonConvert.DeserializeObject <Formu>(json);
                        dgvSolicitudes.Rows[dgvSolicitudes.Rows.Add()].Cells[0].Value = (contador + 1).ToString();
                        dgvSolicitudes.Rows[contador].Cells[1].Value = jsonObj.NombreCompleto;
                        dgvSolicitudes.Rows[contador].Cells[2].Value = oMail.ReceivedDate.ToShortDateString();
                        lista.Add(json);
                        contador++;
                    }
                }
                // Quit and purge emails marked as deleted from Gmail IMAP4 server.
                oClient.Quit();
                Console.Read();
            }
            catch (Exception ep)
            {
                Console.WriteLine(ep.Message);
                Console.Read();
            }
        }
Esempio n. 19
0
        private void RetreiveMail_Load(object sender, EventArgs e)
        {
            MailInfo[] infos = oClient.GetMailInfos();
            for (int i = 0; i < infos.Length; i++)
            {
                MailInfo info = infos[i];

                // Receive email from IMAP4 server
                Mail oMail = oClient.GetMail(info);

                MessageBox.Show("From: " + oMail.From.ToString());
                MessageBox.Show("Subject: \r\n" + oMail.Subject);
                MessageBox.Show(oMail.TextBody);
                MessageBox.Show(oMail.ReceivedDate.ToString());
            }
        }
 private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
 {
     if (listBox1.SelectedItems.Count != 1)
     {
         return;
     }
     try {
         Mail currentEmail = mailClient.GetMail((listBox1.SelectedItem as MailItem).mailInfo);
         txtSubject.Text = currentEmail.Subject;
         tabControl1.TabPages.Remove(tabPage2);
         //--attachments
         Attachment[] attachments = currentEmail.Attachments;
         cmbAttachments.Items.Clear();
         foreach (Attachment attachment in attachments)
         {
             cmbAttachments.Items.Add(new AttachmentItem(attachment));
         }
         if (cmbAttachments.Items.Count > 0)
         {
             cmbAttachments.SelectedItem = cmbAttachments.Items[0];
             tabControl1.TabPages.Add(tabPage2);
         }
         //--combo TO
         MailAddress[] ma = currentEmail.To;
         cmbTO.Items.Clear();
         foreach (MailAddress mailAddress in ma)
         {
             cmbTO.Items.Add(mailAddress.Address);
         }
         cmbTO.SelectedItem = cmbTO.Items[0];
         //--EMAIL view
         foreach (Attachment attachment in attachments)
         {
             currentEmail.HtmlBody = currentEmail.HtmlBody.Replace("cid:" + attachment.ContentID, "data:" + attachment.ContentType + ";base64," + Convert.ToBase64String(attachment.Content));
         }
         webBrowser1.DocumentText = currentEmailBody = currentEmail.HtmlBody;
         tableLayoutPanel1.RowStyles[1].Height = 20;
         tableLayoutPanel1.RowStyles[3].Height = 70;
         tableLayoutPanel1.RowStyles[4].Height = 80;
         btnResize.BackgroundImage             = Resources.up_arrow;
     }
     catch (Exception ex) {
         Text = "błąd połączeńa";
     }
 }
Esempio n. 21
0
        static void Main(string[] args)
        {
            try
            {
                String email, pass;
                Console.WriteLine("Введите логин:");
                email = Console.ReadLine();
                Console.WriteLine("Введите пароль:");
                pass = Console.ReadLine();

                // mail.ru IMAP4 server is "imap.mail.ru"
                MailServer oServer = new MailServer("imap.mail.ru",
                                                    email, pass, ServerProtocol.Imap4);
                MailClient oClient = new MailClient("TryIt");

                // Set SSL connection
                oServer.SSLConnection = true;
                oServer.Port          = 993;

                oClient.Connect(oServer);
                MailInfo[] infos = oClient.GetMailInfos();
                Console.WriteLine("Подключение выполнено успешно. Всего писем: {0}\r\n", infos[infos.Length - 1].Index);
                for (int i = 0; i < infos.Length; i++)
                {
                    MailInfo info = infos[i];
                    Console.WriteLine("№: {0}; Размер: {1}; UIDL: {2}",
                                      info.Index, info.Size, info.UIDL);

                    // Download email
                    Mail oMail = oClient.GetMail(info);

                    Console.WriteLine("От: {0}", oMail.From.ToString());
                    Console.WriteLine("Тема: {0}\r\n", oMail.Subject);
                }
                oClient.Quit();
                Console.ReadLine();
            }
            catch (Exception ep)
            {
                Console.WriteLine(ep.Message);
                Console.ReadLine();
            }
        }
Esempio n. 22
0
        public void ReadEmails()
        {
            try
            {
                //if(!oClient.Connected)
                oClient.Connect(oServer);
                MailInfo[] infos = oClient.GetMailInfos();
                for (int i = 0; i < infos.Length; i++)
                {
                    MailInfo info = infos[i];
                    //Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
                    //    info.Index, info.Size, info.UIDL);

                    // Receive email from IMAP4 server
                    Mail oMail   = oClient.GetMail(info);
                    var  body    = oMail.TextBody.Trim();
                    var  subject = oMail.Subject.Trim().Replace("(Trial Version)", "");
                    //Console.WriteLine("From: {0}", oMail.From.ToString());
                    //Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

                    if (_handler != null && (string.IsNullOrEmpty(_acceptMsgFrom) || string.Compare(oMail.From.Address, _acceptMsgFrom, true) == 0))
                    {
                        _handler(body);
                    }
                    // Generate an email file name based on date time.
                    System.DateTime d = System.DateTime.Now;
                    System.Globalization.CultureInfo cur = new
                                                           System.Globalization.CultureInfo("en-US");
                    string sdate    = d.ToString("ddMMyyyy-HHmmss", cur);
                    string fileName = String.Format("{0}\\{1}_{2}.eml",
                                                    _storePath, sdate, subject.Replace(':', '-'));
                    // Save email to local disk
                    oMail.SaveAs(fileName, true);

                    oClient.ChangeMailFlags(info, "\\Seen");
                    oClient.Move(info, _readMails);
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }
Esempio n. 23
0
        /// <summary>
        /// 下载指定的邮件数据信息到本地
        /// </summary>
        /// <param name="dataInfo"></param>
        public void DownloadEmailInfo(EmailDataInfo dataInfo)
        {
            MailServer oServer = new MailServer(MailServerAddress,
                                                this.User, this.Password, true, ServerAuthType.AuthLogin, ServerProtocol.Imap4);

            oServer.Port = 993;
            MailClient oClient = new MailClient(LicenseCode);

            try
            {
                oClient.Connect(oServer);
                var mail = oClient.GetMail(dataInfo.MailInfo);
                this.BuildEmailDataInfo(dataInfo, mail, dataInfo.MailInfo);
                this.SaveMailDataInfo(dataInfo);
                dataInfo.IsDownloadedMail = true;
            }
            finally
            {
                oClient.Quit();
                oClient.Close();
            }
        }
        public void LoadRecentMessages(int lastSequenceNumber)
        {
            if (lastSequenceNumber != 0 && lastSequenceNumber != null)
            {
                lastMailCheck = lastSequenceNumber;
            }

            MailInfo[] infos = oClient.GetMailInfos();

            for (int i = 0; i < infos.Length; i++)
            {
                MailInfo info = infos[i];
                if (info.Index > lastMailCheck)
                {
                    Mail        mail    = oClient.GetMail(info);
                    MailMessage message = new MailMessage()
                    {
                        Id          = info.Index,
                        RecibedTime = mail.SentDate.Date,
                        SendBy      = mail.From.Name + "-" + mail.From.Address,
                        Subject     = mail.Subject,
                    };
                    foreach (var mailAttachment in mail.Attachments)
                    {
                        message.Attachments.Add(new MailAtachment()
                        {
                            file = mailAttachment.Name,
                            data = mailAttachment.Content
                        });
                    }
                    Messages.Add(message);
                }
                if (lastMailCheck < info.Index)
                {
                    lastMailCheck = info.Index;
                }
            }
        }
Esempio n. 25
0
        private void btnStart_Click(object sender, System.EventArgs e)
        {
            _enableSettingControls(false, false);
            if (!_tryOauth())
            {
                _enableSettingControls(true, false);
                return;
            }

            if (ComboBoxAuthType.SelectedIndex == (int)ServerAuthType.AuthXOAUTH2)
            {
                textUser.Text     = _oauthWrapper.OauthProvider.UserEmail;
                textPassword.Text = _oauthWrapper.OauthProvider.AccessToken;
            }

            if (!_validateInput())
            {
                _enableSettingControls(true, false);
                return;
            }

            _enableSettingControls(false, true);

            // UIDL is the identifier of every email on POP3/IMAP4/Exchange server, to avoid retrieve
            // the same email from server more than once, we record the email UIDL retrieved every time
            // if you delete the email from server every time and not to leave a copy of email on
            // the server, then please remove all the function about uidl.
            // UIDLManager wraps the function to write/read uidl record from a text file.
            UIDLManager oUIDLManager  = new UIDLManager();
            bool        _isUidlLoaded = false;

            try
            {
                // For evaluation usage, please use "TryIt" as the license code, otherwise the
                // "Invalid license code" exception will be thrown. However, the object will expire in 1-2 months, then
                // "Trial version expired" exception will be thrown.
                MailClient client = new MailClient("TryIt");

                // Catching the following events is not necessary,
                // just make the application more user friendly.
                // If you use the object in asp.net/windows service or non-gui application,
                // You need not to catch the following events.
                // To learn more detail, please refer to the code in EAGetMail EventHandler region
                client.OnAuthorized          += new MailClient.OnAuthorizedEventHandler(OnAuthorized);
                client.OnConnected           += new MailClient.OnConnectedEventHandler(OnConnected);
                client.OnIdle                += new MailClient.OnIdleEventHandler(OnIdle);
                client.OnSecuring            += new MailClient.OnSecuringEventHandler(OnSecuring);
                client.OnReceivingDataStream += new MailClient.OnReceivingDataStreamEventHandler(OnReceivingDataStream);

                _isCancelOperation = false;
                textStatus.Text    = "Connecting ...";

                // generate a log file for debug
                // client.LogFileName = string.Format("{0}\\log.txt", _currentPath);

                MailServer server = _buildServer();
                client.Connect(server);

                string localInbox = _createLocalInbox();

                // load existed uidl records to UIDLManager
                string uidlfile = string.Format("{0}\\{1}", localInbox, _uidlFile);
                oUIDLManager.Load(uidlfile);
                _isUidlLoaded = true;

                _setMailRange(ref client);

                textStatus.Text = "Retrieveing email list ...";
                MailInfo[] infos = client.GetMailInfos();
                textStatus.Text = string.Format("Total {0} email(s)", infos.Length);

                if (ComboBoxDateRange.SelectedIndex == 0)
                {
                    // Remove the local uidl that is not existed on the server,
                    // we only synchronize it with uidl of all emails in current mail folder
                    oUIDLManager.SyncUIDL(server, infos);
                    oUIDLManager.Update();
                }

                for (int i = 0; i < infos.Length; i++)
                {
                    pgBar.Maximum = 100;
                    pgBar.Minimum = 0;
                    pgBar.Value   = 0;

                    textStatus.Text = string.Format("Checking {0}/{1}...", i + 1, infos.Length);

                    MailInfo info = infos[i];
                    if (oUIDLManager.FindUIDL(server, info.UIDL) != null)
                    {
                        //this email has been downloaded before.
                        continue;
                    }

                    textStatus.Text = string.Format("Retrieving {0}/{1}...", i + 1, infos.Length);

                    Mail mail = client.GetMail(info);

                    string fileName     = _generateFileName(i + 1);
                    string fullFileName = string.Format("{0}\\{1}", localInbox, fileName);
                    mail.SaveAs(fullFileName, true);

                    _addNewMailToListView(ref mail, fullFileName);
                    mail.Clear();

                    LabelTotal.Text = string.Format("Total {0} email(s)", ListViewMail.Items.Count);

                    // If retrieve only new emails, after we retrieved it, mark it as read,
                    // With this feature, you don't have to UIDLManager to prevent duplicated emails.
                    if (chkNewOnly.Checked && ComboBoxProtocol.SelectedIndex != (int)ServerProtocol.Pop3)
                    {
                        client.MarkAsRead(info, true);
                    }

                    if (chkLeaveCopy.Checked)
                    {
                        // Add the email uidl to uidl file to avoid we retrieve it next time.
                        oUIDLManager.AddUIDL(server, info.UIDL, fileName);
                    }
                    else
                    {
                        textStatus.Text = string.Format("Deleting {0}...", i + 1);
                        client.Delete(info);

                        // Remove UIDL from local uidl file.
                        oUIDLManager.RemoveUIDL(server, info.UIDL);
                    }
                }

                // Delete method just mark the email as deleted,
                // Quit method expunge the emails from server exactly.
                client.Quit();

                // Update the uidl list to local uidl file and then we can load it next time.
                oUIDLManager.Update();
                textStatus.Text = "Completed";
            }
            catch (Exception ep)
            {
                if (_isUidlLoaded)
                {
                    // Update the uidl list to local uidl file and then we can load it next time.
                    oUIDLManager.Update();
                }

                MessageBox.Show(ep.Message);
                textStatus.Text = ep.Message;
            }

            _enableSettingControls(true, false);
        }
Esempio n. 26
0
        public static List <string> RecieveEmailsIMAP4()
        {
            List <string> infosGot = new List <string>();


            // Create a folder named "inbox" under current directory
            // to save the email retrieved.
            string curpath = Directory.GetCurrentDirectory();
            string mailbox = String.Format("{0}\\inboxIMAP4", curpath);

            // If the folder is not existed, create it.
            if (!Directory.Exists(mailbox))
            {
                Directory.CreateDirectory(mailbox);
            }

            // Gmail IMAP4 server is "imap.gmail.com"
            MailServer oServer = new MailServer("imap.gmail.com",
                                                "*****@*****.**", "Europesbiggestowl", ServerProtocol.Imap4);
            MailClient oClient = new MailClient("TryIt");

            // Set SSL connection,
            oServer.SSLConnection = true;

            // Set 993 IMAP4 port
            oServer.Port = 993;

            try
            {
                // Lookup folder based name.
                Imap4Folder[] folders = oClient.Imap4Folders;
                Imap4Folder   folder  = SearchFolder(oClient.Imap4Folders, "[Gmail]/Trash");
                if (folder == null)
                {
                    throw new Exception("Folder was not found");
                }

                // Select this folder
                oClient.SelectFolder(folder);


                oClient.Connect(oServer);
                MailInfo[] infos = oClient.GetMailInfos();
                for (int i = 0; i < infos.Length; i++)
                {
                    MailInfo info = infos[i];
                    Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
                                      info.Index, info.Size, info.UIDL);

                    infosGot.Add(info.Index.ToString());
                    infosGot.Add(info.Size.ToString());
                    infosGot.Add(info.UIDL.ToString());

                    // Download email from GMail IMAP4 server
                    Mail oMail = oClient.GetMail(info);

                    infosGot.Add(oMail.From.ToString());
                    infosGot.Add(oMail.Subject);

                    Console.WriteLine("From: {0}", oMail.From.ToString());
                    Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

                    // Generate an email file name based on date time.
                    System.DateTime d = System.DateTime.Now;
                    System.Globalization.CultureInfo cur = new
                                                           System.Globalization.CultureInfo("en-US");
                    string sdate    = d.ToString("yyyyMMddHHmmss", cur);
                    string fileName = String.Format("{0}\\{1}{2}{3}.eml",
                                                    mailbox, sdate, d.Millisecond.ToString("d3"), i);

                    // Save email to local disk
                    oMail.SaveAs(fileName, true);

                    // Mark email as deleted in GMail account.
                    //oClient.Delete(info);
                }

                // Quit and purge emails marked as deleted from Gmail IMAP4 server.
                oClient.Quit();
            }
            catch (Exception ep)
            {
                Console.WriteLine(ep.Message);
            }
            return(infosGot);
        }
Esempio n. 27
0
        public static List <string> RecieveEmailsIMAP4ByFolder()
        {
            List <string> infosGot = new List <string>();

            // Create a folder named "inbox" under current directory
            // to store the email file retrieved.
            string curpath = Directory.GetCurrentDirectory();
            string mailbox = String.Format("{0}\\inbox", curpath);

            // If the folder is not existed, create it.
            if (!Directory.Exists(mailbox))
            {
                Directory.CreateDirectory(mailbox);
            }

            MailServer oServer = new MailServer("imap4.emailarchitect.net",
                                                "*****@*****.**", "testpassword", ServerProtocol.Imap4);
            MailClient oClient = new MailClient("TryIt");

            // Set IMAP4 server port
            oServer.Port = 143;

            // If your IMAP4 server requires SSL connection,
            // Please add the following codes:
            // oServer.SSLConnection = true;
            // oServer.Port = 993;

            try
            {
                oClient.Connect(oServer);

                // Lookup folder based name.
                Imap4Folder folder = SearchFolder(oClient.Imap4Folders, "Deleted Items");
                if (folder == null)
                {
                    throw new Exception("Folder was not found");
                }

                // Select this folder
                oClient.SelectFolder(folder);

                // Retrieve emails from selected folder instead of default folder.
                MailInfo[] infos = oClient.GetMailInfos();
                for (int i = 0; i < infos.Length; i++)
                {
                    MailInfo info = infos[i];
                    Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
                                      info.Index, info.Size, info.UIDL);

                    infosGot.Add(info.Index.ToString());
                    infosGot.Add(info.Size.ToString());
                    infosGot.Add(info.UIDL.ToString());

                    // Receive email from IMAP4 server
                    Mail oMail = oClient.GetMail(info);

                    infosGot.Add(oMail.From.ToString());
                    infosGot.Add(oMail.Subject);

                    Console.WriteLine("From: {0}", oMail.From.ToString());
                    Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

                    // Generate an email file name based on date time.
                    System.DateTime d = System.DateTime.Now;
                    System.Globalization.CultureInfo cur = new
                                                           System.Globalization.CultureInfo("en-US");
                    string sdate    = d.ToString("yyyyMMddHHmmss", cur);
                    string fileName = String.Format("{0}\\{1}{2}{3}.eml",
                                                    mailbox, sdate, d.Millisecond.ToString("d3"), i);

                    // Save email to local disk
                    oMail.SaveAs(fileName, true);

                    // Mark email as deleted from IMAP4 server.
                    //oClient.Delete(info);
                }

                // Quit and purge emails marked as deleted from IMAP4 server.
                oClient.Quit();
            }
            catch (Exception ep)
            {
                Console.WriteLine(ep.Message);
            }
            return(infosGot);
        }
Esempio n. 28
0
        public static List <String> RecieveEmailsPop3()
        {
            List <string> infosGot = new List <string>();

            // Create a folder named "inbox" under current directory
            // to save the email retrieved.
            string curpath = Directory.GetCurrentDirectory();
            string mailbox = String.Format("{0}\\inbox", curpath);

            // If the folder is not existed, create it.
            if (!Directory.Exists(mailbox))
            {
                Directory.CreateDirectory(mailbox);
            }

            MailServer oServer = new MailServer("pop.gmail.com",
                                                "*****@*****.**", "Europesbiggestowl", ServerProtocol.Pop3);
            MailClient oClient = new MailClient("TryIt");

            // If your POP3 server requires SSL connection,
            // Please add the following codes:
            oServer.SSLConnection = true;
            oServer.Port          = 995;

            try
            {
                oClient.Connect(oServer);
                MailInfo[] infos = oClient.GetMailInfos();
                for (int i = 0; i < infos.Length; i++)
                {
                    MailInfo info = infos[i];

                    infosGot.Add(info.Index.ToString());
                    infosGot.Add(info.Size.ToString());
                    infosGot.Add(info.UIDL.ToString());
                    Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
                                      info.Index, info.Size, info.UIDL);

                    // Receive email from POP3 server
                    Mail oMail = oClient.GetMail(info);

                    infosGot.Add(oMail.From.ToString());
                    infosGot.Add(oMail.Subject);
                    Console.WriteLine("From: {0}", oMail.From.ToString());
                    Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

                    // Generate an email file name based on date time.
                    System.DateTime d = System.DateTime.Now;
                    System.Globalization.CultureInfo cur = new
                                                           System.Globalization.CultureInfo("en-US");
                    string sdate    = d.ToString("yyyyMMddHHmmss", cur);
                    string fileName = String.Format("{0}\\{1}{2}{3}.eml",
                                                    mailbox, sdate, d.Millisecond.ToString("d3"), i);

                    // Save email to local disk
                    oMail.SaveAs(fileName, true);

                    // Mark email as deleted from POP3 server.
                    oClient.Delete(info);
                }

                // Quit and purge emails marked as deleted from POP3 server.
                oClient.Quit();
            }
            catch (Exception ep)
            {
                Console.WriteLine(ep.Message);
            }

            return(infosGot);
        }
Esempio n. 29
0
            public string GetMails()
            {
                StringBuilder result = new StringBuilder();

                try
                {
                    result.AppendLine("Conecta con correo");
                    MailClient oClient = GetMailClient();
                    result.AppendLine("Conexión exitosa");
                    result.AppendLine("Obtiene correos nuevos");
                    MailInfo[] infoMails = oClient.GetMailInfos();

                    if (infoMails != null)
                    {
                        result.AppendLine(string.Format("Se encontraron {0} correos nuevos", infoMails.Length));
                        foreach (MailInfo infoMail in infoMails)
                        {
                            Mail oMail = null;
                            try
                            {
                                oMail = oClient.GetMail(infoMail);
                                List <string> headersIngored = new List <string>
                                {
                                    "Auto-Submitted",
                                    "X-Auto-Response-Suppress",
                                    "Precedence"
                                };
                                result.AppendLine(string.Format("Procesando correo {0} recibido {1}", oMail.Subject, oMail.ReceivedDate));
                                bool correovalido = true;
                                foreach (string header in headersIngored)
                                {
                                    correovalido = ValidaHeader(oMail.Headers.GetValueOfKey(header), _valuesIgnored);
                                    if (!correovalido)
                                    {
                                        break;
                                    }
                                }

                                if (correovalido)
                                {
                                    result.AppendLine(string.Format("Correo {0} recibido {1} procesado como nuevo", oMail.Subject, oMail.ReceivedDate));
                                    if (string.IsNullOrEmpty(oMail.Headers.GetValueOfKey("References")))
                                    {
                                        result.AppendLine(string.Format("Correo {0} recibido {1} procesado como nuevo", oMail.Subject, oMail.ReceivedDate));
                                        Smtp.SendNotificationNewTicket(oMail);
                                    }
                                    else
                                    {
                                        result.AppendLine(string.Format("Correo {0} recibido {1} procesado como comentario", oMail.Subject, oMail.ReceivedDate));
                                        string   references      = oMail.Headers.GetValueOfKey("References");
                                        string[] referencesArray = references.Split('~');
                                        if (referencesArray.Any(w => w.Contains("ticket")))
                                        {
                                            Smtp.SendNotificationCommentTicket(oMail);
                                        }
                                        else
                                        {
                                            Smtp.SendNotificationNewTicket(oMail);
                                        }
                                    }
                                }
                                else
                                {
                                    result.AppendLine(string.Format("Correo {0} recibido {1} se descarto por motivo de autorespuesa", oMail.Subject, oMail.ReceivedDate));
                                }
                                ManagerMessage.MarcarLeidoNoLeido(oClient, infoMail);
                            }
                            catch (Exception e)
                            {
                                if (oMail != null)
                                {
                                    result.AppendLine("error al recibir correo: " + oMail.Subject);
                                }
                                else
                                {
                                    result.AppendLine("error al recibir correo: " + e.Message);
                                }
                            }
                        }
                    }
                    oClient.Quit();
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                return(result.ToString().Trim());
            }
Esempio n. 30
0
        //    public void searchForValidTicket()
        //{
        //    //OpenPoP---

        //    //var client = new POPClient();
        //    //client.Connect("pop.gmail.com", 995, true);
        //    //client.Authenticate("*****@*****.**", "YourPasswordHere");
        //    //var count = client.GetMessageCount();
        //    //Message message = client.GetMessage(count);
        //    //Console.WriteLine(message.Headers.Subject);

        //}
        public static void getMail()
        {
            try
            {
                // Create a folder named "inbox" under current directory
                // to save the email retrieved.
                string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
                // If the folder is not existed, create it.
                if (!Directory.Exists(localInbox))
                {
                    Directory.CreateDirectory(localInbox);
                }

                MailServer oServer = new MailServer("pop3.emailarchitect.net",
                                                    "*****@*****.**",
                                                    "testpassword",
                                                    ServerProtocol.Pop3);

                // Enable SSL/TLS connection, most modern email server require SSL/TLS by default
                oServer.SSLConnection = true;
                oServer.Port          = 995;

                // if your server doesn't support SSL/TLS, please use the following codes
                // oServer.SSLConnection = false;
                // oServer.Port = 110;

                MailClient oClient = new MailClient("TryIt");
                oClient.Connect(oServer);


                MailInfo[] infos = oClient.GetMailInfos();
                Console.WriteLine("Total {0} email(s)\r\n", infos.Length);
                for (int i = 0; i < infos.Length; i++)
                {
                    MailInfo info = infos[i];
                    Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
                                      info.Index, info.Size, info.UIDL);

                    // Receive email from POP3 server
                    Mail oMail = oClient.GetMail(info);



                    Console.WriteLine("From: {0}", oMail.From.ToString());
                    Console.WriteLine("Subject: {0}\r\n", oMail.Subject);

                    // Generate an unqiue email file name based on date time.
                    string fileName = _generateFileName(i + 1);
                    string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
                    //oMail.

                    // Save email to local disk
                    oMail.SaveAs(fullPath, true);

                    // Mark email as deleted from POP3 server.
                    oClient.Delete(info);
                }

                // Quit and expunge emails marked as deleted from POP3 server.
                oClient.Quit();
                Console.WriteLine("Completed!");
            }
            catch (Exception ep)
            {
                Console.WriteLine(ep.Message);
            }
        }
Esempio n. 31
0
        public void ReceiveMailByOauth()
        {
            try
            {
                string client_id     = "3ac1c2b8-9518-4f7d-9520-f886515364d6"; // "8f54719b-4070-41ae-91ad-f48e3c793c5f";
                string client_secret = "s3y39]smt_rQ5D.-WXbol0RV6=9mFUaz";     // "cbmYyGQjz[d29wL2ArcgoO7HLwJXL/-.";

                // If your application is not created by Office365 administrator,
                // please use Office365 directory tenant id, you should ask Offic365 administrator to send it to you.
                // Office365 administrator can query tenant id in https://portal.azure.com/ - Azure Active Directory.
                string tenant = "b5b8b483-5597-4ae7-8e27-fcc464a3b584";// "79a42c6f-5a9a-439b-a2ca-7aa1b0ed9776";
                string scopes = "https://outlook.office.com/EWS.AccessAsUser.All%20offline_access%20email%20openid";
                //string scopes = "https://outlook.office365.com/EWS.AccessUserEmail";

                string requestData =
                    string.Format("client_id={0}&client_secret={1}&scope={2}",
                                  client_id, client_secret, scopes);


                string tokenUri = string.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", tenant);
                //string tokenUri = string.Format("https://login.microsoftonline.com/{0}", tenant);
                string responseText = _postString(tokenUri, requestData);

                OAuthResponseParser parser = new OAuthResponseParser();
                parser.Load(responseText);

                // Create a folder named "inbox" under current directory
                // to save the email retrieved.
                string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
                // If the folder is not existed, create it.
                if (!Directory.Exists(localInbox))
                {
                    Directory.CreateDirectory(localInbox);
                }

                string officeUser = "******";
                string token      = parser.AccessToken;
                //token = "eyJ0eXAiOiJKV1QiLCJub25jZSI6Imhhc2VaaEZUQ3gtY1RmVFM4ZGtUN1lydVEzQ3BwUFl5ZE1xUDdjT3d1RFkiLCJhbGciOiJSUzI1NiIsIng1dCI6IllNRUxIVDBndmIwbXhvU0RvWWZvbWpxZmpZVSIsImtpZCI6IllNRUxIVDBndmIwbXhvU0RvWWZvbWpxZmpZVSJ9.eyJhdWQiOiJodHRwczovL291dGxvb2sub2ZmaWNlLmNvbSIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0L2I1YjhiNDgzLTU1OTctNGFlNy04ZTI3LWZjYzQ2NGEzYjU4NC8iLCJpYXQiOjE1ODUxNDA4NzgsIm5iZiI6MTU4NTE0MDg3OCwiZXhwIjoxNTg1MTQ0Nzc4LCJhY2N0IjowLCJhY3IiOiIxIiwiYWlvIjoiQVRRQXkvOE9BQUFBaTFCQTFnQmw0dXpCRkVIOTlVWnEzTjIwRFFUUjkwZjM2eU1DNkoxeWRqNzkxRjZSZzJ5YnlFNUs1RzZ0WWVRUCIsImFtciI6WyJwd2QiXSwiYXBwX2Rpc3BsYXluYW1lIjoiVHJhYzIgRVdTIENvbm5lY3Rpb24iLCJhcHBpZCI6IjNhYzFjMmI4LTk1MTgtNGY3ZC05NTIwLWY4ODY1MTUzNjRkNiIsImFwcGlkYWNyIjoiMCIsImRldmljZWlkIjoiNmNlMTc2MDgtMTUyOC00N2I5LWIwODItOTc3ZDJhNmE1N2E2IiwiZW5mcG9saWRzIjpbXSwiZmFtaWx5X25hbWUiOiJZYXJsYWdhZGRhIiwiZ2l2ZW5fbmFtZSI6IlBhdmFuIiwiaXBhZGRyIjoiMTY1LjIyNS4wLjc5IiwibmFtZSI6IllhcmxhZ2FkZGEsIFBhdmFuIiwib2lkIjoiZDNiMTMzMzYtMGFlZC00MzQ1LWE1ZmQtMmNjODM4YTZiNWYxIiwib25wcmVtX3NpZCI6IlMtMS01LTIxLTI3MjQxMTM3OTctNDI0MTE3MDAxNi0yNTY2NzgzOTgwLTIxNzU3NSIsInB1aWQiOiIxMDAzQkZGRDlBQ0VENjExIiwic2NwIjoiRVdTLkFjY2Vzc0FzVXNlci5BbGwgVXNlci5SZWFkIiwic2lkIjoiYzZhZDQwYWQtMTg4OC00ZGU0LTgxYTgtMmI5OTM0MzYxYzhjIiwic2lnbmluX3N0YXRlIjpbImR2Y19tbmdkIiwiZHZjX2RtamQiLCJrbXNpIl0sInN1YiI6IlRrdnVRU3NvV3p3MlZIaWtucVJpVnFJMXAtclpqaUJkc2JYbm81ZWRtUEEiLCJ0aWQiOiJiNWI4YjQ4My01NTk3LTRhZTctOGUyNy1mY2M0NjRhM2I1ODQiLCJ1bmlxdWVfbmFtZSI6InBhdmFuLnlhcmxhZ2FkZGFAYnNjaS5jb20iLCJ1cG4iOiJwYXZhbi55YXJsYWdhZGRhQGJzY2kuY29tIiwidXRpIjoiYUNsWXBZZzM4MGl2bkVMSlZZUk5BQSIsInZlciI6IjEuMCJ9.Yd4qV8E3jQAOzDKWU-H5e7__XvJvPXOa4QwT_ryauAVPLG8rV_3tIwZdVHdsYUb3T4dSjkivq7kpl2AvbJGiBF1tZSBhrKEjlpPtYNZyE_oqTtiB0G06ZsoDac37ZatPqKq3OhraYh4OO7VYM8WNCvoeebwHIxe3PZZYRuFCZ-Vu2E3HtkiXFduxXQlcsKXFvEI136xQXMPYw1onSGEybMiz5HYsPPTVHx0PW4WEAyb4tiTNtby2vfFxbMFUROkZhwvRzeQgsHXYuafer2ebiWHapPOmkIbrXHnIvyjEJH8vSg4gGRW2HWvDyLxwR5UhZDcn_if0wa16qdDkFz7qzg";
                // use SSL EWS + OAUTH 2.0
                MailServer oServer = new MailServer("outlook.office365.com", officeUser, token, true,
                                                    ServerAuthType.AuthXOAUTH2, ServerProtocol.ExchangeEWS);

                Console.WriteLine("Connecting server ...");

                MailClient oClient = new MailClient("TryIt");
                oClient.Connect(oServer);

                Console.WriteLine("Retreiving email list ...");
                MailInfo[] infos = oClient.GetMailInfos();
                Console.WriteLine("Total {0} email(s)", infos.Length);

                for (int i = 0; i < infos.Length; i++)
                {
                    Console.WriteLine("Checking {0}/{1} ...", i + 1, infos.Length);
                    MailInfo info = infos[i];

                    // Generate an unqiue email file name based on date time.
                    string fileName = _generateFileName(i + 1);
                    string fullPath = string.Format("{0}\\{1}", localInbox, fileName);

                    Console.WriteLine("Downloading {0}/{1} ...", i + 1, infos.Length);
                    Mail oMail = oClient.GetMail(info);

                    // Save mail to local file
                    oMail.SaveAs(fullPath, true);

                    // Mark the email as deleted on server.
                    Console.WriteLine("Deleting ... {0}/{1}", i + 1, infos.Length);
                    oClient.Delete(info);
                }

                Console.WriteLine("Disconnecting ...");

                // Delete method just mark the email as deleted,
                // Quit method expunge the emails from server permanently.
                oClient.Quit();

                Console.WriteLine("Completed!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("Error: {0}", ep.Message);
            }
        }
        public List<PurchaseEmail> CheckEmail()
        {
            string curpath = Directory.GetCurrentDirectory();
            string mailbox = String.Format("{0}\\inbox", curpath);
            string htmlMailbox = String.Format("{0}\\htmlInbox", curpath);

            // If the .eml and .htm folders do not exist, create it.
            if (!Directory.Exists(mailbox))
            {
                Directory.CreateDirectory(mailbox);
            }
            if (!Directory.Exists(htmlMailbox))
            {
                Directory.CreateDirectory(htmlMailbox);
            }

            // Gmail IMAP4 server is "imap.gmail.com"
            MailServer oServer = new MailServer("imap.gmail.com",
                        "*****@*****.**", "**Jessica8", ServerProtocol.Imap4);
            MailClient oClient = new MailClient("TryIt");

            // Set SSL connection,
            oServer.SSLConnection = true;

            // Set 993 IMAP4 port
            oServer.Port = 993;

            try
            {
                oClient.Connect(oServer);
                MailInfo[] infos = oClient.GetMailInfos();
                for (int i = 0; i < infos.Length; i++)
                {
                    MailInfo info = infos[i];
                    //Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", info.Index, info.Size, info.UIDL);

                    // Download email from GMail IMAP4 server
                    Mail oMail = oClient.GetMail(info);

                    if (oMail.From.ToString().Contains("*****@*****.**"))
                    {
                        // Generate an email file name based on date time.
                        System.DateTime d = System.DateTime.Now;
                        var cur = new System.Globalization.CultureInfo("en-US");
                        string sdate = d.ToString("yyyyMMddHHmmss", cur);
                        string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailbox, sdate, d.Millisecond.ToString("d3"), i);

                        // Save email to local disk
                        oMail.SaveAs(fileName, true);
                    }

                    // Mark email as deleted in GMail account.
                    oClient.Delete(info);

                }

                // Quit and purge emails marked as deleted from Gmail IMAP4 server.
                oClient.Quit();
            }
            catch (Exception ep)
            {
                MessageBox.Show(ep.Message);
            }

            // Get all *.eml files in specified folder and parse it one by one.
            string[] files = Directory.GetFiles(mailbox, "*.eml");

            var purchaseList = new List<PurchaseEmail>();

            for (int i = 0; i < files.Length; i++)
            {
                var convertedMessage = ConvertMailToHtml(files[i]);
                if (System.IO.File.Exists(files[i]))
                {
                    // Use a try block to catch IOExceptions, to
                    // handle the case of the file already being
                    // opened by another process.
                    try
                    {
                        System.IO.File.Delete(files[i]);
                    }
                    catch (System.IO.IOException e)
                    {
                        MessageBox.Show(e.Message);
                    }
                }
                purchaseList.Add(convertedMessage);

            }

            return purchaseList;
        }