private void Timer1_Tick(object sender, EventArgs e)
        {
            OpenPop.Pop3.Pop3Client client = new OpenPop.Pop3.Pop3Client();
            client.Connect("pop.gmail.com", 995, true);
            try
            {
                client.Authenticate(txtAddress.Text, txtPassword.Text);
                int messageCount = client.GetMessageCount();

                if (count == -1)
                {
                    count = messageCount;
                }

                for (int i = messageCount; i > count; i--)
                {
                    txtNewMail.Text            += client.GetMessage(i).Headers.Subject + Environment.NewLine;
                    notifyIcon1.BalloonTipIcon  = ToolTipIcon.Info;
                    notifyIcon1.BalloonTipTitle = "New mail arrived";
                    notifyIcon1.BalloonTipText  = client.GetMessage(i).Headers.Subject;
                    notifyIcon1.ShowBalloonTip(3000);
                }
                count = messageCount;
            }
            catch (OpenPop.Pop3.Exceptions.InvalidLoginException)
            {
                txtNewMail.Text            += "Dose not accept pop3";
                notifyIcon1.BalloonTipIcon  = ToolTipIcon.Info;
                notifyIcon1.BalloonTipTitle = "Error Occured";
                notifyIcon1.BalloonTipText  = "Dose not accept pop3";
                notifyIcon1.ShowBalloonTip(3000);
            }
        }
Exemple #2
0
        public static List<Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password)
        {
            // The client disconnects from the server when being disposed

            using (OpenPop.Pop3.Pop3Client client = new OpenPop.Pop3.Pop3Client())
            {
                // Connect to the server
                client.Connect(hostname, port, useSsl);

                // Authenticate ourselves towards the server
                client.Authenticate(username, password);

                // Get the number of messages in the inbox
                int messageCount = client.GetMessageCount();

                // We want to download all messages
                List<Message> allMessages = new List<Message>(messageCount);

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

                // Now return the fetched messages
                return allMessages;
            }
        }
Exemple #3
0
        public static string FindEmailBySubject(string subject)
        {
            using (OpenPop.Pop3.Pop3Client client = new OpenPop.Pop3.Pop3Client())
            {
                client.Connect("pop.gmail.com", 995, true);
                client.Authenticate("recent:[email protected]", "pass");

                if (client.Connected)
                {
                    int            count       = client.GetMessageCount();
                    List <Message> allMessages = new List <Message>(count);
                    for (int i = count; i > 0; i--)
                    {
                        allMessages.Add(client.GetMessage(i));
                    }

                    foreach (Message msg in allMessages)
                    {
                        if (subject == msg.Headers.Subject)
                        {
                            return(subject);
                        }
                    }
                }
                return("");
            }
        }
Exemple #4
0
        public static void ListEmail()
        {
            using (OpenPop.Pop3.Pop3Client client = new OpenPop.Pop3.Pop3Client())
            {
                client.Connect("pop.gmail.com", 995, true);
                client.Authenticate("recent:[email protected]", "pass");

                if (client.Connected)
                {
                    int            count       = client.GetMessageCount();
                    List <Message> allMessages = new List <Message>(count);
                    for (int i = count; i > 0; i--)
                    {
                        allMessages.Add(client.GetMessage(i));
                    }

                    foreach (Message msg in allMessages)
                    {
                        string subject = msg.Headers.Subject;
                        string date    = msg.Headers.Date;

                        OpenPop.Mime.MessagePart plainText = msg.FindFirstPlainTextVersion();
                        Console.WriteLine("Subject: " + subject);
                        Console.WriteLine("Date: " + date);
                        Console.WriteLine("Body: " + plainText.GetBodyAsText());
                    }
                }
            }
        }
Exemple #5
0
        static void testEmailPop()
        {
            string _popServer;
            int    _popPort;
            bool   _popSSL;

            string _popUser;
            string _popPassword;

            _popServer = ConfigurationManager.AppSettings["PopServer"];
            _popPort   = int.Parse(ConfigurationManager.AppSettings["PopPort"]);
            _popSSL    = bool.Parse(ConfigurationManager.AppSettings["PopSSL"]);

            _popUser     = ConfigurationManager.AppSettings["PopUser"];
            _popPassword = ConfigurationManager.AppSettings["PopPassword"];

            try {
                using (var popClient = new OpenPop.Pop3.Pop3Client()) {
                    popClient.Connect(_popServer, _popPort, _popSSL);
                    popClient.Authenticate(_popUser, _popPassword);

                    Console.WriteLine("SUCCESS (pop client)");

                    popClient.Disconnect();
                }
            } catch (Exception e) {
                Console.WriteLine("FAIL (pop client)");
                Console.WriteLine(e.ToString());
            }
        }
Exemple #6
0
        public static void ReadEmail()
        {
            using (OpenPop.Pop3.Pop3Client client = new OpenPop.Pop3.Pop3Client())
            {
                client.Connect("pop.gmail.com", 995, true);
                client.Authenticate("recent:[email protected]", "pass");

                if (client.Connected)
                {
                    Console.WriteLine("Checking inbox");
                    var count = client.GetMessageCount();
                    OpenPop.Mime.Message     message   = client.GetMessage(count);
                    OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion();

                    builder.Append("Subject: " + message.Headers.Subject + "\n");
                    builder.Append("Date: " + message.Headers.Date + "\n");
                    builder.Append("Body: " + plainText.GetBodyAsText());
                    Console.WriteLine(builder.ToString());

                    //verifica se existem anexos e caso sim salva-os na pasta
                    var att = message.FindAllAttachments();

                    foreach (var ado in att)
                    {
                        ado.Save(new System.IO.FileInfo(System.IO.Path.Combine(@"C:\Users\wviegas\Documents\will", ado.FileName)));
                    }
                }
            }
        }
Exemple #7
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            // 初期化
            OpenPop.Pop3.Pop3Client client = new OpenPop.Pop3.Pop3Client();
            // Gmail接続
            client.Connect("pop.gmail.com", 995, true);
            // ログイン
            client.Authenticate(textBox1.Text, textBox2.Text);

            int messageCount = client.GetMessageCount();

            if (count == -1)
            {
                count = messageCount;
            }

            for (int i = messageCount; i > count; i--)
            {
                textBox3.Text += client.GetMessage(i).Headers.Subject + "\r\n";
                notifyIcon1.BalloonTipIcon  = ToolTipIcon.Info;
                notifyIcon1.BalloonTipTitle = "メールが届きました";
                notifyIcon1.BalloonTipText  = client.GetMessage(i).Headers.Subject;
                notifyIcon1.ShowBalloonTip(3000);
            }

            count = messageCount;
        }
Exemple #8
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            //  NuGetで追加したOpenPop.NETのインスタンスを生成する
            OpenPop.Pop3.Pop3Client client = new OpenPop.Pop3.Pop3Client();

            //  Gmailに接続する
            client.Connect("pop.gmail.com", 995, true);

            //  IDとパスワードのチェック
            client.Authenticate(txtAddress.Text, txtPassword.Text);

            //
            int messageCount = client.GetMessageCount();

            // 
            if (count == -1)
            {
                count = messageCount;
            }

            //
            for (int i = messageCount; i > count; i--)
            {
                textNewMail.Text += client.GetMessage(i).Headers.Subject + Environment.NewLine;

                notifyIcon1.BalloonTipIcon  = ToolTipIcon.Info;
                notifyIcon1.BalloonTipTitle = "メールが届いたじぇ";
                notifyIcon1.BalloonTipText  = client.GetMessage(i).Headers.Subject;
                notifyIcon1.ShowBalloonTip(3000);
            }
            count = messageCount;
        }
        private void carregarButton_Click(object sender, EventArgs e)
        {
            try {
                Cursor = Cursors.WaitCursor;

                //bloco “using” (para que a conexão seja fechada automaticamente quando sairmos do bloco “using“).
                using (var client = new OpenPop.Pop3.Pop3Client()) {
                    client.Connect(_hostname, _port, _useSsl);
                    client.Authenticate(_username, _password);

                    //Após isso, temos que perguntar para o servidor qual é quantidade de e-mails que será baixada.Precisamos disso porque faremos um “loop” pelas mensagens para baixar uma a uma.O método GetMessageCount é método responsável por retornar a quantidade de mensagens.
                    //Com a quantidade de mensagens, podemos fazer um loop. Note que, se quisermos baixar os e-mails mais recentes primeiro, devemos começar do número mais alto até o número “1” (os servidores POP consideram “1” como o menor índice, e não “0” como estamos acostumados com o C#):
                    _emails.Clear();
                    int messageCount = client.GetMessageCount();

                    for (int i = messageCount; i > 0; i--)
                    {
                        var popEmail = client.GetMessage(i);

                        //Dentro da mensagem baixada pela biblioteca OpenPop.NET, temos basicamente duas versões da mensagem: uma em formato texto e a outra em formato HTML. Para recuperarmos a versão da mensagem em formato texto, utilizamos o método “FindFirstPlainTextVersion“. Já para baixarmos a versão HTML, utilizamos o método “FindFirstHtmlVersion“
                        var popText = popEmail.FindFirstPlainTextVersion();
                        var popHtml = popEmail.FindFirstHtmlVersion();

                        string mailText = string.Empty;
                        string mailHtml = string.Empty;
                        if (popText != null)
                        {
                            mailText = popText.GetBodyAsText();
                        }

                        if (popHtml != null)
                        {
                            mailHtml = popHtml.GetBodyAsText();
                        }

                        //armazená-las dentro da nossa lista de e-mails (atributo chamado “_emails” no nível do formulário)
                        _emails.Add(new Email()
                        {
                            Id            = popEmail.Headers.MessageId,
                            Assunto       = popEmail.Headers.Subject,
                            De            = popEmail.Headers.From.Address,
                            Para          = string.Join("; ", popEmail.Headers.To.Select(to => to.Address)),
                            Data          = popEmail.Headers.DateSent,
                            ConteudoTexto = mailText,
                            ConteudoHtml  = !string.IsNullOrWhiteSpace(mailHtml) ? mailHtml : mailText
                        });
                    }

                    AtualizarDataBindings();
                }
            }
            finally {
                Cursor = Cursors.Default;
            }
        }
Exemple #10
0
 public bool Connect(string hostname, int port, bool useSsl)
 {
     try
     {
         client = new OpenPop.Pop3.Pop3Client();
         client.Connect(hostname, port, false);
         Hostname = hostname;
         Port     = port;
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Exemple #11
0
        internal void get()
        {
            client.Connect("pop.gmail.com", 995, true);                      // Connects to the pop3 server for gmail
            client.Authenticate("*****@*****.**", "Max1Oreo2"); // Login Credentials



            var count = client.GetMessageCount();                                     // gets the message count

            OpenPop.Mime.Message     message   = client.GetMessage(count);            // Gets the message that correlates with the count variable- in this case 0
            OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion(); // Gets the first messsages body
            builder.Append(plainText.GetBodyAsText());                                //Puts the email's text into a StringBuilder where it can be outputed
            Console.WriteLine(builder.ToString());                                    //Outputs the email to the console
            builder.Clear();                                                          //Clears the String Builder
            client.Disconnect();                                                      // Disconnects from the Pop3 Client
        }
Exemple #12
0
        public bool Connect()
        {
            try
            {
                Disconnect();

                _popClient = new OpenPop.Pop3.Pop3Client();
                _popClient.Connect(_server, _port, _useSSl);
                _popClient.Authenticate(_user, _password);

                return(true);
            }
            catch (Exception ex)
            {
            }

            return(false);
        }
Exemple #13
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            OpenPop.Pop3.Pop3Client client = new OpenPop.Pop3.Pop3Client();
            client.Connect("pop.gmail.com", 995, true);
            client.Authenticate(txtAddress.Text, txtPassword.Text);
            int messageCount = client.GetMessageCount();

            if (count == -1)
            {
                count = messageCount;
            }
            for (int i = messageCount; i > count; i--)
            {
                txtNewMail.Text            += client.GetMessage(i).Headers.Subject + "¥r¥n";
                notifyIcon1.BalloonTipIcon  = ToolTipIcon.Info;
                notifyIcon1.BalloonTipTitle = "メールが届きました";
                notifyIcon1.BalloonTipText  = client.GetMessage(i).Headers.Subject;
                notifyIcon1.ShowBalloonTip(3000);
            }
            count = messageCount;
        }
Exemple #14
0
        public IEnumerable <MailDto> ReceiveAsync(params string[] identifiers)
        {
            using (var client = new OpenPop.Pop3.Pop3Client())
            {
                client.Connect(this.Host, this.Port, this.EnableSsl);
                client.Authenticate(this.Email, this.Password.Decrypt());

                var uids = client.GetMessageUids();
                for (var i = 1; i <= uids.Count; i++)
                {
                    var uid = uids[i - 1];
                    if (!identifiers.Contains(uid))
                    {
                        var message = client.GetMessage(i);
                        yield return(this.CreateMail(message, uid));
                    }
                }

                client.Disconnect();
            }
        }
 public void Setup()
 {
     client = new OpenPop.Pop3.Pop3Client();
     client.Connect(server, port, useSsl);
     client.Authenticate(username, password);
 }
        public bool Execute()
        {
            // Get already processed messages list
            List <String> processedMessages = _context.ReferralEmails.Select(x => x.MessageID).ToList();

            if (processedMessages == null)
            {
                processedMessages = new List <string>();
            }

            // Get any un-processed messages
            OpenPop.Pop3.Pop3Client popClient = new OpenPop.Pop3.Pop3Client();
            popClient.Connect(_popServer, _popPort, _popSSL);
            popClient.Authenticate(_popUser, _popPassword);

            var messageIDs = popClient.GetMessageUids();

            for (int i = 0; i < messageIDs.Count; i++)
            {
                if (!processedMessages.Contains(messageIDs[i]))
                {
                    OpenPop.Mime.Message msg = null;
                    string msgStatus         = "";
                    string msgSubject        = "";
                    try
                    {
                        msg        = popClient.GetMessage(i + 1);
                        msgSubject = msg.Headers.Subject;
                        if (!_seedMode)
                        {
                            msgStatus = ProcessMessage(msg);
                        }
                    }
                    catch (System.Data.Entity.Validation.DbEntityValidationException ex) {
                        if (ex.EntityValidationErrors != null &&
                            ex.EntityValidationErrors.Count() > 0 &&
                            ex.EntityValidationErrors.First().ValidationErrors != null &&
                            ex.EntityValidationErrors.First().ValidationErrors.Count > 0)
                        {
                            string errorMessage = "An error occurred validating the referral."
                                                  + "\r\nID: " + messageIDs[i]
                                                  + "\r\nSubject: " + msgSubject
                                                  + "\r\nFirst Validation Error: " + ex.EntityValidationErrors.First().ValidationErrors.First().ErrorMessage;

                            _logger.LogError(errorMessage);
                            AABC.DomainServices.Email.SMTP.Send(_smtpAccount, "Referral Validation Error", errorMessage, _validationEmail);
                        }

                        else
                        {
                            string errorMessage = "An error occurred validating the referral."
                                                  + "\r\nID: " + messageIDs[i]
                                                  + "\r\nSubject: " + msgSubject
                                                  + "\r\nError Message: " + ex.Message;

                            _logger.LogError(errorMessage);
                            AABC.DomainServices.Email.SMTP.Send(_smtpAccount, "Referral Validation Error", errorMessage, _validationEmail);
                        }

                        msgStatus = "Validation Error";
                    }
                    catch (System.Exception ex)
                    {
                        string errorMessage = "An error occurred processing the referral."
                                              + "\r\nID: " + messageIDs[i]
                                              + "\r\nSubject: " + msgSubject
                                              + "\r\nError Message: " + ex.Message;

                        _logger.LogError(errorMessage);
                        AABC.DomainServices.Email.SMTP.Send(_smtpAccount, "Referral Error", errorMessage, _errorEmail);

                        msgStatus = "Errored";
                    }

                    _context.ReferralEmails.Add(new Data.Models.ReferralEmail()
                    {
                        MessageID      = messageIDs[i],
                        MessageSubject = msgSubject,
                        MessageStatus  = msgStatus,
                        ProcessedTime  = DateTime.Now
                    });
                    _context.SaveChanges();
                }
            }

            popClient.Disconnect();
            popClient.Dispose();

            return(true);
        }
Exemple #17
0
        public static void FetchAllMessages(object sender, DoWorkEventArgs e)
        {
            // Add messages from pop3 server to message database
            try
            {
                // Makes a new POP3 session
                // POP3 does not allow to check for new mails
                // * facepalm *
                popClient.Disconnect();
                popClient.Connect(currentUser.pop_hostname, currentUser.pop_port, currentUser.pop_ssl);
                popClient.Authenticate(currentUser.mailaddress, currentUser.password);
            }
            catch (SystemException err)
            {
                MessageBox.Show("Kunne ikke genoprette en forbindelse" + Environment.NewLine + err.Message);
            }

            // gets messagecount
            int messageCount = popClient.GetMessageCount();

            // progress of process
            int progress = 0;

            // the progress value when it was sent to the progressbar
            int lastProgress = 0;

            for (int i = messageCount; i > 0; i--)
            {
                OpenPop.Mime.Message msg = popClient.GetMessage(i);

                // We don't like the fact about messageId is optional,
                // so we make our own messageID by a md5 of
                //  - the sender's email
                //  - the tick value (ticks since 1. January year 1)
                //  - md5 of messageID (if it doesnt present then = md5 of "")
                //  - subject of the mail
                string id      = genMd5(string.Format("{0}_{1}_{2}_{3}", msg.Headers.From.MailAddress.Address, msg.Headers.DateSent.Ticks.ToString(), genMd5(msg.Headers.MessageId), msg.Headers.Subject));
                string from    = msg.Headers.From.MailAddress.Address;
                string subject = msg.Headers.Subject;
                string body    = "";

                // We prefer multipart if it's available
                if (msg.MessagePart.IsMultiPart)
                {
                    body = msg.FindFirstHtmlVersion().GetBodyAsText();
                }
                else
                {
                    body = msg.FindFirstPlainTextVersion().GetBodyAsText();
                }

                // Date sent to SQLite DateTime format
                DateTime sent_o = msg.Headers.DateSent;
                string   sent   = string.Format("{0:d4}-{1:d2}-{2:d2} {3:d2}:{4:d2}:{5:d2}", sent_o.Year, sent_o.Month, sent_o.Day, sent_o.Hour, sent_o.Minute, sent_o.Second);

                // Insert it (or not, if it already exists) to the SQLite database
                SQLiteCommand crCMD = new SQLiteCommand("INSERT OR IGNORE INTO messagetable (id,sender,subject,body,date) VALUES (@_id,@_sender,@_subject,@_body,datetime(strftime('%Y-%m-%d %H:%M:%S',@_sent)))", msgSqlCon);

                crCMD.Parameters.AddWithValue("@_id", id);
                crCMD.Parameters.AddWithValue("@_sender", from);
                crCMD.Parameters.AddWithValue("@_subject", subject);
                crCMD.Parameters.AddWithValue("@_body", MerMail.Symmetric.EncryptString(currentUser.encryption_key, body));
                crCMD.Parameters.AddWithValue("@_sent", sent);

                crCMD.ExecuteNonQuery();

                // calculate the progress percentage
                progress = (i * 100) / (messageCount);
                if (progress > lastProgress + 10)
                {
                    // if the progress is 10 percent higher than lastprogress,
                    // then report it to the progressBar, and set lastprogress
                    // to the progress percentage right now
                    (sender as BackgroundWorker).ReportProgress(progress);
                    lastProgress = progress;
                }
            }
        }
Exemple #18
0
        private static void CleanUpInbox()
        {
            OpenPop.Pop3.Pop3Client p3 = new OpenPop.Pop3.Pop3Client();
            int iPort = 110;

            iPort = 995;
            bool bSSL = false;

            bSSL = true;
            string sPopHost = Saved.Code.Common.GetBMSConfigurationKeyValue("outlookhost");
            string sPopUser = Saved.Code.Common.GetBMSConfigurationKeyValue("smtppopuser");
            string sPopPass = Saved.Code.Common.GetBMSConfigurationKeyValue("smtppoppassword");

            p3.Connect(sPopHost, iPort, bSSL, 7000, 7000, null);
            p3.Authenticate(sPopUser, sPopPass);
            int iCount = p3.GetMessageCount();
            int i      = 0;

            for (i = iCount; i > 0; i--)
            {
                try
                {
                    MessageHeader            h         = p3.GetMessageHeaders(i);
                    Message                  m         = p3.GetMessage(i);
                    OpenPop.Mime.MessagePart plainText = m.FindFirstPlainTextVersion();
                    OpenPop.Mime.MessagePart htmlPart  = m.FindFirstHtmlVersion();
                    string body     = "";
                    string myto     = m.Headers.Subject;
                    string mysentto = "";

                    if (myto != null)
                    {
                        string[] vTo = myto.Split(new string[] { "-" }, StringSplitOptions.None);
                        if (vTo.Length > 1)
                        {
                            mysentto = vTo[1].Trim();
                        }
                    }


                    if (plainText != null)
                    {
                        body += plainText.GetBodyAsText();
                    }
                    if (htmlPart != null)
                    {
                        body += htmlPart.GetBodyAsText();
                    }
                    bool fTotaled = false;
                    if (body.Contains("be delivered to one"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("hop count exceeded"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("A communication failure occurred"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("The email address you entered couldn't be found"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("The domain you attempted to contact"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("I'm afraid I wasn't able to deliver the following message"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("cannot be delivered"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("I was unable to deliver your message"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("Your message wasn't delivered"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("rejected your message to the following"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("Delivery to the following recipient failed permanently"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("This is a delivery failure notification message "))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("Delivery has failed to these recipients or groups"))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("There was a temporary problem delivering your message "))
                    {
                        fTotaled = true;
                    }
                    else if (body.Contains("The following addresses had permanent fatal errors"))
                    {
                        fTotaled = true;
                    }

                    else if (body.Contains("the receiving email server outside Office 365 reported ") || body.Contains("couldn't be delivered"))
                    {
                        fTotaled = true;
                    }

                    if (fTotaled)
                    {
                        string sql = "update Leads set Advertised=getdate() where email='" + mysentto + "'";
                        Saved.Code.Common.gData.Exec(sql);
                        p3.DeleteMessage(i);
                    }
                }
                catch (Exception)
                {
                }
            }

            p3.Disconnect();
        }
Exemple #19
0
        static void WeatherMailJob()
        {
            OpenPop.Pop3.Pop3Client mclient = new OpenPop.Pop3.Pop3Client();
            mclient.Connect("mail.cute.edu.tw", 110, false);
            mclient.Authenticate("weather", "0988163835");
            int cnt = mclient.GetMessageCount();
            Console.WriteLine("Message cnt:" + cnt);
            string bodytext;

            for (int i = 1; i <= cnt; i++)
            {
                try
                {
                    bodytext = "";
                    Message msg = mclient.GetMessage(i);
                    string from = msg.Headers.From.MailAddress.Address;

                    Console.WriteLine("from:" + from);

                    Console.WriteLine("subject:" + msg.Headers.Subject);
                    if (from != "*****@*****.**" && from != "*****@*****.**" && from != "*****@*****.**")
                        continue;
                    //  string b = msg.MessagePart.GetBodyAsText();
                    // string htmlString = @"<p>I'm HTML!</p>";
                    //   b= Regex.Replace(b, @"(<(.|\n)*?>|&nbsp;)", "");
                    //  Console.WriteLine(Program.StripHTML( b));
                    if (!msg.MessagePart.IsText)
                    {
                        MessagePart msgpart = msg.FindFirstPlainTextVersion();
                        if (msgpart != null && msgpart.IsText)
                        {
                            //  Console.WriteLine("body:" + msgpart.GetBodyAsText());

                            bodytext = msgpart.GetBodyAsText();
                        }

                    }
                    else
                    {

                        bodytext = msg.MessagePart.GetBodyAsText();
                    }

                    string txtbodytext = StripHTML(bodytext);
                    txtbodytext = txtbodytext.Replace("\r", "<br>");
                    Console.WriteLine("body:" + txtbodytext);
                    //   txtbodytext = txtbodytext.Replace("\r", "<br>");

                    if (LogToDB(msg, txtbodytext) || from == "*****@*****.**" || from == "*****@*****.**")
                    {

                        if (from == "*****@*****.**" || from == "*****@*****.**" || msg.Headers.Subject.Contains("颱風"))
                        {

            #if DEBUG
                            txtbodytext = "<img src=\"http://192.192.161.4/sshmc/logo.png\"><p>致 貴客戶,依中央氣象局發布資料,提醒您以下防災預警資訊:<br>" + txtbodytext;
                            SendMailToAllUser(msg.Headers.Subject.Replace("\n", ""), txtbodytext);
            #else
                         SendMailToAllUser(msg.Headers.Subject.Replace("\n", ""), bodytext);
            #endif
                        }
                        else
                        {
                            txtbodytext = "<img src=\"http://192.192.161.4/sshmc/logo.png\"><p>致 貴客戶,依中央氣象局發布資料,提醒您以下防災預警資訊:<br>" + txtbodytext;
                            SendMailToAllUser(msg.Headers.Subject.Replace("\n", ""), txtbodytext);
                        }
                    }

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            #if !DEBUG
            for (int i = 1; i <= cnt; i++)
                mclient.DeleteMessage(i);
            #endif

            mclient.Dispose();
            //    Console.ReadKey();
        }
        static void Main(string[] args)
        {
            var sustenido = (char)35;

            //Filtrar o assunto com esta Regex
            Regex regex = new Regex(@"\" + sustenido + @"\d+");

            const string host   = "email-ssl.com.br";
            const int    port   = 995;
            const bool   useSsl = true;

            const string username = "******";
            const string password = "******";

            using (OpenPop.Pop3.Pop3Client client = new OpenPop.Pop3.Pop3Client())
            {
                client.Connect(host, port, useSsl);

                client.Authenticate(username, password);

                int messageCount = client.GetMessageCount();

                var messages = new List <Message>(messageCount);

                var message      = client.GetMessage(messageCount);
                var match        = regex.IsMatch(message.Headers.Subject);
                int pendencia_id = 0;
                //Percorrer todas as mensagens
                for (int i = messageCount; i > 0; i--)
                {
                    message = client.GetMessage(i);
                    match   = regex.IsMatch(message.Headers.Subject);
                    if (match)
                    {
                        var Teste = regex.Match(message.Headers.Subject);
                        pendencia_id = int.Parse(Teste.Value.Replace(sustenido.ToString(), string.Empty));
                    }
                    else
                    {
                        pendencia_id = 0;
                    }

                    Console.WriteLine(pendencia_id);
                    Console.WriteLine(message.Headers.Subject);

                    messages.Add(message);
                    message.ToMailMessage();

                    System.Net.NetworkCredential testCreds = new System.Net.NetworkCredential("Login", "Password", "Empresa.LOCAL");

                    System.Net.CredentialCache testCache = new System.Net.CredentialCache();

                    testCache.Add(new Uri("\\\\10.0.1.3"), "Basic", testCreds);


                    //caminho do folder
                    string folder = @"\\10.0.1.3\Comum\Milton.Silva'";

                    //Criar folder
                    System.IO.Directory.CreateDirectory(folder);
                    //salvar arquivo
                    message.Save(new System.IO.FileInfo(folder + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".eml"));

                    //client.DeleteMessage(messageCount);

                    MailMessage mailMessage = new MailMessage();
                    //Endereço que irá aparecer no e-mail do usuário
                    mailMessage.From = new MailAddress("*****@*****.**");
                    //destinatarios do e-mail, para incluir mais de um basta separar por ponto e virgula

                    string to = "*****@*****.**";
                    mailMessage.To.Add(to);

                    //Assunto: o chamado “#98946: Balanca com conversor TCP” requer sua atenção.
                    // string assunto = "enviado por meio do simple farm";
                    mailMessage.Subject    = "O chamado " + message.Headers.Subject + " requer sua atenção";
                    mailMessage.IsBodyHtml = true;
                    //conteudo do corpo do e-mail
                    string mensagem = "<h1>Prezado</h1>" +
                                      "<p>Nosso processo automatizado recebeu este e-mail e " +
                                      "anexou no chamado e registrou que o mesmo foi encaminhado para sua atuação.</p>" +
                                      "<p>Favor ajustar o status imediatamente(visto que o cliente monitora pelo Portal)" +
                                      "e atuar no atendimento.</p> <p>Grato.</p><p>Processo Automatizado de Recepção de E-mail</p><br>";

                    var parts = message.MessagePart.MessageParts;

                    var bodyText = GetBody(parts);

                    mailMessage.Body = mensagem + bodyText;

                    //Salvando Imagem no folder
                    foreach (MessagePart emailAttachment in message.FindAllAttachments())
                    {
                        //-Definir variáveis
                        string OriginalFileName = emailAttachment.FileName;
                        string ContentID        = emailAttachment.ContentId;             // Se isso estiver definido, o anexo será inline.
                        string ContentType      = emailAttachment.ContentType.MediaType; // tipo de anexo pdf, jpg, png, etc.

                        //escreve o anexo no disco
                        System.IO.File.WriteAllBytes(folder + OriginalFileName, emailAttachment.Body); // sobrescreve MessagePart.Body com anexo
                        //salvando folder no disco
                        mailMessage.Attachments.Add(new Attachment(folder + OriginalFileName));
                    }

                    mailMessage.Priority = MailPriority.High;

                    //smtp do e-mail que irá enviar
                    SmtpClient smtpClient = new SmtpClient("email-ssl.com.br");
                    smtpClient.EnableSsl = false;
                    //credenciais da conta que utilizará para enviar o e-mail
                    smtpClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "Password");
                    //Mensagem em copia
                    MailAddress copy = new MailAddress("*****@*****.**");
                    mailMessage.CC.Add(copy);
                    smtpClient.Send(mailMessage);
                }
                //Após ler todos, apagar
                //client.DeleteAllMessages();

                // exclui uma mensagem através de seu ID .. o ID é na verdadea posição no web-mail da mensagem
                // para excluir o client precisa executar a operação de QUIT para realmente excluir (para ser atomico). Em outras palavras, precisa ser 'disposado'//Disconnect
                //client.DeleteMessage(messageCount);
            }

            Console.ReadLine();
        }
Exemple #21
0
        //
        // ===========================================================================================
        //
        public void bounceProcess(Contensive.BaseClasses.CPBaseClass cp)
        {
            try {
                CPCSBaseClass CS = cp.CSNew();
                string        MessageText;
                string[]      FilterLines;
                string[]      FilterText = Array.Empty <string>();
                int[]         FilterType = Array.Empty <int>();
                int           LinePtr;
                string[]      LineSplit;
                int           FilterLineCnt = 0;
                string        Filter;
                int           BounceType;
                string        EmailAddress;
                string        PopServer;
                int           popPort;
                string        POPServerUsername;
                string        POPServerPassword;
                int           EmailBounceProcessAction;
                bool          AllowEmailBounceProcessing;
                string        bounceLogPathPage;
                string        ActionTaken;
                string        FilterFilename;
                string        Filename     = "";
                DateTime      rightNowDate = DateTime.Now.Date;
                string        logDatePart  = rightNowDate.Year + rightNowDate.Month.ToString().PadLeft(2) + rightNowDate.Day.ToString().PadLeft(2);
                string        amazonMsg    = "An error occurred while trying to deliver the mail to the following recipients:" + "\r\n";
                //
                AllowEmailBounceProcessing = cp.Site.GetBoolean("AllowEmailBounceProcessing", false);
                if (AllowEmailBounceProcessing)
                {
                    PopServer = cp.Site.GetText("PopServer", "");
                    popPort   = cp.Site.GetInteger("popServerPort", 110);
                    if (popPort <= 0)
                    {
                        popPort = 110;
                    }
                    POPServerUsername = cp.Site.GetText("POPServerUsername", "");
                    POPServerPassword = cp.Site.GetText("POPServerPassword", "");
                    if ((PopServer == "") | (POPServerUsername == "") | (POPServerPassword == ""))
                    {
                        cp.Utils.AppendLog("AllowEmailBounceProcessing true but server, username or password is blank");
                    }
                    else
                    {
                        bounceLogPathPage        = @"BounceLog\" + logDatePart + @"\trace.txt";
                        FilterFilename           = @"\config\EmailBounceFilters.txt";
                        EmailBounceProcessAction = cp.Site.GetInteger("EmailBounceProcessAction", 0);
                        //
                        // Read in the filter file
                        //
                        if (true)
                        {
                            string copy;
                            copy = cp.CdnFiles.Read(FilterFilename);
                            if (copy == "")
                            {
                                cp.Utils.AppendLog(@"Bounce processing filters file \config\EmailBounceFilters.txt is empty");
                            }
                            else
                            {
                                copy          = copy.Replace("\r\n", "\r");
                                copy          = copy.Replace("\n", "\r");
                                FilterLines   = copy.Split('\r');
                                FilterLineCnt = FilterLines.Length;
                                FilterText    = new string[FilterLineCnt + 100 + 1];
                                FilterType    = new int[FilterLineCnt + 100 + 1];
                                //
                                //
                                //
                                for (LinePtr = 0; LinePtr <= FilterLineCnt - 1; LinePtr++)
                                {
                                    if (FilterLines[LinePtr] != "")
                                    {
                                        LineSplit           = FilterLines[LinePtr].Split(',');
                                        FilterText[LinePtr] = LineSplit[0];
                                        if (LineSplit.Length > 0)
                                        {
                                            FilterType[LinePtr] = cp.Utils.EncodeInteger(LineSplit[1]);
                                        }
                                    }
                                }
                                //
                                // add amazon
                                //
                                FilterText[FilterLineCnt] = amazonMsg;
                                FilterType[FilterLineCnt] = 2;
                                FilterLineCnt            += 1;
                            }
                        }
                        //
                        // Retrieve the emails
                        //
                        int    MessageCnt;
                        string headerList;
                        OpenPop.Mime.Message msg;
                        using (OpenPop.Pop3.Pop3Client pop = new OpenPop.Pop3.Pop3Client()) {
                            try {
                                pop.Connect(PopServer, popPort, true);
                                pop.Authenticate(POPServerUsername, POPServerPassword);
                                MessageCnt = pop.GetMessageCount();
                                //
                                cp.CdnFiles.Append(bounceLogPathPage, "\r\n" + "New bounce emails, cnt=" + MessageCnt);
                                //
                                for (int msgPtr = 1; msgPtr <= MessageCnt; msgPtr++)
                                {
                                    msg          = pop.GetMessage(msgPtr);
                                    headerList   = "";
                                    EmailAddress = "";
                                    headerList   = "";
                                    MessageText  = "";
                                    if (!msg.Headers.From.HasValidMailAddress)
                                    {
                                        //
                                        cp.CdnFiles.Append(bounceLogPathPage, "\n\r" + "email" + msgPtr + "-" + "email address not found");
                                    }
                                    else
                                    {
                                        EmailAddress = msg.Headers.From.Address;

                                        foreach (string key in msg.Headers.UnknownHeaders.AllKeys)
                                        {
                                            string keyValue = msg.Headers.UnknownHeaders[key];
                                            headerList += "\r\n" + key + "=" + keyValue;
                                        }

                                        OpenPop.Mime.MessagePart msgBody;
                                        msgBody = msg.FindFirstPlainTextVersion();
                                        if ((msgBody == null))
                                        {
                                            msgBody = msg.FindFirstHtmlVersion();
                                        }
                                        MessageText = "";
                                        if (!(msgBody == null))
                                        {
                                            MessageText = msgBody.GetBodyAsText();
                                        }

                                        if (string.IsNullOrEmpty(MessageText))
                                        {
                                            //
                                            cp.CdnFiles.Append(bounceLogPathPage, "\n\r" + "email" + msgPtr + "-" + "email has blank body");
                                        }
                                        else
                                        {
                                            //
                                            // Process them as they come in
                                            //
                                            if ((EmailAddress == "*****@*****.**"))
                                            {
                                                if ((MessageText.IndexOf(amazonMsg) > -1))
                                                {
                                                    EmailAddress = MessageText.Replace(amazonMsg, "");
                                                }
                                            }
                                            ActionTaken = "no action";
                                            if (EmailAddress == "")
                                            {
                                                //
                                                cp.CdnFiles.Append(bounceLogPathPage, "\n\r" + "email" + msgPtr + "-" + "email address was blank");
                                                //
                                                ActionTaken = "deleted with no action, email address could not be determined, email content saved [" + Filename + "]";
                                            }
                                            else if (FilterLineCnt == 0)
                                            {
                                                //
                                                cp.CdnFiles.Append(bounceLogPathPage, "\n\r" + "email" + msgPtr + "-" + "email filter file was not found (" + FilterFilename + ")");
                                                //
                                                ActionTaken = "[" + EmailAddress + "], deleted with no action, no Filter File [" + FilterFilename + "]";
                                            }
                                            else
                                            {
                                                // Copy = strDecodeMime(MessageText, MessageHeaders)
                                                for (LinePtr = 0; LinePtr <= FilterLineCnt - 1; LinePtr++)
                                                {
                                                    Filter = FilterText[LinePtr].Trim();
                                                    if (Filter != "")
                                                    {
                                                        if (MessageText.IndexOf(Filter) >= 0)
                                                        {
                                                            BounceType = FilterType[LinePtr];
                                                            switch (BounceType)
                                                            {
                                                            case 0: {
                                                                //
                                                                ActionTaken = "[" + EmailAddress + "], deleted with no action, Filter [" + Filter + "] is not a bounce";
                                                                break;
                                                            }

                                                            case 1: {
                                                                //
                                                                // soft bounce - may recover
                                                                //
                                                                ActionTaken = "[" + EmailAddress + "], deleted with no action, Filter [" + Filter + "] is soft error, may recover";
                                                                break;
                                                            }

                                                            case 2: {
                                                                //
                                                                // hard bounce - take action on the member email
                                                                //
                                                                //
                                                                //
                                                                //
                                                                //
                                                                EmailBounceProcessAction = 1;
                                                                //
                                                                //
                                                                //
                                                                switch (EmailBounceProcessAction)
                                                                {
                                                                case 1: {
                                                                    //
                                                                    // clear allowgroupemail
                                                                    //
                                                                    ActionTaken = "[" + EmailAddress + "], clear allowBulkEmail action, Filter [" + Filter + "] is hard error";
                                                                    CS.Open("people", "email=" + cp.Db.EncodeSQLText(EmailAddress), "", true, "ID,Name,OrganizationID,allowbulkemail");
                                                                    if (!(CS.OK()))
                                                                    {
                                                                        ActionTaken += ", NO RECORD FOUND";
                                                                    }
                                                                    else
                                                                    {
                                                                        ActionTaken += ", clearing allowGroupEmail for records [";
                                                                        while (CS.OK())
                                                                        {
                                                                            ActionTaken += "," + CS.GetInteger("id").ToString();
                                                                            CS.SetField("allowbulkemail", 0.ToString());
                                                                            CS.GoNext();
                                                                        }
                                                                        ActionTaken += "]";
                                                                    }
                                                                    CS.Close();
                                                                    break;
                                                                }

                                                                case 2: {
                                                                    //
                                                                    // clear email
                                                                    //
                                                                    ActionTaken = "[" + EmailAddress + "], clear email address action, Filter [" + Filter + "] is hard error";
                                                                    CS.Open("people", "email=" + cp.Db.EncodeSQLText(EmailAddress), "", true, "ID,Name,OrganizationID,email");
                                                                    if (!CS.OK())
                                                                    {
                                                                        ActionTaken += ", NO RECORD FOUND";
                                                                    }
                                                                    else
                                                                    {
                                                                        ActionTaken += ", clear email address for records [";
                                                                        while (CS.OK())
                                                                        {
                                                                            CS.SetField("email", "");
                                                                            CS.GoNext();
                                                                        }
                                                                        ActionTaken += "]";
                                                                    }
                                                                    CS.Close();
                                                                    break;
                                                                }

                                                                case 3: {
                                                                    //
                                                                    // Delete Member
                                                                    //
                                                                    ActionTaken = "[" + EmailAddress + "], delete member, Filter [" + Filter + "] is hard error";
                                                                    CS.Open("people", "email=" + cp.Db.EncodeSQLText(EmailAddress), "", true, "ID,Name,OrganizationID");
                                                                    if (!CS.OK())
                                                                    {
                                                                        ActionTaken += ", NO RECORD FOUND";
                                                                    }
                                                                    else
                                                                    {
                                                                        ActionTaken += ", delete people records [";
                                                                        while (CS.OK())
                                                                        {
                                                                            CS.Delete();
                                                                            CS.GoNext();
                                                                        }
                                                                        ActionTaken += "]";
                                                                    }
                                                                    CS.Close();
                                                                    break;
                                                                }

                                                                default: {
                                                                    //
                                                                    // Unknown Process Action
                                                                    //
                                                                    ActionTaken = "[" + EmailAddress + "], deleted with no action, Filter [" + Filter + "] is hard error, but Process Action is unknown [" + EmailBounceProcessAction + "]";
                                                                    break;
                                                                }
                                                                }

                                                                break;
                                                            }
                                                            }
                                                            //
                                                            cp.CdnFiles.Append(bounceLogPathPage, "\n\r" + "email" + msgPtr + "-" + ActionTaken);
                                                            //
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    //
                                    // save bounced email
                                    //
                                    cp.CdnFiles.Save(@"BounceLog\" + logDatePart + @"\email-" + msgPtr + ".txt", EmailAddress + "\n\r" + headerList + "\n\r" + MessageText);
                                    //
                                    // delete the message
                                    //
                                    pop.DeleteMessage(msgPtr);
                                }
                            } catch (Exception ex) {
                                cp.Site.ErrorReport(ex, "Bounce Processing exception");
                            } finally {
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                cp.Site.ErrorReport(ex);
            }
        }
        private void ler()
        {
            try
            {
                using (var client = new OpenPop.Pop3.Pop3Client())
                {
                    int quantos = 0, index = 0;
                    int porc, cnt = 0;
                    client.Connect(server, Convert.ToInt32(porta), Ssl);
                    client.Authenticate(user, senha);
                    int messageCount = client.GetMessageCount();
                    _emails.Clear();

                    if (Quantos != 0)
                    {
                        quantos = Quantos;
                        index   = messageCount - quantos;
                    }

                    if (quantos == 0)
                    {
                        quantos = messageCount;
                    }

                    porc = (0 * 100) / quantos;
                    #region Leitura
                    while (index != messageCount)
                    {
                        var popEmail = client.GetMessage(messageCount);
                        var popText  = popEmail.FindFirstPlainTextVersion();
                        var popHtml  = popEmail.FindFirstHtmlVersion();

                        string mailText = "";
                        string mailHtml = "";

                        if (popText != null)
                        {
                            mailText = popText.GetBodyAsText();
                        }
                        if (popHtml != null)
                        {
                            mailHtml = popHtml.GetBodyAsText();
                        }

                        _emails.Add(new E_mail()
                        {
                            Id            = popEmail.Headers.MessageId,
                            Assunto       = popEmail.Headers.Subject,
                            De            = popEmail.Headers.From.Address,
                            Para          = string.Join("; ", popEmail.Headers.To.Select(to => to.Address)),
                            Data          = popEmail.Headers.DateSent,
                            ConteudoTexto = mailText,
                            ConteudoHtml  = !string.IsNullOrWhiteSpace(mailHtml) ? mailHtml : mailText
                        });
                        messageCount--;
                        cnt++;
                        porc           = (cnt * 100) / quantos;
                        PrinAccess.qtd = porc;
                        PrinAccess.ControlaBar();
                        if (cnt % 20 == 0)
                        {
                            PrinAccess.AttBinding();
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Erro: " + ex.Message);
            }

            finally
            {
                PrinAccess.AttBinding();
                PrinAccess.AttBtn();
            }
        }
Exemple #23
0
        private void Verificar_Email()
        {
            progresso.Value = 0;
            Cursor          = Cursors.WaitCursor;

            try
            {
                using (var client = new OpenPop.Pop3.Pop3Client())
                {
                    int    quantos = 0, index = 0;
                    double porc;
                    client.Connect(pop.Text, Convert.ToInt32(portaPP.Text), _useSsl);
                    client.Authenticate(paraTextBox.Text, senha.Text);
                    int messageCount = client.GetMessageCount();
                    _emails.Clear();
                    quantos = Convert.ToInt32(Qtd.Text);
                    index   = messageCount - quantos;
                    porc    = (Convert.ToDouble(quantos)) / quantos;
                    while (index != messageCount)
                    {
                        var popEmail = client.GetMessage(messageCount);
                        var popText  = popEmail.FindFirstPlainTextVersion();
                        var popHtml  = popEmail.FindFirstHtmlVersion();

                        string mailText = string.Empty;
                        string mailHtml = string.Empty;
                        if (popText != null)
                        {
                            mailText = popText.GetBodyAsText();
                        }
                        if (popHtml != null)
                        {
                            mailHtml = popHtml.GetBodyAsText();
                        }

                        _emails.Add(new E_mail()
                        {
                            Id            = popEmail.Headers.MessageId,
                            Assunto       = popEmail.Headers.Subject,
                            De            = popEmail.Headers.From.Address,
                            Para          = string.Join("; ", popEmail.Headers.To.Select(to => to.Address)),
                            Data          = popEmail.Headers.DateSent,
                            ConteudoTexto = mailText,
                            ConteudoHtml  = !string.IsNullOrWhiteSpace(mailHtml) ? mailHtml : mailText
                        });
                        lastEmail     = popEmail.Headers.From.Address;
                        lastAssunto   = popEmail.Headers.Subject;
                        lastEmailHour = popEmail.Headers.DateSent.ToString();
                        messageCount--;
                        progresso.Maximum = quantos;
                        progresso.Value  += Convert.ToInt32(porc);
                    }
                    //for (int i = messageCount; i > 2400; i--)
                    AtualizarDataBindings();
                }
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
Exemple #24
0
        private void LeerCorreo(object IdOperador)
        {
            Int32 idProcesoPersonal = idProceso;

            try
            {
                Int32 idOperador = (int)IdOperador;
                using (CobranzasDataContext db = new CobranzasDataContext())
                {
                    List <Entidades.CorreosFiltros> Filtros = db.CorreosFiltros./*Where(x => x.idOperador == idOperador).*/ ToList();

                    String Ruta             = Parametro("RutaCorreos", db);
                    Entidades.Operadores op = db.Operadores.Single(x => x.idOperador == idOperador);
                    Log("Leyendo: " + op.Nombre, idProcesoPersonal, idOperador);
                    String Servidor = (op.POP3Host ?? Parametro("POP3Host", db));
                    if (Servidor == null)
                    {
                        Log("Saltando, por no tener definido un servidor", idProcesoPersonal, idOperador);
                        return;
                    }
                    Int32   Puerto   = (op.POP3Port ?? Convert.ToInt32(Parametro("POP3Port", db)));
                    Boolean SSL      = op.POP3SSL ?? (Parametro("POP3SSL", db) == "1");
                    String  Usuario  = op.POP3Login;
                    String  Password = op.POP3Password;
                    if (op.POP3Password == null)
                    {
                        Log("Saltando, por no tener contraseña", idProcesoPersonal, idOperador);
                        return;
                    }
                    DateTime?UltimaFecha = op.UltimaFechaCorreoEntrante;
                    using (OpenPop.Pop3.Pop3Client POP3 = new OpenPop.Pop3.Pop3Client())//Iniciando el servidor POP3;
                    {
                        POP3.Connect(Servidor, Puerto, SSL);
                        POP3.Authenticate(Usuario, Password);
                        int Count = POP3.GetMessageCount();

                        Int32 Inicio = Count;
                        while (true)
                        {
                            OpenPop.Mime.Header.MessageHeader mh = POP3.GetMessageHeaders(Inicio);
                            if (db.Correos.Any(x => x.idOperador == idOperador && x.IdPop3 == mh.MessageId))
                            {
                                break;
                            }
                            Inicio--;
                            if (Inicio == 0)
                            {
                                break;
                            }
                        }
                        Inicio++;
                        //Inicio = UltimaFecha == null ? 1 : BuscarIdPorFecha(1, Count, POP3, UltimaFecha.Value);
                        //Inicio -= 4;
                        //if (Inicio < 1) Inicio = 1;


                        Log(op.Login + " Inicio:" + Inicio + ", Total:" + Count, idProcesoPersonal, idOperador);
                        Int32 ErroresSeguidos = 0;
                        if (Inicio > Count)
                        {
                            Log("No hay correos nuevos para: " + op.Login, idProcesoPersonal, idOperador);
                        }
                        for (int i = Inicio; i <= Count; i++)//últimos 5 correos para verificar.
                        {
                            if (ErroresSeguidos == 5)
                            {
                                Log("Abortando Lectura de " + op.Login + " Por 5 erorres consecutivos", idProcesoPersonal, idOperador);
                                break;
                            }
                            try
                            {
                                OpenPop.Mime.Header.MessageHeader mh = POP3.GetMessageHeaders(i);

                                /*if (UltimaFecha != null && mh.DateSent.ToLocalTime() <= UltimaFecha)
                                 * {
                                 *  Log("Saltando Mensaje", idProcesoPersonal, i);
                                 *  continue;
                                 * }*/
                                if (db.Correos.Any(x => x.idOperador == idOperador && x.IdPop3 == mh.MessageId))
                                {
                                    Log("Saltando Mensaje de " + op.Login + " " + i.ToString() + "/" + Count.ToString(), idProcesoPersonal, idOperador);
                                    continue;
                                }
                                Log("Leyendo Mensaje de " + op.Login + " " + i.ToString() + "/" + Count.ToString(), idProcesoPersonal, idOperador);

                                OpenPop.Mime.Message m = POP3.GetMessage(i);
                                UltimaFecha = mh.DateSent.ToLocalTime();
                                String idLimpio      = Limpiar(mh.MessageId);
                                String Directorio    = UltimaFecha.Value.ToString("yyyyMMdd") + "\\";
                                String Prefijo       = UltimaFecha.Value.ToString("mmss") + "_";
                                String RutaCompleta  = Ruta + Directorio + Prefijo + idLimpio + ".eml";
                                Int32  idCorreoNuevo = 0;
                                if (!File.Exists(RutaCompleta))
                                {
                                    Directory.CreateDirectory(Ruta + Directorio);
                                    m.Save(new FileInfo(RutaCompleta));
                                }
                                Entidades.Correos Correo = new Entidades.Correos();
                                Correo.IdPop3                   = mh.MessageId;
                                Correo.idOperador               = idOperador;
                                Correo.Asunto                   = Limitar(mh.Subject, 2000);
                                Correo.Remitente                = Limitar(mh.From.Raw, 500);
                                Correo.FechaCreacion            = mh.DateSent.ToLocalTime();
                                Correo.Destinatarios            = Limitar(String.Join(",", mh.To.Select(x => x.Raw)), 5000);
                                Correo.DestinatariosCopia       = Limitar(String.Join(",", mh.Cc.Select(x => x.Raw)), 5000);
                                Correo.DestinatariosCopiaOculta = Limitar(String.Join(",", mh.Bcc.Select(x => x.Raw)), 5000);
                                Correo.RutaEml                  = Directorio + Prefijo + idLimpio;
                                var Personas = Filtros.Where(x => mh.From.Address.ToLower() == x.De.ToLower()).Select(x => x.idPersona);
                                foreach (int idPersona in Personas)
                                {
                                    Correo.Correos_Personas.Add(new Entidades.Correos_Personas()
                                    {
                                        idPersona = idPersona
                                    });
                                }
                                db.Correos.InsertOnSubmit(Correo);
                                Correo.Fecha = DateTime.Now;
                                db.SubmitChanges();
                                idCorreoNuevo = Correo.idCorreo;

                                db.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, op);
                                op.UltimaFechaCorreoEntrante = UltimaFecha;
                                db.SubmitChanges();
                                Log("Leido Mensaje de " + op.Login + " " + i.ToString() + "/" + Count.ToString() + "#" + idCorreoNuevo, idProcesoPersonal, idOperador);
                                ErroresSeguidos = 0;
                            }
                            catch (OpenPop.Pop3.Exceptions.InvalidLoginException Ex)
                            {
                                ErroresSeguidos++;
                                Log("Error en Mensaje: IL Op: " + op.Login + "(" + i.ToString() + "/" + Count.ToString() + "), Mensaje:" + Ex.Message, idProcesoPersonal, idOperador);
                            }
                            catch (OpenPop.Pop3.Exceptions.InvalidUseException Ex)
                            {
                                ErroresSeguidos++;
                                Log("Error en Mensaje: IU Op: " + op.Login + "(" + i.ToString() + "/" + Count.ToString() + "), Mensaje:" + Ex.Message, idProcesoPersonal, idOperador);
                            }
                            catch (OpenPop.Pop3.Exceptions.LoginDelayException Ex)
                            {
                                ErroresSeguidos++;
                                Log("Error en Mensaje: LD Op: " + op.Login + "(" + i.ToString() + "/" + Count.ToString() + "), Mensaje:" + Ex.Message, idProcesoPersonal, idOperador);
                            }
                            catch (OpenPop.Pop3.Exceptions.PopServerException Ex)
                            {
                                ErroresSeguidos++;
                                Log("Error en Mensaje: PS Op: " + op.Login + "(" + i.ToString() + "/" + Count.ToString() + "), Mensaje:" + Ex.Message, idProcesoPersonal, idOperador);
                            }
                            catch (OpenPop.Pop3.Exceptions.PopServerLockedException Ex)
                            {
                                ErroresSeguidos++;
                                Log("Error en Mensaje: PSL Op: " + op.Login + "(" + i.ToString() + "/" + Count.ToString() + "), Mensaje:" + Ex.Message, idProcesoPersonal, idOperador);
                            }
                            catch (OpenPop.Pop3.Exceptions.PopServerNotAvailableException Ex)
                            {
                                ErroresSeguidos++;
                                Log("Error en Mensaje: PSNA Op: " + op.Login + "(" + i.ToString() + "/" + Count.ToString() + "), Mensaje:" + Ex.Message, idProcesoPersonal, idOperador);
                            }
                            catch (OpenPop.Pop3.Exceptions.PopServerNotFoundException Ex)
                            {
                                ErroresSeguidos++;
                                Log("Error en Mensaje: SNF Op: " + op.Login + "(" + i.ToString() + "/" + Count.ToString() + "), Mensaje:" + Ex.Message, idProcesoPersonal, idOperador);
                            }
                            catch (OpenPop.Pop3.Exceptions.PopClientException Ex)
                            {
                                ErroresSeguidos++;
                                Log("Error en Mensaje: PC Op: " + op.Login + "(" + i.ToString() + "/" + Count.ToString() + "), Mensaje:" + Ex.Message, idProcesoPersonal, idOperador);
                            }
                            catch (Exception Ex)
                            {
                                ErroresSeguidos++;
                                Log("Error en Mensaje: Op: " + op.Login + "(" + i.ToString() + "/" + Count.ToString() + "), Mensaje:" + Ex.Message, idProcesoPersonal, idOperador);
                            }
                        }
                        POP3.Disconnect();
                    }
                    Log("Fin Lectura: " + op.Nombre, idProcesoPersonal, idOperador);
                }
            }
            catch (Exception Ex)
            {
                if (Ex.Message == "Server did not accept user credentials")
                {
                    try
                    {
                        using (CobranzasDataContext db = new CobranzasDataContext())
                        {
                            db.Operadores.Single(x => x.idOperador == (Int32)IdOperador).POP3Password = null;
                            db.SubmitChanges();
                            db.Avisos.InsertOnSubmit(new Entidades.Avisos
                            {
                                Aviso          = "El servidor ha rechazado su contraseña, por favor actualice su contraseña de correo nuevamente",
                                FechaAviso     = DateTime.Now.AddMinutes(2),
                                FechaCrea      = DateTime.Now,
                                FechaOriginal  = DateTime.Now.AddMinutes(2),
                                idOperador     = (Int32)IdOperador,
                                idOperadorCrea = 1,
                                VecesMostrada  = 0
                            });
                            db.SubmitChanges();
                        }
                    }
                    catch { }
                }
                Log("Error General: Op:" + IdOperador + ", Mensaje:" + Ex.Message, idProcesoPersonal, (int)IdOperador);
            }
        }
Exemple #25
0
		///<summary>Fetches up to fetchCount number of messages from a POP3 server.  Set fetchCount=0 for all messages.  Typically, fetchCount is 0 or 1.
		///Example host name, pop3.live.com. Port is Normally 110 for plain POP3, 995 for SSL POP3.</summary>
		private static List<EmailMessage> ReceiveFromInboxThreadSafe(int receiveCount,EmailAddress emailAddressInbox) {
			//No need to check RemotingRole; no call to db.
			List<EmailMessage> retVal=new List<EmailMessage>();
			//This code is modified from the example at: http://hpop.sourceforge.net/exampleFetchAllMessages.php
			using(OpenPop.Pop3.Pop3Client client=new OpenPop.Pop3.Pop3Client()) {//The client disconnects from the server when being disposed.
				client.Connect(emailAddressInbox.Pop3ServerIncoming,emailAddressInbox.ServerPortIncoming,emailAddressInbox.UseSSL,180000,180000,null);//3 minute timeout, just as for sending emails.
				client.Authenticate(emailAddressInbox.EmailUsername.Trim(),emailAddressInbox.EmailPassword,OpenPop.Pop3.AuthenticationMethod.UsernameAndPassword);
				List <string> listMsgUids=client.GetMessageUids();//Get all unique identifiers for each email in the inbox.
				List<EmailMessageUid> listDownloadedMsgUids=EmailMessageUids.GetForRecipientAddress(emailAddressInbox.EmailUsername.Trim());
				List<string> listDownloadedMsgUidStrs=new List<string>();
				for(int i=0;i<listDownloadedMsgUids.Count;i++) {
					listDownloadedMsgUidStrs.Add(listDownloadedMsgUids[i].MsgId);
				}
				int msgDownloadedCount=0;
				for(int i=0;i<listMsgUids.Count;i++) {
					int msgIndex=i+1;//The message indicies are 1-based.
					string strMsgUid=listMsgUids[i];//Example: 1420562540.886638.p3plgemini22-06.prod.phx.2602059520
					OpenPop.Mime.Header.MessageHeader messageHeader=null;
					if(strMsgUid.Length==0) {
						//Message Uids are commonly used, but are optional according to the RFC822 email standard.
						//Uids are assgined by the sending client application, so they could be anything, but are supposed to be unique.
						//Additionally, most email servers are probably smart enough to create a Uid for any message where the Uid is missing.
						//In the worst case scenario, we create a Uid for the message based off of the message header information, which takes a little extra time, 
						//but is better than downloading old messages again, especially if some of those messages contain large attachments.
						messageHeader=client.GetMessageHeaders(msgIndex);//Takes 1-2 seconds to get this information from the server.  The message, minus body and minus attachments.
						strMsgUid=messageHeader.DateSent.ToString("yyyyMMddHHmmss")+emailAddressInbox.EmailUsername.Trim()+messageHeader.From.Address+messageHeader.Subject;
					}
					if(strMsgUid.Length>4000) {//The EmailMessageUid.MsgId field is only 4000 characters in size.
						strMsgUid=strMsgUid.Substring(0,4000);
					}
					if(listDownloadedMsgUidStrs.Contains(strMsgUid)) {
						continue;//Skip emails which have already been downloaded.
					}
					//messageHeader will only be defined if we created our own unique ID manually above.  MessageId is optional, just as the message UIDs are.
					if(messageHeader!=null && messageHeader.MessageId!="") {
						//The MessageId is usually generated by the email server.
						//The message does not have a UID, and the ID that we made up has not been downloaded before.  As a last resort we check the MessageId in 
						//the message header.  MessageId is different than the UID.  We should have used the MessageId as the second option in the past, but now 
						//we are stuck using it as a third option, because using MessageId as a second option would cause old emails to download again.
						strMsgUid=messageHeader.MessageId;//Example: [email protected]
						if(strMsgUid.Length>4000) {//The EmailMessageUid.MsgId field is only 4000 characters in size.
							strMsgUid=strMsgUid.Substring(0,4000);
						}
						if(listDownloadedMsgUidStrs.Contains(strMsgUid)) {
							continue;//Skip emails which have already been downloaded.
						}
					}
					//At this point, we know that the email is one which we have not downloaded yet.
					try {
						OpenPop.Mime.Message openPopMsg=client.GetMessage(msgIndex);//This is where the entire raw email is downloaded.
						bool isEmailFromInbox=true;
						if(openPopMsg.Headers.From.ToString().ToLower().Contains(emailAddressInbox.EmailUsername.Trim().ToLower())) {//The email Recipient and email From addresses are the same.
							//The email Recipient and email To or CC or BCC addresses are the same.  We have verified that a user can send an email to themself using only CC or BCC.
							if(String.Join(",",openPopMsg.Headers.To).ToLower().Contains(emailAddressInbox.EmailUsername.Trim().ToLower()) ||
								String.Join(",",openPopMsg.Headers.Cc).ToLower().Contains(emailAddressInbox.EmailUsername.Trim().ToLower()) ||
								String.Join(",",openPopMsg.Headers.Bcc).ToLower().Contains(emailAddressInbox.EmailUsername.Trim().ToLower()))
							{
								//Download this message because it was clearly sent from the user to theirself.
							}
							else {
								//Gmail will report sent email as if it is part of the Inbox. These emails will have the From address as the Recipient address, but the To address will be a different address.
								isEmailFromInbox=false;
							}
						}
						if(isEmailFromInbox) {
							string strRawEmail=openPopMsg.MessagePart.BodyEncoding.GetString(openPopMsg.RawMessage);
							EmailMessage emailMessage=ProcessRawEmailMessageIn(strRawEmail,0,emailAddressInbox,true);//Inserts to db.
							retVal.Add(emailMessage);
							msgDownloadedCount++;
						}
						EmailMessageUid emailMessageUid=new EmailMessageUid();
						emailMessageUid.RecipientAddress=emailAddressInbox.EmailUsername.Trim();
						emailMessageUid.MsgId=strMsgUid;
						EmailMessageUids.Insert(emailMessageUid);//Remember Uid was downloaded, to avoid email duplication the next time the inbox is refreshed.
					}
					catch(ThreadAbortException) {
						//This can happen if the application is exiting. We need to leave right away so the program does not lock up.
						//Otherwise, this loop could continue for a while if there are a lot of messages to download.
						throw;
					}
					catch {
						//If one particular email fails to download, then skip it for now and move on to the next email.
					}
					if(receiveCount>0 && msgDownloadedCount>=receiveCount) {
						break;
					}
				}
			}
			//Since this function is fired automatically based on the inbox check interval, we also try to send the oldest unsent Ack.
			//The goal is to keep trying to send the Acks at a reasonable interval until they are successfully delivered.
			SendOldestUnsentAck(emailAddressInbox);
			return retVal;
		}
Exemple #26
0
        static void Pop3Test()
        {
            OpenPop.Pop3.Pop3Client mclient = new OpenPop.Pop3.Pop3Client();
            mclient.Connect("mail.cute.edu.tw", 110, false);
            mclient.Authenticate("weather", "0988163835");
            int cnt = mclient.GetMessageCount();
            Console.WriteLine("Message cnt:" + cnt);
            string bodytext;
            for (int i = 1; i <= cnt; i++)
            {
                bodytext = "";
                Message msg = mclient.GetMessage(i);

                Console.WriteLine("from:" + msg.Headers.From.MailAddress.Address);
                Console.WriteLine("subject:" + msg.Headers.Subject);
                if (!msg.MessagePart.IsText)
                {
                    MessagePart msgpart = msg.FindFirstPlainTextVersion();
                    if (msgpart != null && msgpart.IsText)
                    {
                        Console.WriteLine("body:" + msgpart.GetBodyAsText());

                        bodytext = msgpart.GetBodyAsText();
                    }

                }
                else
                {
                    Console.WriteLine("body:" + msg.MessagePart.GetBodyAsText());
                    bodytext = msg.MessagePart.GetBodyAsText();
                }

                if (msg.Headers.Subject.Contains("大雨") || msg.Headers.Subject.Contains("強風") || msg.Headers.Subject.Contains("地震"))
                {
                    System.Net.Mail.SmtpClient c = new SmtpClient("mail.cute.edu.tw", 25);
                    c.DeliveryMethod = SmtpDeliveryMethod.Network;
                    c.Credentials = new System.Net.NetworkCredential("weather", "0988163835");
                    MailMessage m_mesg = new MailMessage(new MailAddress("*****@*****.**"), new MailAddress("*****@*****.**"));
                    m_mesg.Body = bodytext;
                    m_mesg.Subject = msg.Headers.Subject.Replace("\n", "");

                    m_mesg.IsBodyHtml = true;
                    if (bodytext != "")
                        c.Send(m_mesg);
                }

            }
            for (int i = 1; i <= cnt; i++)
                mclient.DeleteMessage(i);

            mclient.Dispose();
        }
		///<summary>Fetches up to fetchCount number of messages from a POP3 server.  Set fetchCount=0 for all messages.  Typically, fetchCount is 0 or 1.
		///Example host name, pop3.live.com. Port is Normally 110 for plain POP3, 995 for SSL POP3.</summary>
		private static List<EmailMessage> ReceiveFromInboxThreadSafe(int receiveCount,EmailAddress emailAddressInbox) {
			//No need to check RemotingRole; no call to db.
			List<EmailMessage> retVal=new List<EmailMessage>();
			//This code is modified from the example at: http://hpop.sourceforge.net/exampleFetchAllMessages.php
			using(OpenPop.Pop3.Pop3Client client=new OpenPop.Pop3.Pop3Client()) {//The client disconnects from the server when being disposed.
				client.Connect(emailAddressInbox.Pop3ServerIncoming,emailAddressInbox.ServerPortIncoming,emailAddressInbox.UseSSL,180000,180000,null);//3 minute timeout, just as for sending emails.
				client.Authenticate(emailAddressInbox.EmailUsername.Trim(),emailAddressInbox.EmailPassword,OpenPop.Pop3.AuthenticationMethod.UsernameAndPassword);
				List <string> listMsgUids=client.GetMessageUids();//Get all unique identifiers for each email in the inbox.
				List<EmailMessageUid> listDownloadedMsgUids=EmailMessageUids.GetForRecipientAddress(emailAddressInbox.EmailUsername.Trim());
				int msgDownloadedCount=0;
				for(int i=0;i<listMsgUids.Count;i++) {
					int msgIndex=i+1;//The message indicies are 1-based.
					string strMsgUid=listMsgUids[i];
					if(strMsgUid.Length==0) {
						//Message Uids are commonly used, but are optional according to the RFC822 email standard.
						//Uids are assgined by the sending client application, so they could be anything, but are supposed to be unique.
						//Additionally, most email servers are probably smart enough to create a Uid for any message where the Uid is missing.
						//In the worst case scenario, we create a Uid for the message based off of the message header information, which takes a little extra time, 
						//but is better than downloading old messages again, especially if some of those messages contain large attachments.
						OpenPop.Mime.Header.MessageHeader messageHeader=client.GetMessageHeaders(msgIndex);//Takes 1-2 seconds to get this information from the server.  The message, minus body and minus attachments.
						strMsgUid=messageHeader.DateSent.ToString("yyyyMMddHHmmss")+emailAddressInbox.EmailUsername.Trim()+messageHeader.From.Address+messageHeader.Subject;
					}
					else if(strMsgUid.Length>4000) {//The EmailMessageUid.MsgId field is only 4000 characters in size.
						strMsgUid=strMsgUid.Substring(0,4000);
					}
					//Skip any email messages matching Uids which have been previously downloaded.
					bool isDownloaded=false;
					for(int j=0;j<listDownloadedMsgUids.Count;j++) {
						if(listDownloadedMsgUids[j].MsgId==strMsgUid) {
							isDownloaded=true;
							break;
						}
					}
					if(isDownloaded) {
						continue;
					}
					//At this point, we know that the email is one which we have not downloaded yet.
					try {
						OpenPop.Mime.Message openPopMsg=client.GetMessage(msgIndex);//This is where the entire raw email is downloaded.
						string strRawEmail=openPopMsg.MessagePart.BodyEncoding.GetString(openPopMsg.RawMessage);
						EmailMessage emailMessage=ProcessRawEmailMessage(strRawEmail,0,emailAddressInbox);//Inserts to db.
						EmailMessageUid emailMessageUid=new EmailMessageUid();
						emailMessageUid.RecipientAddress=emailMessage.RecipientAddress.Trim();
						emailMessageUid.MsgId=strMsgUid;
						EmailMessageUids.Insert(emailMessageUid);//Remember Uid was downloaded, to avoid email duplication the next time the inbox is refreshed.
						retVal.Add(emailMessage);
						msgDownloadedCount++;
					}
					catch(ThreadAbortException) {
						//This can happen if the application is exiting. We need to leave right away so the program does not lock up.
						//Otherwise, this loop could continue for a while if there are a lot of messages to download.
						throw;
					}
					catch {
						//If one particular email fails to download, then skip it for now and move on to the next email.
					}
					if(receiveCount>0 && msgDownloadedCount>=receiveCount) {
						break;
					}
				}
			}
			//Since this function is fired automatically based on the inbox check interval, we also try to send the oldest unsent Ack.
			//The goal is to keep trying to send the Acks at a reasonable interval until they are successfully delivered.
			SendOldestUnsentAck(emailAddressInbox);
			return retVal;
		}
Exemple #28
0
        public OpenPop.Mime.Message[] recibir()
        {
            OpenPop.Pop3.Pop3Client client = new OpenPop.Pop3.Pop3Client();

            /* Mail de Pruebas*/
            //client.Connect("mail.xeta.com.ar", 110, false);
            //client.Authenticate("*****@*****.**", "test712as");

            /* Mail de Pruebas en Gmail */
            //client.Connect("pop.googlemail.com", 110, false);
            //client.Authenticate("*****@*****.**", "sitmemge");

            client.Connect("10.90.19.5", 110, false);
            client.Authenticate("*****@*****.**", "redise");
            //            client.Authenticate("*****@*****.**", "redise");
            //            client.Authenticate("*****@*****.**", "redise");
            //            client.Authenticate("*****@*****.**", "redise");
            //            client.Authenticate("*****@*****.**", "redise");
            //            client.Connect("10.90.19.8", 110, false);
            //            client.Authenticate("*****@*****.**", "redise");

            int messageCount = client.GetMessageCount();
            OpenPop.Mime.Message[] allMessages = new OpenPop.Mime.Message[messageCount];
            /*
            if (messageCount == 0)
            {
                MessageBox.Show("No existen mensajes para descargar");
            }
            else
            {

                MessageBox.Show("mensajes recibidos", messageCount.ToString());
            };
            */
            Form formulario = new Form();

            if (client.Connected && messageCount > 0)
            {
                int i = 0;
                for (int j = messageCount; j > 0; j--)
                {
                    OpenPop.Mime.Message TEST = client.GetMessage(j);
                    allMessages[i] = TEST;
                    i++;
                }
            }
            else {
                if (!(client.Connected))
                {
                    MessageBox.Show("No conectado");
                }
                else
                {
                    MessageBox.Show("No existen mensajes para descargar");
                }
            }
            return allMessages;
        }