Beispiel #1
0
        public static void Verify(string email, string pass, string ipmap, int port)
        {
            string url = null;

            using (ImapClient ic = new ImapClient())
            {
                ic.Connect(ipmap, port, true, false);
                ic.Login(email, pass);
                ic.SelectMailbox("INBOX");
                int mailcount;
                for (mailcount = ic.GetMessageCount(); mailcount < 2; mailcount = ic.GetMessageCount())
                {
                    Mail.Delay(5);
                    ic.SelectMailbox("INBOX");
                }
                MailMessage[] mm    = ic.GetMessages(mailcount - 1, mailcount - 1, false, false);
                MailMessage[] array = mm;
                for (int j = 0; j < array.Length; j++)
                {
                    MailMessage i = array[j];
                    //bool flag = i.Subject == "Account registration confirmation" || i.Subject.Contains("Please verify your account");
                    //if (flag)
                    {
                        string sbody = i.Body;
                        url = Regex.Match(i.Body, "a href=\"(https:[^\n]+)").Groups[1].Value;
                        bool flag2 = string.IsNullOrEmpty(url);
                        if (flag2)
                        {
                            url = Regex.Match(i.Body, "(http.*)").Groups[1].Value.Trim();
                            url = url.Substring(0, url.IndexOf('"'));
                        }
                        break;
                    }
                }
                ic.Dispose();
            }
            HttpRequest rq = new HttpRequest();

            rq.Cookies   = new CookieDictionary(false);
            rq.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36";
            bool Load = false;

            while (!Load)
            {
                try
                {
                    rq.Get(url, null);
                    Load = true;
                }
                catch (Exception)
                {
                }
            }
        }
        private void btnRun_Click(object sender, EventArgs e)
        {
            // Create an imapclient with host, user and password
            ImapClient client = new ImapClient();

            client.Host                = this.HostInput.Text;
            client.Username            = this.Username.Text;
            client.Password            = this.Password.Text;
            client.ConnectionProtocols = ConnectionProtocols.Ssl;
            client.Port                = int.Parse(this.PortInput.Text);
            client.Connect();
            ImapFolderCollection folders = client.GetFolderCollection();
            StringBuilder        sb      = new StringBuilder();

            foreach (ImapFolder folderInfo in folders)
            {
                // Folder name and get messages in the folder
                sb.AppendLine("Folder name is " + folderInfo.Name);
                sb.AppendLine("Message count: " + client.GetMessageCount(folderInfo.Name));
                sb.AppendLine("Is it Marked? " + folderInfo.Marked);
                sb.AppendLine("Message that recent flag count: " + folderInfo.RecentCount);
                sb.AppendLine("Is it Selectable? " + folderInfo.Selectable);
                sb.AppendLine("SubFolders count: " + folderInfo.SubFolders.Count);
                sb.AppendLine("The next unique identifier value: " + folderInfo.UidNext);
                sb.AppendLine("The unique identifier validity value: " + folderInfo.UidValidity);
                sb.AppendLine("Messages which are not set the seen flag count: " + folderInfo.UnseenCount);
                sb.AppendLine("-----------------------Next Folder---------------------------");
            }
            File.WriteAllText("GetFoldersInfo.txt", sb.ToString());
            MessageBox.Show("Completed");
        }
Beispiel #3
0
        private static MailMessage[] GetEmails()
        {
            List <MailMessage> response = new List <MailMessage>();

            using (var imap = new ImapClient(Host, UserName, Password, ImapClient.AuthMethods.Login, Port, false))
            {
                imap.SelectMailbox("INBOX");

                // Get message count
                var messageCount = imap.GetMessageCount();

                if (messageCount == 0)
                {
                    return(response.ToArray());
                }

                var msgs = imap.GetMessages(0, (messageCount - 1)).ToArray();

                foreach (MailMessage msg in msgs)
                {
                    var flags = msg.Flags.ToString();
                    if (!flags.Contains("Deleted"))
                    {
                        response.Add(msg);
                    }
                }
            }

            return(response.ToArray());
        }
        public List <GmailAPIService.CurrentMessage> GetAllMessages(string mail, string password)
        {
            List <GmailAPIService.CurrentMessage> messagesInfo = new List <GmailAPIService.CurrentMessage>();

            ImapClient ic = new ImapClient("imap.gmail.com", mail, password,
                                           AuthMethods.Login, 993, true);

            ic.SelectMailbox("INBOX");

            int messageCount = ic.GetMessageCount();

            MailMessage[] mm = ic.GetMessages(messageCount, messageCount - 30);
            foreach (MailMessage m in mm)
            {
                messagesInfo.Add(new GmailAPIService.CurrentMessage()
                {
                    Id      = m.MessageID.Replace('<', '"').Replace('>', '"'),
                    Date    = m.Date.ToString(),
                    From    = m.From.ToString(),
                    Subject = m.Subject
                });
            }
            ic.Dispose();
            return(messagesInfo);
        }
 public void GetMessageCount()
 {
     using (ImapClient imap = new ImapClient("imap-mail.outlook.com", "*****@*****.**", "password", AuthMethods.Login, 993, true))
     {
         var count = imap.GetMessageCount();
     }
 }
Beispiel #6
0
        private PlugResponse GetLastMailSubject()
        {
            List <MailMessage> msgs = null;

            using (ImapClient client = new ImapClient(HOST, LOGIN, PWD, AuthMethods.Login, PORT, true))
            {
                DateTime dt = DateTime.Now.AddHours(-1);
                msgs = client.GetMessages(client.GetMessageCount() - 5, client.GetMessageCount(), false).ToList();
            }
            MailMessage oneMessage = msgs.MaxBy(mess => mess.Uid);

            RESPONSE.Params.Add("UID", oneMessage.Uid);
            RESPONSE.WaitForChainedAction = true;
            RESPONSE.NextChainedAction    = "GetBodyMessage";
            RESPONSE.ChainedQuestion      = "Souhaitez vous une lecture de l'email ?";
            RESPONSE.Response             = oneMessage.Subject;
            return(RESPONSE);
        }
Beispiel #7
0
        public void DeleteAllMessages()
        {
            DashBoardMailBoxJob model = new DashBoardMailBoxJob();

            model.Inbox = new List <MailMessege>();
            string accountType = "gmail";

            try
            {
                EmailConfiguration email = new EmailConfiguration();
                switch (accountType)
                {
                case "Gmail":
                    // type your popserver
                    email.POPServer = "imap.gmail.com";
                    break;

                case "Outlook":
                    // type your popserver
                    email.POPServer = "outlook.office365.com";
                    break;
                }
                email.POPUsername  = UserName; // type your username credential
                email.POPpassword  = Password; // type your password credential
                email.IncomingPort = "993";
                email.IsPOPssl     = true;


                ImapClient ic = new ImapClient(email.POPServer, email.POPUsername, email.POPpassword, AuthMethods.Login, Convert.ToInt32(email.IncomingPort), (bool)email.IsPOPssl);
                // Select a mailbox. Case-insensitive
                ic.SelectMailbox("INBOX");
                int i        = 1;
                int msgcount = ic.GetMessageCount("INBOX");
                int end      = msgcount - 1;
                int start    = msgcount - msgcount;
                // Note that you must specify that headersonly = false
                // when using GetMesssages().
                MailMessage[] mm = ic.GetMessages(start, end, false);
                // var messages = ic.GetMessages(start, end, true);
                foreach (var it1 in mm)
                {
                    ic.DeleteMessage(it1);
                }


                ic.Dispose();
            }

            catch (Exception e)
            {
                model.mess = "Error occurred retrieving mail. " + e.Message;
            }
            finally
            {
            }
            //return model.Inbox;
        }
Beispiel #8
0
        public void TestMethod1()
        {
            Pop3Client pc = new Pop3Client("mail.jacobgudbjerg.dk", "*****@*****.**", "jacobgud");

            var pi = pc.GetMessageCount();

//      var mes = pc.GetMessage(0);

            //mes.Attachments.First().Save(@"c:\temp\foto.jpg");

            pc.Dispose();

            ImapClient IC = new ImapClient("imap.gmail.com", "*****@*****.**", "", ImapClient.AuthMethods.Login, 993, true);
            var        i  = IC.GetMessageCount("Inbox");

            var mes = IC.GetMessage(IC.GetMessageCount() - 1);

            mes.Attachments.First().Save(@"c:\temp\foto.jpg");
            IC.Dispose();
        }
        static void Main(string[] args)
        {
            ImapClient         client = new ImapClient("imap.gmail.com", "*****@*****.**", "6ot04obb", AuthMethods.Login, 993, true);
            DateTime           dt     = DateTime.Now.AddHours(-1);
            List <MailMessage> msgs   = client.GetMessages(client.GetMessageCount() - 5, client.GetMessageCount(), false).ToList();

            MailMessage oneMessage = msgs.MaxBy(mess => mess.Uid);
            var         message    = msgs.First();

            Console.ReadLine();
        }
        public static GAAutentication Autenticate(string _client_id, string _client_secret)
        {
            GAAutentication result = new GAAutentication();

            try
            {
                UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets {
                    ClientId = _client_id, ClientSecret = _client_secret
                },
                                                                                        new[] { "https://mail.google.com/ email" },
                                                                                        "Lindau",
                                                                                        CancellationToken.None,
                                                                                        new FileDataStore("Analytics.Auth.Store")).Result;
            }
            catch (Exception ex)
            {
                int i = 1;
            }

            if (result.credential != null)
            {
                result.service = new PlusService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = result.credential,
                    ApplicationName       = "Google mail",
                });


                Google.Apis.Plus.v1.Data.Person me = result.service.People.Get("me").Execute();

                Google.Apis.Plus.v1.Data.Person.EmailsData myAccountEmail = me.Emails.Where(a => a.Type == "account").FirstOrDefault();

                // Connect to the IMAP server. The 'true' parameter specifies to use SSL
                // which is important (for Gmail at least)
                ImapClient ic = new ImapClient("imap.gmail.com", myAccountEmail.Value, result.credential.Token.AccessToken,
                                               ImapClient.AuthMethods.SaslOAuth, 993, true);
                // Select a mailbox. Case-insensitive
                ic.SelectMailbox("INBOX");
                Console.WriteLine(ic.GetMessageCount());
                // Get the first *11* messages. 0 is the first message;
                // and it also includes the 10th message, which is really the eleventh ;)
                // MailMessage represents, well, a message in your mailbox
                MailMessage[] mm = ic.GetMessages(0, 10);
                foreach (MailMessage m in mm)
                {
                    Console.WriteLine(m.Subject + " " + m.Date.ToString());
                }
                // Probably wiser to use a using statement
                ic.Dispose();
            }
            return(result);
        }
Beispiel #11
0
        public string GetMailText(DateTime dt)
        {
            try
            {
                var res = ic.SelectMailbox("INBOX");
            }
            catch
            {
                return("123456");
            }
            MailMessage[] mm = ic.GetMessages(ic.GetMessageCount() - 1, ic.GetMessageCount());

            if (mm[mm.Length - 1].Date > dt)
            {
                MailMessage message = ic.GetMessage(mm[mm.Length - 1].Uid);

                string     path       = $"message{r}.html";
                FileStream filestream = new FileStream(path, FileMode.Create);
                filestream.Close();
                StreamWriter file = new StreamWriter(path);
                file.Write(message.Body);
                file.Close();

                Thread.Sleep(5000);
                HtmlAgilityPack.HtmlWeb web = new HtmlWeb();

                HtmlAgilityPack.HtmlDocument doc = web.Load(Environment.CurrentDirectory + @"\" + path);

                var    nodes  = doc.DocumentNode.SelectNodes("//p/font");
                string result = nodes[0].InnerText;

                return(result);//message.Body.ToString();
            }
            else
            {
                Thread.Sleep(5000);
                return(GetMailText(dt));
            }
        }
        public ActionResult GetMessegeBody(string id)
        {
            JsonResult result = new JsonResult();

            EmailConfiguration email = new EmailConfiguration();

            email.POPServer    = "imap.gmail.com";
            email.POPUsername  = "";
            email.POPpassword  = "";
            email.IncomingPort = "993";
            email.IsPOPssl     = true;

            ImapClient ic = new ImapClient(email.POPServer, email.POPUsername, email.POPpassword, AuthMethods.Login, Convert.ToInt32(email.IncomingPort), (bool)email.IsPOPssl);

            // Select a mailbox. Case-insensitive
            ic.SelectMailbox("INBOX");

            int         msgcount = ic.GetMessageCount("INBOX");
            MailMessage mm       = ic.GetMessage(id, false);

            if (mm.Attachments.Count() > 0)
            {
                foreach (var att in mm.Attachments)
                {
                    string fName;
                    fName = att.Filename;
                }
            }
            StringBuilder builder = new StringBuilder();

            builder.Append(mm.Body);
            string sm = builder.ToString();

            CustomerEmailDetails model = new CustomerEmailDetails();

            model.UID      = mm.Uid;
            model.subject  = mm.Subject;
            model.sender   = mm.From.ToString();
            model.sendDate = mm.Date;
            model.Body     = sm;
            if (mm.Attachments == null)
            {
            }
            else
            {
                model.Attachments = mm.Attachments;
            }

            return(View("CreateNewCustomer", model));
        }
Beispiel #13
0
        public void pollServer(string filter)
        {
            List <MailMessage> inbox = new List <MailMessage>();

            try
            {
                EmailConfiguration email = new EmailConfiguration();
                email.POPServer    = ConfigurationManager.AppSettings["host"];
                email.POPUsername  = ConfigurationManager.AppSettings["username"];
                email.POPpassword  = ConfigurationManager.AppSettings["password"];
                email.IncomingPort = ConfigurationManager.AppSettings["port"];
                email.IsPOPssl     = true;


                ImapClient imap = new ImapClient(email.POPServer, email.POPUsername, email.POPpassword, AuthMethods.Login, Convert.ToInt32(email.IncomingPort), (bool)email.IsPOPssl);

                //var messages = imap.SearchMessages(SearchCondition.Unseen(), false, true);

                //List<MailMessage> messages = imap.GetMessages(0, imap.GetMessageCount() - 1, false, false,fa);

                for (int i = imap.GetMessageCount() - 1; i >= 0; i--)
                {
                    var message = imap.GetMessage(i, false, false);
                    if (message.Subject == filter && message.Flags != Flags.Seen)
                    {
                        // Console.WriteLine(message.Attachments); //figure out how to get attachments to work
                        MailMessage outMessage = new MailMessage(); //should probably just pass the message x_x
                        outMessage.Subject = message.Subject;
                        outMessage.Body    = message.Body;

                        if (message.Attachments != null)
                        {
                            outMessage.Attachments = message.Attachments;
                        }

                        imap.AddFlags(Flags.Seen, message);


                        //callback, better to use a delegate here
                        useMessage(outMessage);
                    }
                }
            }
            catch (Exception ex)
            {
                // Console.WriteLine(ex.Message);
                throw;
            }
        }
Beispiel #14
0
        private MailMessage GetLastMessageFromInBox(string folderName = "INBOX")
        {
            // Connect to the IMAP server.
            MailMessage message;

            WriteLine(EnvironmentSettings.TestAccountName);
            WriteLine(EnvironmentSettings.TestAccountPassword);
            using (var ic = new ImapClient(EnvironmentSettings.TestEmailServerHost, EnvironmentSettings.TestAccountName, EnvironmentSettings.TestAccountPassword, AuthMethods.Login, 993, true))
            {
                // Select folder and get the last mail.
                ic.SelectMailbox(folderName);
                message = ic.GetMessage(ic.GetMessageCount() - 1);
            }
            return(message);
        }
Beispiel #15
0
        public static void Verify(string email, string pass, string ipmap = "imap.gmail.com", int port = 993)
        {
            string url = string.Empty;

            using (ImapClient ic = new ImapClient())
            {
                ic.Connect(ipmap, port, true, false);
                ic.Login(email, pass);
                ic.SelectMailbox("INBOX");
                int           mailcount = ic.GetMessageCount();
                MailMessage[] mails     = ic.GetMessages(mailcount - 5, mailcount - 1, false, false);

                foreach (var mm in mails.Reverse())
                {
                    bool flag = mm.Subject.Contains("Xác nhận") || mm.Subject.Contains("xác nhận");
                    if (flag)
                    {
                        string sbody       = mm.Body;
                        string regexString = "(?<=<a href=\").*?(?=\">)";
                        url = Regex.Match(sbody, regexString).ToString();
                        break;
                    }
                }

                ic.Dispose();
            }
            HttpRequest rq = new HttpRequest();

            rq.Cookies   = new CookieDictionary();
            rq.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36";

            if (url == string.Empty)
            {
                MessageBox.Show("Không tìm thấy email nào");
                return;
            }

            try
            {
                var result = rq.Get(url).ToString();
                WriteHtmlFile(result, "verify_mail.html");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        public ICollection <Message> ReceiveMessages(int returnCount) //TODO needs refectoring try-catch
        {
            imapClient.SelectMailbox("INBOX");
            var messageTotalAmount = imapClient.GetMessageCount();

            if (messageTotalAmount < returnCount)
            {
                returnCount = messageTotalAmount;
            }
            var mailMessageList = new List <AE.Net.Mail.MailMessage>();

            for (int i = messageTotalAmount - 1; i >= messageTotalAmount - returnCount; i--)
            {
                AE.Net.Mail.MailMessage message = imapClient.GetMessage(i);
                mailMessageList.Add(message);
            }
            var resultMessageList = new List <Message>();

            mailMessageList.ForEach(mail => resultMessageList.Add(new Message(mail)));

            return(resultMessageList);
        }
Beispiel #17
0
 private void _timer_Elapsed(object sender, ElapsedEventArgs e)
 {
     _timer.Stop();
     using (var client = new ImapClient(_imapServer, _userName, _password, AuthMethods.Login, _imapPort, _imapUseSsl))
     {
         int msgCount = client.GetMessageCount();
         var msg      = client.GetMessages(msgCount - 10, msgCount)
                        .FirstOrDefault(m => m.Subject.ToLower().Contains("pj restart me") && m.Date >= _lastCheck.AddMinutes(-2));
         if (msg != null)
         {
             sendEmail("PJ RESTARTING", "PJ RESTARTING");
             try
             {
                 client.DeleteMessage(msg);
             }
             catch { }
             Process.Start("shutdown", "/r /f");
         }
     }
     _lastCheck = DateTime.Now;
     _timer.Start();
 }
Beispiel #18
0
        private void PasswordEmailButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ic = new ImapClient("imap.gmail.com", "*****@*****.**", PasswordrEmailPB.Password,
                                    AuthMethods.Login, 993, true);


                ic.SelectMailbox("INBOX");


                MailMessage[]      mm = ic.GetMessages(0, ic.GetMessageCount(), true, false);
                List <MailMessage> mms;
                mms = mm.Reverse().ToList();
                mms.RemoveAll(r => r.Encoding != Encoding.UTF8);
                EmailListView.ItemsSource = mms;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Beispiel #19
0
 static void Main(string[] args)
 {
     try
     {
         Console.WriteLine("Welcome to mail box");
         ImapClient imap    = new ImapClient();
         ImapClient Objimap = new ImapClient();
         Objimap = ConnectGmailIMap("outlook.office365.com", "*****@*****.**", "Pass", 143, imap);
         int         MsgCount = Objimap.GetMessageCount("Inbox");
         MailMessage ObjMes   = Objimap.GetFullMessage(MsgCount);
         GetMail(ObjMes);
         //for (int i = MsgCount; i >= 1; i--)
         //{
         //    MailMessage ObjMes = Objimap.GetFullMessage(i);
         //    GetMail(ObjMes);
         //}
     }
     catch (Exception ex)
     {
         Console.WriteLine($"Exception : {Convert.ToString(ex.Message)}");
     }
 }
Beispiel #20
0
        /// <summary>
        /// Function Name : ParseNewEmail
        /// Input Parameters : none
        /// Input Parameter Type : none
        /// Description:This method is going to record the event when an email is received to the Test email. It uses ImapClient which is available in AE.Net.Mail Nuget package.
        /// ImapClient has inbuilt properties to extract subject, body, sender information details from a newly received email
        /// </summary>
        /// <returns>
        /// Return Parameter : emailJson
        /// Return Parameter Type : string
        /// </returns>

        public string ParseNewEmail()
        {
            // Connect to the IMAP server. The 'true' parameter specifies to use SSL, which is important (for Gmail at least)
            ImapClient imapClient = new ImapClient(ConfigurationManager.AppSettings["ImapServer"], ConfigurationManager.AppSettings["UserId"], ConfigurationManager.AppSettings["Password"], AuthMethods.Login, 993, true);
            var        userName   = ConfigurationManager.AppSettings["UserID"];

            //  ImapClient imapClient = new ImapClient(ConfigurationManager.AppSettings["ImapServer"], "*****@*****.**", "7Ywy7N[S", AuthMethods.Login, 993, true);
            // Select a mailbox. Case-insensitive
            imapClient.SelectMailbox("INBOX");
            string emailJson = "";

            Console.WriteLine(imapClient.GetMessageCount());

            imapClient.NewMessage += (sender, e) =>
            {
                var           msg    = imapClient.GetMessage(e.MessageCount - 1);
                string        result = "";
                UpdatePackage up     = new UpdatePackage();
                List <string> li     = new List <string>();
                up.Subject     = msg.Subject;
                up.Body        = msg.Body;
                up.Updates     = ParseBody(msg.Body);
                li             = ParseSubject(msg.Subject);
                up.ProjectName = li[li.Count - 1];
                up.Updates.Add("PhaseId", li[1]);
                up.Updates.Add("VerticalId", li[2]);
                emailJson = JsonConvert.SerializeObject(up);

                using (var client = new WebClient())
                {
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";
                    // result = client.UploadString("https://localhost:44300/ProjectUpdate/Update", "Post", emailJson);
                    result = client.UploadString("http://costcodevops.azurewebsites.net/ProjectUpdate/Update", "Post", emailJson);
                    Console.WriteLine(result);
                }
            };
            return(emailJson);
        }
Beispiel #21
0
        private static void BeginCopy(ImapClient source, Mailbox mailbox, ImapClient destination)
        {
            var srcMsgCount = source.GetMessageCount(mailbox.Name);

            if (srcMsgCount > 0)
            {
                source.SelectMailbox(mailbox.Name);
                Console.WriteLine("Getting source mesages " + srcMsgCount);
                var srcMsgs      = source.GetMessages(0, 5, false);
                var destMsgCount = destination.GetMessageCount(mailbox.Name);
                if (destMsgCount > 0)
                {
                    destination.SelectMailbox(mailbox.Name);
                    var destMsgs = destination.GetMessages(0, destMsgCount);
                    CopyEmails(srcMsgs, destMsgs, destination, mailbox);
                }
                else
                {
                    var destMsgs = new AE.Net.Mail.MailMessage[0];
                    CopyEmails(srcMsgs, destMsgs, destination, mailbox);
                }
            }
        }
Beispiel #22
0
        private static MailMessage connectToImap(string mailFolder)
        {
            //Create an IMAP client
            ImapClient imap = new ImapClient();

            // Set host, username, password etc. for the client
            imap.Host                = "imap.udag.de";
            imap.Port                = 143;
            imap.Username            = "******";
            imap.Password            = "******";
            imap.ConnectionProtocols = ConnectionProtocols.Ssl;
            //Connect the server
            imap.Connect();

            //Select Inbox folder
            imap.Select(mailFolder);

            Int64 messageCounter = imap.GetMessageCount(mailFolder);

            //Get the first message by its sequence number
            MailMessage message = imap.GetFullMessage(messageCounter.ToString());

            return(message);
        }
        public void correos2()
        {
            ImapClient ic = new ImapClient();
            List <AE.Net.Mail.MailMessage> mx;
            List <AE.Net.Mail.MailMessage> emRq17;
            APPSETTING lg = db.APPSETTINGs.Where(x => x.NOMBRE == "logPath" && x.ACTIVO).FirstOrDefault();

            log.ruta = lg.VALUE + "LeerCorreos_";
            log.escribeLog("-----------------------------------------------------------------------START");
            try
            {
                List <CONMAIL> cc      = db.CONMAILs.ToList();
                CONMAIL        conmail = cc.FirstOrDefault(x => x.ID == "LE");
                if (conmail == null)
                {
                    log.escribeLog("Falta configurar inbox."); return;
                }
                ic = new ImapClient(conmail.HOST, conmail.MAIL, conmail.PASS,
                                    AuthMethods.Login, (int)conmail.PORT, conmail.SSL);

                // Select a mailbox. Case-insensitive
                ic.SelectMailbox("INBOX");

                //Esto traera los emails recibidos y no leidos
                //mx = ic.GetMessages(0, ic.GetMessageCount() - 1, true, false)
                long a = ic.GetMessageCount();
                if (a > 100)
                {
                    mx = ic.GetMessages(ic.GetMessageCount() - 100, ic.GetMessageCount() - 1, true, false)
                         .Where(m => !m.Flags.HasFlag(Flags.Seen) && !m.Flags.HasFlag(Flags.Deleted)).ToList();
                }
                else
                {
                    mx = ic.GetMessages(0, ic.GetMessageCount() - 1, true, false)
                         .Where(m => !m.Flags.HasFlag(Flags.Seen) && !m.Flags.HasFlag(Flags.Deleted)).ToList();
                }

                //En esta lista ingresaremos a los mails que sean recibidos como cc
                emRq17 = new List <AE.Net.Mail.MailMessage>();
                log.escribeLog("Leer inbox - numReg=(" + mx.Count + ")");
            }
            catch (Exception e)
            {
                mx     = new List <AE.Net.Mail.MailMessage>();
                emRq17 = new List <AE.Net.Mail.MailMessage>();
                log.escribeLog("Error al leer" + e.Message.ToString());
            }
            try
            {
                //ingresamos los correos CORREO
                for (int i = 0; i < mx.Count; i++)
                {
                    AE.Net.Mail.MailMessage mm = ic.GetMessage(mx[i].Uid, false);
                    try
                    {
                        string[] arrAsunto = mm.Subject.Split(']');
                        int      a         = arrAsunto.Length - 1;
                        //Recupero el asunto y lo separo del numdoc y pos
                        string[] arrAprNum = arrAsunto[a].Split('-');//RSG cambiar 0 a 1
                        string[] arrClaves = arrAprNum[1].Split('.');
                        //Valido que tenga los datos necesarios para el req 17
                        if (arrClaves.Length > 1)
                        {
                            arrClaves[1] = Decimal.Parse(arrClaves[1]).ToString();
                        }
                        ////var xy = arrAprNum[0].Trim();
                        if (arrAprNum[0].Trim() == "De Acuerdo" || arrAprNum[0].Trim() == "DeAcuerdo")
                        {
                            emRq17.Add(mm);
                            log.escribeLog("NEGO A - " + arrClaves[1]);
                        }
                        else if (arrAprNum[0].Trim() == "Tengo Observaciones" || arrAprNum[0].Trim() == "TengoObservaciones")
                        {
                            emRq17.Add(mm);
                            log.escribeLog("NEGO O - " + arrClaves[1]);
                        }
                    }
                    catch
                    {
                        ic.AddFlags(Flags.Seen, mm);
                        log.escribeLog("ERROR - " + mm.Subject);
                    }
                }
                //Correos de FLUJO DE APROBACIÓN y RECURRENTE-----------------------------------------------------2 y 3
                if (true)
                {
                    for (int i = 0; i < mx.Count; i++)
                    {
                        AE.Net.Mail.MailMessage mm = ic.GetMessage(mx[i].Uid, false);
                        try
                        {
                            string[] arrAsunto = mm.Subject.Split(']');
                            int      a         = arrAsunto.Length - 1;
                            //Recupero el asunto y lo separo del numdoc y pos
                            string[] arrAprNum = arrAsunto[a].Split('-');//RSG cambiar 0 a 1
                            string[] arrClaves = arrAprNum[1].Split('.');
                            decimal  numdoc    = Decimal.Parse(arrClaves[0]);
                            //Si el Texto es Aprobado, Rechazado o Recurrente
                            string[] arrApr = arrAprNum[0].Split(':');
                            if (arrApr.Length > 1)
                            {
                                ProcesaFlujo pF = new ProcesaFlujo();
                                if (arrApr[1] == "Approved" || arrApr[1] == "Rejected")
                                {
                                    log.escribeLog("APPR AR - " + arrClaves[0]);
                                    int   pos = Convert.ToInt32(arrAprNum[2]);
                                    FLUJO fl  = db.FLUJOes.Where(x => x.NUM_DOC == numdoc && x.POS == pos).FirstOrDefault();
                                    if (fl != null)
                                    {
                                        Console.WriteLine(mm.From.Address.Trim()); Console.WriteLine(fl.USUARIO.EMAIL);
                                        log.escribeLog("APPR mails - " + mm.From.Address.Trim() + " == " + fl.USUARIO.EMAIL);
                                        if (mm.From.Address.Trim().ToLower() == fl.USUARIO.EMAIL.Trim().ToLower() || mm.From.Address.Trim().ToLower() == fl.USUARIO1.EMAIL.Trim().ToLower())
                                        {
                                            Console.WriteLine("true");
                                            fl.ESTATUS = arrApr[1].Substring(0, 1);
                                            fl.FECHAM  = DateTime.Now;
                                            Comentario com = new Comentario();
                                            fl.COMENTARIO = com.getComment(mm.Body, mm.ContentType);
                                            ////fl.COMENTARIO = mm.Body;
                                            ////if (fl.COMENTARIO.Length > 255)
                                            ////    fl.COMENTARIO = fl.COMENTARIO.Substring(0, 252) + "...";
                                            var res = pF.procesa(fl, "");
                                            log.escribeLog("APPR PROCESA - Res = " + res);
                                            Email email = new Email();
                                            if (res == "1")
                                            {
                                                email.enviarCorreo(fl.NUM_DOC, 1, pos);
                                            }
                                            else if (res == "3")
                                            {
                                                email.enviarCorreo(fl.NUM_DOC, 3, pos);
                                            }

                                            using (TAT001Entities db1 = new TAT001Entities())
                                            {
                                                FLUJO     ff   = db1.FLUJOes.Where(x => x.NUM_DOC == fl.NUM_DOC).OrderByDescending(x => x.POS).FirstOrDefault();
                                                Estatus   es   = new Estatus();//RSG 18.09.2018
                                                DOCUMENTO ddoc = db1.DOCUMENTOes.Find(fl.NUM_DOC);
                                                ff.STATUS           = es.getEstatus(ddoc);
                                                db1.Entry(ff).State = System.Data.Entity.EntityState.Modified;
                                                db1.SaveChanges();
                                            }
                                            Console.WriteLine(res);
                                        }
                                    }
                                    ic.AddFlags(Flags.Seen, mm);
                                }
                                ////else if (arrApr[1] == "Rejected")
                                ////{
                                ////    int pos = Convert.ToInt32(arrAprNum[2]);
                                ////    FLUJO fl = db.FLUJOes.Where(x => x.NUM_DOC == numdoc && x.POS == pos).FirstOrDefault();
                                ////    fl.ESTATUS = "R";
                                ////    fl.FECHAM = DateTime.Now;
                                ////    fl.COMENTARIO = mm.Body;
                                ////    var res = pF.procesa(fl, "");
                                ////    if (res == "0")
                                ////    {
                                ////        //
                                ////    }
                                ////    else if (res == "1")
                                ////    {
                                ////        enviarCorreo(fl.NUM_DOC, 1);
                                ////    }
                                ////    else if (res == "3")
                                ////    {
                                ////        enviarCorreo(fl.NUM_DOC, 3);
                                ////    }
                                ////    //para marcar el mensaje como leido
                                ////    ic.AddFlags(Flags.Seen, mm);
                                ////}
                                else if (arrApr[1] == "Recurrent")
                                {
                                    ////Reversa r = new Reversa();
                                    ////string ts = db.DOCUMENTOes.Find(numdoc).TSOL.TSOLR;
                                    ////int ret = 0;
                                    ////if (ts != null)
                                    ////    ret = r.creaReversa(numdoc.ToString(), ts);

                                    //////para marcar el mensaje como leido
                                    ////if (ret != 0)
                                    ////    ic.AddFlags(Flags.Seen, mm);
                                }
                            }
                        }
                        catch (Exception ee)
                        {
                            ic.AddFlags(Flags.Seen, mm);
                            log.escribeLog("ERROR - " + ee.Message.ToString());
                        }
                    }
                }
                //req17
                ////FLUJNEGO fn = new FLUJNEGO();
                for (int i = 0; i < emRq17.Count; i++)
                {
                    ////AE.Net.Mail.MailMessage mm = emRq17[i];
                    AE.Net.Mail.MailMessage mm = ic.GetMessage(emRq17[i].Uid, false);
                    if (true)
                    {
                        string[] arrAsunto = mm.Subject.Split(']');
                        int      isa       = arrAsunto.Length - 1;
                        //Recupero el asunto y lo separo del numdoc y pos
                        string[] arrAprNum = arrAsunto[isa].Split('-');
                        string[] arrPiNN   = arrAprNum[1].Split('.');
                        var      _id       = int.Parse(arrPiNN[1]);
                        var      vkorg     = arrPiNN[2];
                        var      _correo   = arrPiNN[4].Replace('*', '.').Replace('+', '-').Replace('/', '@').Replace('#', '-');
                        //recupero las fechas de envio
                        var _xres = db.NEGOCIACIONs.Where(x => x.ID == _id).FirstOrDefault();
                        var pid   = arrPiNN[0];
                        //// var fs = db.DOCUMENTOes.Where(f => f.PAYER_ID == pid && f.FECHAC.Value.Month == DateTime.Now.Month  && f.FECHAC.Value.Year == DateTime.Now.Year && f.DOCUMENTO_REF == null).ToList();
                        var _xff = _xres.FECHAF.AddDays(1);
                        var fs   = db.DOCUMENTOes.Where(f => f.PAYER_ID == pid && f.VKORG == vkorg && f.PAYER_EMAIL == _correo && f.FECHAC >= _xres.FECHAI && f.FECHAC < _xff && f.DOCUMENTO_REF == null).ToList();
                        //LEJ 20.07.2018-----
                        var dOCUMENTOes = fs;
                        var lstD        = new List <DOCUMENTO>();//---
                        ////DOCUMENTOA dz = null;//---
                        for (int y = 0; y < dOCUMENTOes.Count; y++)
                        {
                            PorEnviar pe = new PorEnviar();
                            if (pe.seEnvia(dOCUMENTOes[y], db, log))
                            {
                                lstD.Add(dOCUMENTOes[y]);
                            }

                            //////recupero el numdoc
                            ////var de = fs[i].NUM_DOC;
                            //////sino ecuentra una coincidencia con el criterio discriminatorio se agregan o no a la lista
                            ////dz = db.DOCUMENTOAs.Where(x => x.NUM_DOC == de && x.CLASE != "OTR").FirstOrDefault();
                            ////if (dz == null || dz != null)
                            ////{
                            ////    if (dOCUMENTOes[y].TSOL.NEGO == true)//para el ultimo filtro
                            ////    {

                            ////        string estatus = "";
                            ////        if (dOCUMENTOes[y].ESTATUS != null) { estatus += dOCUMENTOes[y].ESTATUS; } else { estatus += " "; }
                            ////        if (dOCUMENTOes[y].ESTATUS_C != null) { estatus += dOCUMENTOes[y].ESTATUS_C; } else { estatus += " "; }
                            ////        if (dOCUMENTOes[y].ESTATUS_SAP != null) { estatus += dOCUMENTOes[y].ESTATUS_SAP; } else { estatus += " "; }
                            ////        if (dOCUMENTOes[y].ESTATUS_WF != null) { estatus += dOCUMENTOes[y].ESTATUS_WF; } else { estatus += " "; }
                            ////        if (dOCUMENTOes[y].FLUJOes.Count > 0)
                            ////        {
                            ////            estatus += dOCUMENTOes[y].FLUJOes.OrderByDescending(a => a.POS).FirstOrDefault().WORKFP.ACCION.TIPO;
                            ////        }
                            ////        else
                            ////        {
                            ////            estatus += " ";
                            ////        }
                            ////        if (dOCUMENTOes[y].TSOL.PADRE) { estatus += "P"; } else { estatus += " "; }
                            ////        if (dOCUMENTOes[y].FLUJOes.Where(x => x.ESTATUS == "R").ToList().Count > 0)
                            ////        {
                            ////            estatus += dOCUMENTOes[y].FLUJOes.Where(x => x.ESTATUS == "R").OrderByDescending(a => a.POS).FirstOrDefault().USUARIO.PUESTO_ID;
                            ////        }
                            ////        else
                            ////        {
                            ////            estatus += " ";
                            ////        }


                            ////        if (System.Text.RegularExpressions.Regex.IsMatch(estatus, "...[P][R].."))
                            ////            lstD.Add(dOCUMENTOes[y]);
                            ////        else if (System.Text.RegularExpressions.Regex.IsMatch(estatus, "...[R]..[8]"))
                            ////            lstD.Add(dOCUMENTOes[y]);
                            ////        else if (System.Text.RegularExpressions.Regex.IsMatch(estatus, "[P]..[A]..."))
                            ////            lstD.Add(dOCUMENTOes[y]);
                            ////        else if (System.Text.RegularExpressions.Regex.IsMatch(estatus, "..[P][A]..."))
                            ////            lstD.Add(dOCUMENTOes[y]);
                            ////        else if (System.Text.RegularExpressions.Regex.IsMatch(estatus, "..[E][A]..."))
                            ////            lstD.Add(dOCUMENTOes[y]);
                            ////        else if (System.Text.RegularExpressions.Regex.IsMatch(estatus, "...[A].[P]."))
                            ////            lstD.Add(dOCUMENTOes[y]);
                            ////        else if (System.Text.RegularExpressions.Regex.IsMatch(estatus, "...[A]..."))
                            ////            lstD.Add(dOCUMENTOes[y]);
                            ////        else if (System.Text.RegularExpressions.Regex.IsMatch(estatus, "...[T]..."))
                            ////            lstD.Add(dOCUMENTOes[y]);

                            ////        //if (dOCUMENTOes[y].ESTATUS_WF == "P")//LEJ 20.07.2018---------------------------I
                            ////        //{
                            ////        //    if (dOCUMENTOes[y].FLUJOes.Count > 0)
                            ////        //    {
                            ////        //        if (dOCUMENTOes[y].FLUJOes.OrderByDescending(a => a.POS).FirstOrDefault().USUARIO != null)
                            ////        //        {
                            ////        //            //(Pendiente Validación TS)
                            ////        //            if (dOCUMENTOes[y].FLUJOes.OrderByDescending(a => a.POS).FirstOrDefault().USUARIO.PUESTO_ID == 8)
                            ////        //            {
                            ////        //                lstD.Add(dOCUMENTOes[y]);
                            ////        //            }
                            ////        //        }
                            ////        //    }
                            ////        //}
                            ////        //else if (dOCUMENTOes[y].ESTATUS_WF == "R")//(Pendiente Corrección)
                            ////        //{
                            ////        //    if (dOCUMENTOes[y].FLUJOes.Count > 0)
                            ////        //    {
                            ////        //        lstD.Add(dOCUMENTOes[y]);
                            ////        //    }
                            ////        //}
                            ////        //else if (dOCUMENTOes[y].ESTATUS_WF == "T")//(Pendiente Taxeo)
                            ////        //{
                            ////        //    if (dOCUMENTOes[y].TSOL_ID == "NCIA")
                            ////        //    {
                            ////        //        if (dOCUMENTOes[y].PAIS_ID == "CO")//(sólo Colombia)
                            ////        //        {
                            ////        //            lstD.Add(dOCUMENTOes[y]);
                            ////        //        }
                            ////        //    }
                            ////        //}
                            ////        //else if (dOCUMENTOes[y].ESTATUS_WF == "A")//(Por Contabilizar)
                            ////        //{
                            ////        //    if (dOCUMENTOes[y].ESTATUS == "P")
                            ////        //    {
                            ////        //        lstD.Add(dOCUMENTOes[y]);
                            ////        //    }
                            ////        //}
                            ////        //else if (dOCUMENTOes[y].ESTATUS_SAP == "E")//Error en SAP
                            ////        //{
                            ////        //    lstD.Add(dOCUMENTOes[y]);
                            ////        //}
                            ////        //else if (dOCUMENTOes[y].ESTATUS_SAP == "X")//Succes en SAP
                            ////        //{
                            ////        //    lstD.Add(dOCUMENTOes[y]);
                            ////        //}
                            ////    }
                            ////    //LEJ 20.07.2018----------------------------------------------------------------T
                            ////}
                        }
                        //----
                        if (arrAprNum[0].Trim() == "DeAcuerdo" || arrAprNum[0].Trim() == "De Acuerdo")
                        {
                            for (int x = 0; x < lstD.Count; x++)
                            {
                                FLUJNEGO fn = new FLUJNEGO();
                                fn.NUM_DOC = lstD[x].NUM_DOC;
                                DateTime fecham = mm.Date;
                                fn.FECHAM = fecham;
                                fn.FECHAC = lstD[x].FECHAC;
                                fn.KUNNR  = arrPiNN[0];
                                var        cm  = arrAprNum[0].ToString();
                                Comentario com = new Comentario();
                                cm += com.getComment(mm.Body, mm.ContentType);
                                ////cm += " - " + mm.Body;
                                var cpos = db.FLUJNEGOes.Where(h => h.NUM_DOC.Equals(fn.NUM_DOC)).ToList().Count;
                                fn.POS        = cpos + 1;
                                fn.COMENTARIO = cm;
                                db.FLUJNEGOes.Add(fn);
                                db.SaveChanges();
                            }
                        }
                        else if (arrAprNum[0].Trim() == "TengoObservaciones" || arrAprNum[0].Trim() == "Tengo Observaciones")
                        {
                            for (int x = 0; x < lstD.Count; x++)
                            {
                                FLUJNEGO fn = new FLUJNEGO();
                                fn.NUM_DOC = lstD[x].NUM_DOC;
                                fn.FECHAC  = lstD[x].FECHAC;
                                DateTime fecham = mm.Date;
                                fn.FECHAM = fecham;
                                fn.KUNNR  = arrPiNN[0];
                                var        cm  = arrAprNum[0] + " ";
                                Comentario com = new Comentario();
                                cm += com.getComment(mm.Body, mm.ContentType);
                                ////cm += " - " + mm.Body;
                                var cpos = db.FLUJNEGOes.Where(h => h.NUM_DOC.Equals(fn.NUM_DOC)).ToList().Count;
                                fn.POS        = cpos + 1;
                                fn.COMENTARIO = cm;
                                db.FLUJNEGOes.Add(fn);
                                db.SaveChanges();
                            }
                        }
                        else
                        {
                            //Hubo algun error
                            break;
                        }
                    }
                    //para marcar el mensaje como leido
                    ic.AddFlags(Flags.Seen, mm);
                }
            }
            catch (Exception ex)
            {
                log.escribeLog("ERROR - " + ex.InnerException.ToString());
                ////throw new Exception(ex.InnerException.ToString());
            }
            finally
            {
                ic.Dispose();
            }
        }
Beispiel #24
0
        private void GetFolders()
        {
            this.Cursor = Cursors.WaitCursor;

            Account account = accounts[iTalk_TabControl.SelectedIndex];

            try
            {
                _client.Logout();
                Console.WriteLine("Logout succeeded!");
            }
            catch
            {
                Console.WriteLine("Logout failed!");
            }

            _client = new ImapClient();

            //Create POP3 client with parameters needed
            //URL of host to connect to
            _client.Host = account.Host;
            //TCP port for connection
            _client.Port = (ushort)account.Port;
            //Username to login to the POP3 server
            _client.Username = account.Username;
            //Password to login to the POP3 server
            _client.Password = account.Password;

            _client.SSLInteractionType = Email.Net.Common.Configurations.EInteractionType.SSLPort;

            try
            {
                //Login to the server
                CompletionResponse response = _client.Login();
                if (response.CompletionResult != ECompletionResponseType.OK)
                {
                    MessageBox.Show("Error", String.Format("Connection error:\n {0}", response.Message), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    //Get all messages to know the uid
                    Mailbox folders = _client.GetMailboxTree();

                    iTalk.iTalk_TabControl tab = tabs[iTalk_TabControl.SelectedIndex];
                    tab.TabPages.Clear();

                    for (int i = 0; i <= folders.Children.Count - 1; i++)
                    {
                        tab.TabPages.Add(folders.Children[i].DisplayName + " - " + _client.GetMessageCount(folders.Children[i]));
                    }

                    GetMessages();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }

            this.Cursor = Cursors.Default;
        }
        private DashBoardMailBoxJob ReceiveMails()
        {
            DashBoardMailBoxJob model = new DashBoardMailBoxJob();

            model.Inbox = new List <MailMessege>();

            try
            {
                EmailConfiguration email = new EmailConfiguration();
                email.POPServer    = "imap.gmail.com"; // type your popserver
                email.POPUsername  = "";               // type your username credential
                email.POPpassword  = "";               // type your password credential
                email.IncomingPort = "993";
                email.IsPOPssl     = true;


                int        success = 0;
                int        fail    = 0;
                ImapClient ic      = new ImapClient(email.POPServer, email.POPUsername, email.POPpassword, AuthMethods.Login, Convert.ToInt32(email.IncomingPort), (bool)email.IsPOPssl);
                // Select a mailbox. Case-insensitive
                ic.SelectMailbox("INBOX");
                int i        = 1;
                int msgcount = ic.GetMessageCount("INBOX");
                int end      = msgcount - 1;
                int start    = msgcount - 40;
                // Note that you must specify that headersonly = false
                // when using GetMesssages().
                MailMessage[] mm = ic.GetMessages(start, end, false);
                foreach (var item in mm)
                {
                    MailMessege obj = new MailMessege();
                    try
                    {
                        obj.UID      = item.Uid;
                        obj.subject  = item.Subject;
                        obj.sender   = item.From.ToString();
                        obj.sendDate = item.Date;
                        if (item.Attachments == null)
                        {
                        }
                        else
                        {
                            obj.Attachments = item.Attachments;
                        }

                        model.Inbox.Add(obj);
                        success++;
                    }
                    catch (Exception e)
                    {
                        DefaultLogger.Log.LogError(
                            "TestForm: Message fetching failed: " + e.Message + "\r\n" +
                            "Stack trace:\r\n" +
                            e.StackTrace);
                        fail++;
                    }
                    i++;
                }
                ic.Dispose();
                model.Inbox = model.Inbox.OrderByDescending(m => m.sendDate).ToList();
                model.mess  = "Mail received!\nSuccesses: " + success + "\nFailed: " + fail + "\nMessage fetching done";

                if (fail > 0)
                {
                    model.mess = "Since some of the emails were not parsed correctly (exceptions were thrown)\r\n" +
                                 "please consider sending your log file to the developer for fixing.\r\n" +
                                 "If you are able to include any extra information, please do so.";
                }
            }

            catch (Exception e)
            {
                model.mess = "Error occurred retrieving mail. " + e.Message;
            }
            finally
            {
            }
            return(model);
        }
Beispiel #26
0
 public int GetMessageCount()
 {
     return(clientImap.GetMessageCount());
 }
        public List <Expenses> GetMails(string _client_id, string _client_secret)
        {
            CustomMailService result      = new CustomMailService();
            List <Expenses>   emailModels = new List <Expenses>();
            //If you want to test new gmail account,
            //Go to the browser, log off, log in with the new account,
            //and then change this 'tmpUser'
            var tmpUser = "******";

            try
            {
                result.credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets {
                    ClientId = _client_id, ClientSecret = _client_secret
                },
                                                                                new[] { "https://mail.google.com/ email" },
                                                                                tmpUser,
                                                                                CancellationToken.None,
                                                                                new FileDataStore("Analytics.Auth.Store")).Result;
            }
            catch (Exception ex)
            {
            }

            if (result.credential != null)
            {
                result.service = new PlusService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = result.credential,
                    ApplicationName       = "Google mail",
                });


                Google.Apis.Plus.v1.Data.Person me = result.service.People.Get("me").Execute();

                Google.Apis.Plus.v1.Data.Person.EmailsData myAccountEmail = me.Emails.Where(a => a.Type == "account").FirstOrDefault();

                // Connect to the IMAP server. The 'true' parameter specifies to use SSL
                // which is important (for Gmail at least)
                ImapClient imapClient = new ImapClient("imap.gmail.com", myAccountEmail.Value, result.credential.Token.AccessToken,
                                                       ImapClient.AuthMethods.SaslOAuth, 993, true);

                var mailBox = imapClient.SelectMailbox("FNB");

                Console.WriteLine("ListMailboxes");

                Console.WriteLine(mailBox.Name);
                var original = Console.ForegroundColor;

                var examine = imapClient.Examine(mailBox.Name);
                if (examine != null)
                {
                    Console.WriteLine(" - Count: " + imapClient.GetMessageCount());

                    //Get One Email per folder

                    MailMessage[] mm = imapClient.GetMessages(0, imapClient.GetMessageCount());
                    Console.ForegroundColor = ConsoleColor.Blue;
                    var counter = 0;
                    foreach (MailMessage m in mm)
                    {
                        if (m.Date > DateTime.Now.AddDays(-30))
                        {
                            if (m.Subject.Contains("reserved for purchase") || m.Subject.Contains("paid from cheq"))
                            {
                                var substring = m.Subject.Substring(7, 10);
                                var number    = Regex.Split(substring, @"[^0-9\.]+")[1];
                                var amount    = Convert.ToDouble(number, CultureInfo.InvariantCulture);
                                var email     = new Expenses()
                                {
                                    PaymentType = PaymentType.Bill, Name = m.Subject, Amount = amount, Id = m.MessageID, PaymentDate = m.Date
                                };
                                if (m.Subject.Contains("paid from cheq"))
                                {
                                    email.PaymentType = PaymentType.Buy;
                                }
                                emailModels.Add(email);
                                counter++;
                            }
                        }
                    }
                }
                else
                {
                }

                imapClient.Dispose();
            }
            return(emailModels);
        }
Beispiel #28
0
        private void button8_Click(object sender, EventArgs e)
        {
            lstMsg.Visible = false;
            if (textBox3.Text == "" || textBox2.Text == "")
            {
                MessageBox.Show("Lütfen mail adresi ve şifrenizi giriniz.");
            }
            else
            {
                if (Regex.IsMatch(textBox3.Text, @"(@)"))
                {
                    this.Size     = new Size(1454, 664);
                    this.Location = new Point(50, 50);
                    username      = textBox3.Text.Split('@')[0];
                    domain        = textBox3.Text.Split('@')[1];

                    lblMsg.Visible = true;
                    i = 0;
                    lstMsg.Items.Clear();
                    if (domain == "hotmail.com" || domain == "std.yildiz.edu.tr")
                    {
                        ConnectToExchangeServer();
                        TimeSpan ts   = new TimeSpan(0, -24, 0, 0);
                        DateTime date = DateTime.Now.Add(ts);
                        SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);

                        if (exchange != null)
                        {
                            PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
                            itempropertyset.RequestedBodyType = BodyType.Text;
                            ItemView itemview = new ItemView(1000);
                            itemview.PropertySet = itempropertyset;

                            //FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, "subject:TODO", itemview);

                            lstMsg.Width  = 1170;
                            lstMsg.Height = 450;
                            button8.Text  = "Yenile";
                            try
                            {
                                FindItemsResults <Item> findResults = exchange.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(100));
                                foreach (Item item in findResults)
                                {
                                    lstMsg.Visible = true;
                                    item.Load(itempropertyset);
                                    String content = item.Body;
                                    icerikler[i] = content;


                                    var input = new Input {
                                        Text = content
                                    };
                                    var prediction = predictor.Predict(input);


                                    double skor = Cast(prediction.Probability, typeof(double));

                                    String durum;
                                    if ((Convert.ToBoolean(prediction.Prediction) ? "Spam" : "Not spam") == "Spam")
                                    {
                                        durum = "YES";
                                    }
                                    else
                                    {
                                        durum = "NO";
                                    }

                                    EmailMessage message = EmailMessage.Bind(exchange, item.Id);
                                    basliklar[i] = message.Subject;
                                    i++;
                                    ListViewItem listitem = new ListViewItem(new[]
                                    {
                                        message.DateTimeReceived.ToString(), message.From.Name.ToString() + "(" + message.From.Address.ToString() + ")", message.Subject,
                                        content, durum, skor.ToString("N2")
                                    });

                                    lstMsg.Items.Add(listitem);
                                }
                                if (findResults.Items.Count <= 0)
                                {
                                    lstMsg.Items.Add("Yeni Mail Bulunamadı.!!");
                                }
                                colorListcolor(lstMsg);
                            }
                            catch
                            {
                                MessageBox.Show("Mail adresi veya şifre yanlış.");
                                textBox3.Text  = "";
                                textBox2.Text  = "";
                                lblMsg.Text    = "";
                                lblMsg.Visible = false;
                                button8.Text   = "Giriş";
                                Screen screen = Screen.FromControl(this);

                                Rectangle workingArea = screen.WorkingArea;
                                this.Location = new Point()
                                {
                                    X = Math.Max(workingArea.X, workingArea.X + (workingArea.Width - this.Width) / 2),
                                    Y = Math.Max(workingArea.Y, workingArea.Y + (workingArea.Height - this.Height) / 2)
                                };
                            }
                        }
                    }
                    else if (domain == "gmail.com")
                    {
                        lblMsg.Text = "IMAP Server'a bağlanılıyor....";
                        lblMsg.Refresh();
                        try
                        {
                            IC          = new ImapClient("imap.gmail.com", textBox3.Text, textBox2.Text, AuthMethods.Login, 993, true);
                            lblMsg.Text = "IMAP Server'a bağlandı.\nGünlük Mailler Gösteriliyor.";
                            lblMsg.Refresh();
                            IC.SelectMailbox("INBOX");
                            int mailCount = IC.GetMessageCount();
                            mailCount--;
                            var      Email        = IC.GetMessage(mailCount);
                            DateTime localDate    = DateTime.Now;
                            TimeSpan baseInterval = new TimeSpan(24, 0, 0);
                            var      value        = localDate.Subtract(Email.Date);

                            lstMsg.Visible = true;
                            lstMsg.Width   = 1170;
                            lstMsg.Height  = 450;
                            button8.Text   = "Yenile";

                            while (TimeSpan.Compare(baseInterval, value) == 1)
                            {
                                basliklar[i] = Email.Subject.ToString();
                                icerikler[i] = Email.Body.ToString();
                                i++;


                                var input = new Input {
                                    Text = Email.Body
                                };
                                var prediction = predictor.Predict(input);

                                double skor = Cast(prediction.Probability, typeof(double));

                                String durum;
                                if ((Convert.ToBoolean(prediction.Prediction) ? "Spam" : "Not spam") == "Spam")
                                {
                                    durum = "YES";
                                }
                                else
                                {
                                    durum = "NO";
                                }
                                var          content  = Email.Body.ToString();
                                ListViewItem listitem = new ListViewItem(new[]
                                {
                                    Email.Date.ToString(), Email.From.Address.ToString(), Email.Subject.ToString(),
                                    content, durum, skor.ToString("N2")
                                });

                                lstMsg.Items.Add(listitem);
                                //MessageBox.Show(Email.Subject.ToString());
                                mailCount--;
                                Email = IC.GetMessage(mailCount);
                                value = localDate.Subtract(Email.Date);
                            }
                            colorListcolor(lstMsg);
                        }
                        catch
                        {
                            MessageBox.Show("Lütfen email güvenlik ayarlarından Daha az güvenli uygulamalara izin ver: AÇIK yapınız.");
                        }
                    }
                    else
                    {
                        MessageBox.Show("Geçersiz bir domain ismi girdiniz.Lütfen kontrol edin!");
                    }
                }
                else
                {
                    MessageBox.Show("Lütfen doğru bir mail formatı giriniz.");
                }
            }
        }
Beispiel #29
0
    protected void Page_Load(object sender, EventArgs e)
    {
        int page = -1;

        if (Request.QueryString["page"] == null)
        {
            Response.Redirect("ImapClientProtocolAll.aspx?page=1");
            Response.Flush();
            Response.End();
        }
        else
        {
            page = Convert.ToInt32(Request.QueryString["page"]);
        }
        try
        {
            Email    = Session["email"].ToString();
            Password = Session["pwd"].ToString();

            int totalEmails;
            //List<EMail> emails;
            string             emailAddress;
            EmailConfiguration email = new EmailConfiguration();
            email.IMAPServer   = "imap.gmail.com"; // type your popserver
            email.IMAPUsername = Email;            // type your username credential
            email.IMAPpassword = Password;         // type your password credential
            email.IncomingPort = "993";
            email.IsIMAPssl    = true;
            int success = 0;
            //int fail = 0;


            DashBoardMailBoxJob model = new DashBoardMailBoxJob();
            ImapClient          ic    = new ImapClient(email.IMAPServer, email.IMAPUsername, email.IMAPpassword, AuthMethods.Login, Convert.ToInt32(email.IncomingPort), (bool)email.IsIMAPssl);
            ic.SelectMailbox("INBOX");
            uids = ic.Search("ALL");
            int co = uids.Count();
            totalEmails = ic.GetMessageCount();

            emailAddress = Email;


            int totalPages;
            int mod = (co) % NoOfEmailsPerPage;
            if (mod == 0)
            {
                totalPages = (co) / NoOfEmailsPerPage;
            }
            else
            {
                totalPages = ((co - mod) / NoOfEmailsPerPage) + 1;
            }

            int i = 0;
            foreach (var uid in uids)
            {
                MailMessege obj     = new MailMessege();
                var         message = ic.GetMessage(uid);

                obj.sender   = message.From.ToString();
                obj.sendDate = message.Date;
                obj.subject  = message.Subject;
                obj.UID      = message.Uid; //UID is unique identifier assigned to each message by mail server
                if (message.Attachments == null)
                {
                }
                else
                {
                    obj.Attachments = message.Attachments;
                }
                //model.Inbox.Add(obj);
                success++;
                int       emailId = ((page - 1) * NoOfEmailsPerPage) + i + 1;
                TableCell noCell  = new TableCell();
                noCell.CssClass = "emails-table-cell";
                noCell.Text     = Convert.ToString(emailId);
                TableCell fromCell = new TableCell();
                fromCell.CssClass = "emails-table-cell";
                fromCell.Text     = obj.sender;
                TableCell subjectCell = new TableCell();
                subjectCell.CssClass       = "emails-table-cell";
                subjectCell.Style["width"] = "300px";
                subjectCell.Text           = String.Format(DisplayEmailLink, emailId, obj.subject);
                TableCell dateCell = new TableCell();
                dateCell.CssClass = "emails-table-cell";
                if (obj.sendDate != DateTime.MinValue)
                {
                    dateCell.Text = obj.sendDate.ToString();
                }
                TableRow emailRow = new TableRow();
                emailRow.Cells.Add(noCell);
                emailRow.Cells.Add(fromCell);
                emailRow.Cells.Add(subjectCell);
                emailRow.Cells.Add(dateCell);
                EmailsTable.Rows.AddAt(2 + i, emailRow);
                i = i + 1;
            }

            if (totalPages > 1)
            {
                if (page > 1)
                {
                    PreviousPageLiteral.Text = String.Format(SelfLink, page - 1, "Previous Page");
                }
                if (page > 0 && page < totalPages)
                {
                    NextPageLiteral.Text = String.Format(SelfLink, page + 1, "Next Page");
                }
            }
            EmailFromLiteral.Text  = Convert.ToString(((page - 1) * NoOfEmailsPerPage) + 1);
            EmailToLiteral.Text    = Convert.ToString(page * NoOfEmailsPerPage);
            EmailTotalLiteral.Text = Convert.ToString(totalEmails);
            EmailLiteral.Text      = emailAddress;
        }

        catch (Exception ex)
        {
            Response.Redirect("Login.aspx");
        }
    }
        public static GAAutentication Autenticate(string _client_id, string _client_secret)
        {
            GAAutentication result = new GAAutentication();

            //If you want to test new gmail account,
            //Go to the browser, log off, log in with the new account,
            //and then change this 'tmpUser'
            var tmpUser = "******";

            try
            {
                result.credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets {
                    ClientId = _client_id, ClientSecret = _client_secret
                },
                                                                                new[] { "https://mail.google.com/ email" },
                                                                                tmpUser,
                                                                                CancellationToken.None,
                                                                                new FileDataStore("Analytics.Auth.Store")).Result;
            }
            catch (Exception ex)
            {
            }

            if (result.credential != null)
            {
                result.service = new PlusService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = result.credential,
                    ApplicationName       = "Google mail",
                });


                Google.Apis.Plus.v1.Data.Person me = result.service.People.Get("me").Execute();

                Google.Apis.Plus.v1.Data.Person.EmailsData myAccountEmail = me.Emails.Where(a => a.Type == "account").FirstOrDefault();

                // Connect to the IMAP server. The 'true' parameter specifies to use SSL
                // which is important (for Gmail at least)
                ImapClient ic = new ImapClient("imap.gmail.com", myAccountEmail.Value, result.credential.Token.AccessToken,
                                               ImapClient.AuthMethods.SaslOAuth, 993, true);

                var listOfMainboxes = ic.ListMailboxes(string.Empty, "*");
                Console.WriteLine("ListMailboxes");
                foreach (Mailbox mb in listOfMainboxes)
                {
                    Console.WriteLine(mb.Name);
                    var original = Console.ForegroundColor;

                    var examine = ic.Examine(mb.Name);
                    if (examine != null)
                    {
                        //Count?
                        ic.SelectMailbox(mb.Name);
                        Console.WriteLine(" - Count: " + ic.GetMessageCount());

                        //Get One Email per folder
                        MailMessage[] mm = ic.GetMessages(0, 0);
                        Console.ForegroundColor = ConsoleColor.Blue;
                        foreach (MailMessage m in mm)
                        {
                            Console.WriteLine(" - " + m.Subject + " " + m.Date);
                        }
                        Console.ForegroundColor = original;
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.Error.WriteLine("* Folder doesn't exists: " + mb.Name);
                        Console.ForegroundColor = original;
                    }
                }

                /*
                 * // Select a mailbox. Case-insensitive
                 * ic.SelectMailbox("INBOX");
                 *
                 * Console.WriteLine(ic.GetMessageCount());
                 * // Get the first *11* messages. 0 is the first message;
                 * // and it also includes the 10th message, which is really the eleventh ;)
                 * // MailMessage represents, well, a message in your mailbox
                 * MailMessage[] mm = ic.GetMessages(0, 10);
                 * foreach (MailMessage m in mm)
                 * {
                 *  Console.WriteLine(m.Subject + " " + m.Date.ToString());
                 * }
                 * // Probably wiser to use a using statement
                 */
                ic.Dispose();
            }
            return(result);
        }
Beispiel #31
0
 public static void loadAllMessages()
 {
     mMailMessages = mImapClient.GetMessages(mImapClient.GetMessageCount(), 0);
 }