Esempio n. 1
0
 private void DeleteMail(DateTime datetime)
 {
     using (var pop3 = new POP3_Client())
     {
         pop3.Connect(pop3host, 995, true);
         pop3.Timeout = 3000;
         pop3.Login(user, pwd);
         var date = datetime.ToString("yyyy-MM-dd");
         var del  = 0;
         foreach (POP3_ClientMessage m in pop3.Messages)
         {
             var header = Mail_Message.ParseFromByte(m.HeaderToByte());
             var ss     = header.Subject.Split('@');
             if (ss.Length != 2)
             {
                 m.MarkForDeletion();
                 continue;
             }
             if (ss[0] == this.shop && ss[1] == date)
             {
                 m.MarkForDeletion();
                 sb.Append("delete old mail: " + date + "\r\n");
                 del++;
                 continue;
             }
         }
         sb.Append(string.Format("共{0}邮件,删除旧邮件{1}\r\n", pop3.Messages.Count, del));
         pop3.Disconnect();
     }
 }
Esempio n. 2
0
        public List <Mail> ReceiveMail(Setting setting)
        {
            List <Mail> list = new List <Mail>();

            using (POP3_Client pop3_Client = new POP3_Client())
            {
                //设置SMPT服务地址和端口并连接
                pop3_Client.Connect(setting.SmtpHostName, setting.SmtpPort);
                //设置Authentication
                pop3_Client.Auth(new LumiSoft.Net.AUTH.AUTH_SASL_Client_Login(setting.User.UserName, setting.User.Password));
                if (pop3_Client.Messages != null && pop3_Client.Messages.Count > 0)
                {
                    foreach (POP3_ClientMessage message in pop3_Client.Messages)
                    {
                        //将收到的邮件逐一转化Mail实体类型
                        Mail_Message mail_Message = Mail_Message.ParseFromByte(message.MessageToByte());
                        list.Add(new Mail()
                        {
                            From            = mail_Message.From.ToString(),
                            To              = mail_Message.To.ToArray().Select(address => address.ToString()).ToList(),
                            CreatedDateTime = mail_Message.Date,
                            Subject         = mail_Message.Subject,
                            Body            = mail_Message.BodyHtmlText,
                            Attachments     = mail_Message.Attachments.Select(attach => new Attachment(attach.ContentDisposition.Param_FileName)).ToList()
                        });
                    }
                }
            }
            return(list);
        }
Esempio n. 3
0
        private List <Mime> GetEmails(string pop3Server, int pop3Port, bool pop3UseSsl, string username, string password, out List <string> mailMsgIds)
        {
            mailMsgIds = new List <string>();
            List <Mime>   result      = new List <Mime>();
            List <string> gotEmailIds = new List <string>();

            using (POP3_Client pop3 = new POP3_Client())
            {
                pop3.Connect(pop3Server, pop3Port, pop3UseSsl);
                pop3.Authenticate(username, password, false);
                POP3_ClientMessageCollection infos = pop3.Messages;
                int maxRetriveMail = this.GetMaxRetrieveMail();
                int messageCount   = infos != null ? infos.Count : 0;
                int totalEmails    = messageCount > maxRetriveMail ? maxRetriveMail : messageCount;

                //foreach (POP3_ClientMessage info in infos)
                for (int i = totalEmails; i > 0; i--)
                {
                    var info = infos[i - 1];
                    if (gotEmailIds.Contains(info.UID))
                    {
                        continue;
                    }
                    byte[] bytes = info.MessageToByte();
                    gotEmailIds.Add(info.UID);
                    Mime mime = Mime.Parse(bytes);
                    result.Add(mime);
                }

                mailMsgIds.AddRange(gotEmailIds);
            }

            return(result);
        }
 /// <summary>
 /// 删除
 /// </summary>
 /// <param name="account">配置</param>
 /// <param name="UID">UID</param>
 public static void Delete(MailAccount account, string UID)
 {
     try
     {
         using (POP3_Client pop3Client = new POP3_Client())
         {
             pop3Client.Connect(account.POP3Host, account.POP3Port, false);
             pop3Client.Login(account.Account, account.Password);
             if (pop3Client.Messages.Count > 0)
             {
                 foreach (POP3_ClientMessage messages in pop3Client.Messages)
                 {
                     if (messages.UID == UID)
                     {
                         messages.MarkForDeletion();
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Esempio n. 5
0
        static public List <Mime> getEmails()
        {
            List <Mime> result = new List <Mime>();

            using (POP3_Client pop3 = new POP3_Client())
            {
                try
                {
                    pop3.Connect("pop3.163.com", 110, false);
                    pop3.Authenticate("*****@*****.**", "6728924", false);

                    //获取邮件信息列表
                    POP3_ClientMessageCollection infos = pop3.Messages;

                    foreach (POP3_ClientMessage info in infos)
                    {
                        byte[] bytes = info.MessageToByte();

                        //解析从Pop3服务器发送过来的邮件信息
                        Mime mime = Mime.Parse(bytes);

                        result.Add(mime);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
            return(result);
        }
Esempio n. 6
0
        public override Server creack(String ip, int port, String username, String password, int timeOut)
        {
            POP3_Client conn   = null;
            Server      server = new Server();

            try
            {
                conn = new POP3_Client();
                //与Pop3服务器建立连接
                conn.Timeout = timeOut;
                conn.Connect(ip, port, true);
                if (conn.IsConnected)
                {
                    conn.Login(username, password);

                    if (conn.IsAuthenticated)
                    {
                        server.isSuccess = conn.IsAuthenticated;
                        server.banner    = conn.GreetingText;
                    }
                }
            }
            catch (Exception e) {
                throw e;
            }
            finally
            {
                if (conn != null && conn.IsConnected)
                {
                    conn.Disconnect();
                }
            }
            return(server);
        }
Esempio n. 7
0
        private void m_pConnect_Click(object sender, EventArgs e)
        {
            if (m_pUserName.Text == "")
            {
                MessageBox.Show(this, "Please fill user name !", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            POP3_Client pop3 = new POP3_Client();

            try{
                pop3.Logger           = new Logger();
                pop3.Logger.WriteLog += m_pLogCallback;
                pop3.Connect(m_pServer.Text, (int)m_pPort.Value, (m_pSecurity.SelectedIndex == 2));
                if (m_pSecurity.SelectedIndex == 1)
                {
                    pop3.Stls(null);
                }
                pop3.Login(m_pUserName.Text, m_pPassword.Text);

                m_pPop3           = pop3;
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception x) {
                MessageBox.Show(this, "POP3 server returned: " + x.Message + " !", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                pop3.Dispose();
            }
        }
Esempio n. 8
0
        private void DeleteMail()
        {
            using (POP3_Client c = new POP3_Client())
            {
                c.Connect(serverName, pop3Port, false);
                c.Login(loginName, password);

                if (c.Messages.Count > 0)
                {
                    foreach (POP3_ClientMessage mail in c.Messages)
                    {
                        try
                        {
                            if (lviMail.SubItems[4].Text == mail.UID)
                            {
                                CustomDesktopAlert.H2(mail.UID);
                                mail.MarkForDeletion();
                                lviMail.Remove();
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            //LogTextHelper.Error(ex);
                        }
                    }
                }
            }
        }
        public override void Open()
        {
            if (!(channelState == ChannelState.Closed || channelState == ChannelState.Broken))
            {
                return;
            }

            channelState = ChannelState.Connecting;

            try
            {
                client = new POP3_Client();

                if ("/Settings/Channels/LoggerEnabled".AsKey(false))
                {
                    client.Logger           = new LumiSoft.Net.Log.Logger();
                    client.Logger.WriteLog += (sender, e) => Logger.Debug(e.LogEntry.Text, LogSource.Channel);
                }

                client.Connect(Hostname, Port, IsSecured);

                channelState = ChannelState.Connected;
            }
            catch (Exception ex)
            {
                channelState = ChannelState.Closed;

                throw new ChannelException("Unable to connect to server", ex);
            }
        }
Esempio n. 10
0
    private POP3_Client CreateLumisoftPop3Client()
    {
        POP3_Client client = new POP3_Client();

        client.Connect(MailHostOptions.Pop3163EnterpriseHost, MailHostOptions.Pop3163EnterprisePort, true);
        client.Login(MailHostOptions.Enterprise163Account, MailHostOptions.Enterprise163Password);
        return(client);
    }
 public void Disconnect()
 {
     if (_popClient != null)
     {
         _popClient.Dispose();
         _popClient = null;
     }
 }
Esempio n. 12
0
        private void UpdateData()
        {
            using (var pop3 = new POP3_Client())
            {
                pop3.Connect(this.pop3Host, 995, true);
                pop3.Login(this.user, this.password);
                int delete  = 0;
                int insert  = 0;
                int old     = 0;
                int sum     = pop3.Messages.Count;
                int newShop = 0;
                foreach (POP3_ClientMessage m in pop3.Messages)
                {
                    var header  = Mail_Message.ParseFromByte(m.HeaderToByte());
                    var subject = header.Subject;
                    var ss      = subject.Split('@'); // "wkl@2017-01-01"
                    if (ss.Length != 2)
                    {
                        m.MarkForDeletion();
                        delete++;
                        continue;
                    }
                    if (!shops.Keys.Contains <string>(ss[0]))
                    {
                        newShop++;
                        continue;
                    }
                    DateTime dt;
                    if (!DateTime.TryParse(ss[1], out dt))
                    {
                        m.MarkForDeletion();
                        delete++;
                        continue;
                    }
                    if (this.IsOldUid(m.UID)) //如果已读取过的邮件跳过
                    {
                        if (this.IsOldDate(dt))
                        {
                            m.MarkForDeletion(); //过期删除
                            delete++;
                        }
                        old++;
                        continue;
                    }
                    var mail = Mail_Message.ParseFromByte(m.MessageToByte());
                    var xml  = new XmlDocument();
                    xml.LoadXml(mail.BodyText);
                    this.InsertData(xml, dt);
                    this.InsertOldMail(m.UID, dt);
                    insert++;
                }

                MessageBox.Show(string.Format("共 {0} 条邮件,删除过期邮件 {1}, 略过已读邮件 {2}, 读取新邮件 {3}.\r\n未识别门店邮件 {4}, (如此值大于零, 请添加新门店!)",
                                              sum, delete, old, insert, newShop), "数据处理报告:", MessageBoxButtons.OK, MessageBoxIcon.Information);

                pop3.Disconnect();
            }
        }
Esempio n. 13
0
        static void Main()
        {
            var          user       = "******";
            var          pwd        = "xAcmQ3gg";
            const string pop3Server = "smtp.united-imaging.com";
            const int    pop3Port   = 995;

            // Connect Elasticsearch
            var node        = new Uri("http://10.6.14.157:9200");
            var elasticUser = "******";
            var elasticPwd  = "123qwe";
            var setting     = new ConnectionSettings(node);

            setting.BasicAuthentication(elasticUser, elasticPwd);
            var elasticSearchClient = new ElasticClient(setting);


            // Index Mapping
            var descriptor = new CreateIndexDescriptor("mail")
                             .Mappings(ms => ms.Map <Mail>(m => m.AutoMap()));

            elasticSearchClient.CreateIndex(descriptor);

            // Scheduled Mail Collecting
            while (true)
            {
                using (var pop3 = new POP3_Client())
                {
                    pop3.Connect(pop3Server, pop3Port, true);
                    pop3.Login(user, pwd);

                    var messages      = pop3.Messages;
                    var messagesCount = messages.Count;
                    Console.WriteLine("Message Count: {0}", messagesCount);

                    for (int i = 0; i < messagesCount; i++)
                    {
                        Console.WriteLine("Indexing Mail: {0} of {1}", i, messagesCount);
                        var message = messages[i];
                        var mail    = IndexMessage(message);
                        CheckMailToToSupervisor(mail);
                        var respose = elasticSearchClient.Index(mail, idx => idx.Index("mail"));
                        Console.WriteLine("Indexed a mail with respose : {0}", respose.Result.ToString());
                        Console.WriteLine();

                        message.MarkForDeletion();
                    }
                    pop3.Disconnect();
                }

                Thread.Sleep(5 * 60 * 1000);
            }

            //Console.WriteLine("Press any key to continue");
            //Console.ReadKey();
        }
Esempio n. 14
0
 public void StartFetching()
 {
     if (this.m_Fetching)
     {
         return;
     }
     this.m_Fetching = true;
     try
     {
         DataView users = this.m_pApi.GetUsers("ALL");
         using (DataView userRemoteServers = this.m_pApi.GetUserRemoteServers(""))
         {
             foreach (DataRowView dataRowView in userRemoteServers)
             {
                 try
                 {
                     if (ConvertEx.ToBoolean(dataRowView["Enabled"]))
                     {
                         users.RowFilter = "UserID='" + dataRowView["UserID"] + "'";
                         if (users.Count > 0)
                         {
                             string userName = users[0]["UserName"].ToString();
                             string host     = dataRowView.Row["RemoteServer"].ToString();
                             int    port     = Convert.ToInt32(dataRowView.Row["RemotePort"]);
                             string user     = dataRowView.Row["RemoteUserName"].ToString();
                             string password = dataRowView.Row["RemotePassword"].ToString();
                             bool   ssl      = ConvertEx.ToBoolean(dataRowView["UseSSL"]);
                             using (POP3_Client pOP3_Client = new POP3_Client())
                             {
                                 pOP3_Client.Logger           = new System.NetworkToolkit.Log.Logger();
                                 pOP3_Client.Logger.WriteLog += new EventHandler <WriteLogEventArgs>(this.Pop3_WriteLog);
                                 pOP3_Client.Connect(host, port, ssl);
                                 pOP3_Client.Login(user, password);
                                 foreach (POP3_ClientMessage pOP3_ClientMessage in pOP3_Client.Messages)
                                 {
                                     this.m_pServer.ProcessUserMsg("", "", userName, "Inbox", new MemoryStream(pOP3_ClientMessage.MessageToByte()), null);
                                     pOP3_ClientMessage.MarkForDeletion();
                                 }
                             }
                         }
                     }
                 }
                 catch
                 {
                 }
             }
         }
         this.m_LastFetch = DateTime.Now;
     }
     catch (Exception x)
     {
         Error.DumpError(this.m_pServer.Name, x);
     }
     this.m_Fetching = false;
 }
        public void Connect()
        {
            if (_popClient != null)
            {
                throw new ApplicationException("Already connected.");
            }

            _popClient = new POP3_Client();
            _popClient.Connect(PopMailProviderConfiguration.Settings.Server.Name, PopMailProviderConfiguration.Settings.Server.Port);
            _popClient.Authenticate(PopMailProviderConfiguration.Settings.Server.Username, PopMailProviderConfiguration.Settings.Server.Password, true);
        }
Esempio n. 16
0
        /// <summary>
        /// Cleans up any resources being used.
        /// </summary>
        /// <param name="disposing"></param>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            // Clean up POP3 client.
            if (m_pPop3 != null)
            {
                m_pPop3.Dispose();
                m_pPop3 = null;
            }
        }
Esempio n. 17
0
        public static List <Email> GetAllEmails(string server, int port, string user, string pwd, bool usessl, bool deleteafterread, ref List <string> errors)
        {
            var ret = new List <Email>();

            errors.Clear();
            var oClient = new POP3_Client();

            try
            {
                oClient.Connect(server, port, usessl);
                oClient.Authenticate(user, pwd, true);
            }
            catch (Exception exception)
            {
                errors.Add("Error connect/authenticate - " + exception.Message);
                return(null);
            }
            foreach (POP3_ClientMessage message in oClient.Messages)
            {
                var wrapper = new Email();
                wrapper.Uid = message.UID;
                try
                {
                    Mail_Message mime = Mail_Message.ParseFromByte(message.HeaderToByte());
                    wrapper.Subject = mime.Subject;
                    wrapper.From    = mime.From[0].Address;
                    wrapper.To      = mime.To[0].ToString();
                    mime            = Mail_Message.ParseFromByte(message.MessageToByte());

                    string sa = mime.BodyHtmlText;
                    if (sa == null)
                    {
                        wrapper.TextBody = mime.BodyText;
                    }
                    else
                    {
                        wrapper.HtmlBody = sa;
                    }
                }
                catch (Exception exception)
                {
                    errors.Add("Error reading " + wrapper.Uid + " - " + exception.Message);
                }
                if (deleteafterread)
                {
                    message.MarkForDeletion();
                }
                ret.Add(wrapper);
            }
            oClient.Disconnect();
            oClient.Dispose();

            return(ret);
        }
Esempio n. 18
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string    userId = context.Request.QueryString["UserID"];
            DataTable table;

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM [TU_EmailPOP] WHERE UserID='" + userId + "'", connection);
                table = new DataTable();
                sda.Fill(table);
            }
            string host     = string.Empty;
            string userName = string.Empty;;
            string password = string.Empty;;
            int    port     = 993;
            bool   ssl      = true;

            foreach (DataRow row in table.Rows)
            {
                host     = row["Host"].ToString();
                userName = row["UserName"].ToString();
                password = row["Password"].ToString();
                port     = int.Parse(row["Port"].ToString());
            }
            string      json  = string.Empty;
            List <Item> items = new List <Item>();

            using (POP3_Client client = new POP3_Client())
            {
                client.Connect(host, port, ssl);
                client.Authenticate(userName, password, false);
                var messages = client.Messages;
                foreach (POP3_ClientMessage message in messages)
                {
                    Mail_Message email = Mail_Message.ParseFromByte(message.MessageToByte());
                    Item         item  = new Item
                    {
                        Sender   = email.From.ToString().Replace("\"", ""),
                        Subject  = email.Subject,
                        SendDate = email.Date.ToString(),
                        Date     = email.Date.ToString(),
                    };
                    items.Add(item);
                }
            }
            items = items.OrderByDescending(i => i.SendDate).ToList <Item>();
            json  = JsonConvert.SerializeObject(items);
            context.Response.Write(json);
        }
Esempio n. 19
0
        protected void btnTestConnection_Click(object sender, EventArgs e)
        {
            int port = 993;

            WX.WXUser user     = WX.Main.CurUser;
            string    host     = this.txtHostAddress.Text.Trim();
            string    userName = this.txtUserName.Text.Trim();
            string    password = this.txtPassword.Text.Trim();
            bool      b        = int.TryParse(this.txtPort.Text, out port);
            bool      ssl      = this.chkSSL.Checked;

            using (POP3_Client client = new POP3_Client())
            {
                try
                {
                    client.Connect(host, port, ssl);
                    client.Authenticate(userName, password, false);
                    using (SqlConnection connection = new SqlConnection(connectionString))
                    {
                        connection.Open();
                        string insertText = "INSERT INTO [TU_EmailPOP] ([UserID],[Host],[UserName],[Password],[Port],[SSL]) VALUES (@UserID,@Host,@UserName,@Password,@Port,@SSL)";
                        string updateText = "UPDATE [TU_EmailPOP] SET [UserID]=@UserID,[Host]=@Host,[UserName]=@UserName,[Password]=@Password,[Port]=@Port,[SSL]=@SSL";

                        SqlCommand command;
                        command = new SqlCommand("SELECT COUNT(ID) FROM [TU_EmailPOP] WHERE UserID='" + user.UserID + "'", connection);
                        int row = (int)command.ExecuteScalar();
                        if (row > 0)
                        {
                            command = new SqlCommand(updateText, connection);
                        }
                        else
                        {
                            command = new SqlCommand(insertText, connection);
                        }
                        command.Parameters.AddWithValue("@UserID", user.UserID);
                        command.Parameters.AddWithValue("@Host", host);
                        command.Parameters.AddWithValue("@UserName", userName);
                        command.Parameters.AddWithValue("@Password", password);
                        command.Parameters.AddWithValue("@Port", port);
                        command.Parameters.AddWithValue("@SSL", true);
                        command.ExecuteNonQuery();
                        MessageBox.ShowAndRedirect(this, "邮箱配置成功", Request.RawUrl);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.ShowAndRedirect(this, "邮箱配置失败:" + ex.Message, Request.RawUrl);
                }
            }
        }
Esempio n. 20
0
        public List <Mime> GetEmailsByLumiSoft()
        {                                                //需要首先设置这些信息
            string        pop3Server  = this.pop3Server; //邮箱服务器 如:"pop.sina.com.cn";或 "pop.tom.com" 好像sina的比较快
            int           pop3Port    = this.pop3Port;   //端口号码   用"110"好使。最好看一下你的邮箱服务器用的是什么端口号
            bool          pop3UseSsl  = false;
            string        username    = this.username;   //你的邮箱用户名
            string        password    = this.password;   //你的邮箱密码
            List <string> gotEmailIds = new List <string>();
            List <Mime>   result      = new List <Mime>();

            using (POP3_Client pop3 = new POP3_Client())
            {
                try
                {
                    //与Pop3服务器建立连接
                    pop3.Connect(pop3Server, pop3Port, pop3UseSsl);
                    //验证身份
                    pop3.Login(username, password);
                    //获取邮件信息列表
                    POP3_ClientMessageCollection infos = pop3.Messages;

                    foreach (POP3_ClientMessage info in infos)
                    {
                        //每封Email会有一个在Pop3服务器范围内唯一的Id,检查这个Id是否存在就可以知道以前有没有接收过这封邮件
                        if (gotEmailIds.Contains(info.UID))
                        {
                            continue;
                        }

                        //获取这封邮件的内容
                        byte[] bytes = info.MessageToByte();

                        //记录这封邮件的Id
                        gotEmailIds.Add(info.UID);

                        //解析从Pop3服务器发送过来的邮件信息
                        Mime mime = Mime.Parse(bytes);

                        //mime.Attachments[0].DataToFile(@"c:\" + mime.Attachments[0].ContentDisposition_FileName);
                        result.Add(mime);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
            return(result);
        }
Esempio n. 21
0
 public void Connect(String server, String User, String pass, int port, bool useSSl)
 {
     try
     {
         Client = new POP3_Client();
         Client.Connect(server, port, useSSl);
         Client.Login(User, pass);
         _IsConnected = true;
     }
     catch (Exception exe)
     {
         throw new EMailException {
                   ExceptionType = EMAIL_EXCEPTION_TYPE.ERROR_ON_CONNECTION, InnerException = exe
         };
     }
 }
        public static string SearchSingleEmail(string subject,string date)
        {
            string userId = new WX.WXUser().UserID;
            DataTable table;
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM [TU_EmailPOP] WHERE UserID='" + userId + "'", connection);
                table = new DataTable();
                sda.Fill(table);
            }
            string host = string.Empty;
            string userName = string.Empty;
            string password = string.Empty;
            int port = 995;
            bool ssl = true;
            foreach (DataRow row in table.Rows)
            {
                host = row["Host"].ToString();
                userName = row["UserName"].ToString();
                password = row["Password"].ToString();
                port = int.Parse(row["Port"].ToString());
            }
            string json = string.Empty;
            using (POP3_Client client = new POP3_Client())
            {
                client.Connect(host, port, ssl);
                client.Authenticate(userName, password, false);
                var messages = client.Messages;

                foreach (POP3_ClientMessage message in messages)
                {
                    Mail_Message email = Mail_Message.ParseFromByte(message.MessageToByte());
                    if (email.Subject.Equals(subject) && email.Date == Convert.ToDateTime(date))
                    {
                        TestItem item = new TestItem
                        {
                            Subject = email.Subject,
                            Body = email.BodyHtmlText
                        };
                        json = JsonConvert.SerializeObject(item);
                    }
                }

            }
            return json;
        }
Esempio n. 23
0
 private void GetEmails()
 {
     using (POP3_Client c = new POP3_Client())
     {
         c.Connect("pop.exmail.qq.com", 995, true);
         c.Login("*****@*****.**", "1qaz!QAZ");
         if (c.Messages.Count > 0)
         {
             for (var i = 960; i > -1; i--)
             {
                 //var t = Mail_Message.ParseFromByte(c.Messages[i].MessageTopLinesToByte(50));
                 var header = Mail_Message.ParseFromByte(c.Messages[i].HeaderToByte());
                 var from   = header.From;
                 if (from != null && from.ToArray().Any(a => a.Address == "*****@*****.**"))
                 {
                     var t        = Mail_Message.ParseFromByte(c.Messages[i].MessageToByte());
                     var to       = t.To;
                     var date     = t.Date;
                     var subject  = t.Subject;
                     var bodyText = t.BodyText;
                     try
                     {
                         if (!string.IsNullOrWhiteSpace(t.BodyHtmlText))
                         {
                             bodyText = t.BodyHtmlText;
                         }
                         var match = regx.Match(bodyText);
                         if (this.richText_content.InvokeRequired)
                         {
                             this.richText_content.Invoke(new dispText(() => {
                                 this.richText_content.AppendText("\r\n" + string.Format("Account:{0};Pwd:{1};", match.Groups[1].Value, match.Groups[2].Value));
                             }));
                         }
                         else
                         {
                             this.richText_content.AppendText("\r\n" + string.Format("Account:{1};Pwd:{2};", match.Groups[0].Value, match.Groups[1].Value));
                         }
                     }
                     catch (Exception ex)
                     {}
                 }
             }
         }
     }
 }
Esempio n. 24
0
        /// <summary>
        /// 链接至服务器并读取邮件集合
        /// </summary>
        public override Boolean Authenticate()
        {
            try
            {
                _pop3Client = new POP3_Client();
                _pop3Client.Connect(Pop3Address, Pop3Port);     //通过POP3地址,端口连接服务器。
                _pop3Client.Login(EmailAddress, EmailPassword); //登录之后验证用户的合法性

                foreach (POP3_ClientMessage pop3ClientMessage in _pop3Client.Messages)
                {
                    _pop3MessageList.Add(pop3ClientMessage);
                }

                _mailTotalCount = _pop3MessageList.Count;

                return(ExitsError = true);
            }
            catch (Exception ex) { ErrorMessage = ex.Message; return(ExitsError = false); }
        }
Esempio n. 25
0
        private ConcurrentDictionary <string, Mail_Message> GetEmails(string pop3Server, int pop3Port, bool pop3UseSsl, string username, string password)
        {
            List <string> gotEmailIds = new List <string>();
            ConcurrentDictionary <string, Mail_Message> result = new ConcurrentDictionary <string, Mail_Message>();

            using (POP3_Client pop3 = new POP3_Client())
            {
                pop3.Connect(pop3Server, pop3Port, pop3UseSsl);
                pop3.Login(username, password);
                POP3_ClientMessageCollection infos = pop3.Messages;
                int maxRetriveMail = this.GetMaxRetrieveMail();
                int messageCount   = infos != null ? infos.Count : 0;
                int totalEmails    = (maxRetriveMail > 0 && messageCount > maxRetriveMail) ? maxRetriveMail : messageCount;
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Emails from Lotus Notes").Add("MaxRetriveMail", totalEmails).ToInputLogString());

                if (infos != null)
                {
                    for (int i = totalEmails; i > 0; i--)
                    {
                        var info = infos[i - 1];
                        if (gotEmailIds.Contains(info.UID))
                        {
                            continue;
                        }
                        gotEmailIds.Add(info.UID);
                        byte[] messageBytes = info.MessageToByte();

                        if (messageBytes != null && messageBytes.Length > 0)
                        {
                            Mail_Message mimeMessage = Mail_Message.ParseFromByte(messageBytes, new System.Text.UTF8Encoding(false));
                            Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Body").Add("SequenceNumber", i).Add("UID", info.UID).ToOutputLogString());
                            result.TryAdd(info.UID, mimeMessage);
                        }
                        else
                        {
                            Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail Body").Add("SequenceNumber", i).Add("Error Message", "Mail Body is null").ToOutputLogString());
                        }
                    }
                }
            }

            return(result);
        }
Esempio n. 26
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        public wfrm_Main()
        {
            InitUI();

            this.Visible = true;

            wfrm_Connect frm = new wfrm_Connect(new EventHandler <WriteLogEventArgs>(Pop3_WriteLog));

            if (frm.ShowDialog(this) == DialogResult.OK)
            {
                m_pPop3 = frm.POP3;

                FillMessagesList();
            }
            else
            {
                Dispose();
            }
        }
Esempio n. 27
0
        public List <Mail_Message> ReciveEmail()
        {
            List <Mail_Message> mailMsgs = new List <Mail_Message>();

            POP3_Client pop3 = new POP3_Client();

            //pop3.Connect("pop3.sina.com.cn",110);
            pop3.Connect(Pop3Server, Pop3Port, SSL);
            //pop3.Login("lulufaer", "ljc123456");
            pop3.Login(MailAccount, MailPassword);

            if (pop3.IsAuthenticated)
            {
                for (int i = 0; i < pop3.Messages.Count; i++)
                {
                    //MailMsg msg= new MailMsg();

                    byte[] bytes = pop3.Messages[i].MessageToByte();

                    Mail_Message m_msg = Mail_Message.ParseFromByte(bytes);

                    //msg.msgFrom = m_msg.From[0].Address;
                    //msg.msgTime = m_msg.Date;
                    //msg.msgTo = m_msg.To.Mailboxes[0].Address;

                    //msg.MsgSubject = m_msg.Subject;
                    //msg.MsgContent = m_msg.BodyText;

                    mailMsgs.Add(m_msg);

                    if (DelAfterRecived)
                    {
                        pop3.Messages[i].MarkForDeletion();
                        //pop3.Messages[i].MarkForDeletion();
                        //pop3.Messages[i].MarkForDeletion();
                    }
                }
            }
            pop3.Disconnect();

            return(mailMsgs);
        }
Esempio n. 28
0
        private void DeleteMail(string pop3Server, int pop3Port, bool pop3UseSsl, string username, string password, List <string> mailMsgIds)
        {
            using (POP3_Client c = new POP3_Client())
            {
                c.Connect(pop3Server, pop3Port, pop3UseSsl);
                c.Login(username, password);

                var totalEmail = c.Messages.Count;
                Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail List").Add("MailList Size", totalEmail).ToOutputLogString());

                if (totalEmail > 0)
                {
                    foreach (POP3_ClientMessage mail in c.Messages)
                    {
                        if (mailMsgIds.Contains(mail.UID))
                        {
                            Logger.Info(_logMsg.Clear().SetPrefixMsg("Get Mail by UID").Add("UID", mail.UID)
                                        .Add("SequenceNumber", mail.SequenceNumber).Add("Mail Size", mail.Size).ToInputLogString());

                            try
                            {
                                mail.MarkForDeletion();
                            }
                            catch (POP3_ClientException pex)
                            {
                                Logger.Error("POP3_ClientException occur:\n", pex);
                            }

                            if (mail.IsMarkedForDeletion)
                            {
                                Logger.Info(_logMsg.Clear().SetPrefixMsg("Mark For Deletion").ToSuccessLogString());
                            }
                            else
                            {
                                Logger.Info(_logMsg.Clear().SetPrefixMsg("Mark For Deletion").Add("Error Message", "Failed to delete an email").ToFailLogString());
                                throw new CustomException(string.Format(CultureInfo.InvariantCulture, "Failed to delete an email {0}", mail.UID));
                            }
                        }
                    }
                }
            }
        }
Esempio n. 29
0
        private void DeleteMail(string pop3Server, int pop3Port, bool pop3UseSsl, string username, string password, List <string> mailMsgIds)
        {
            using (POP3_Client c = new POP3_Client())
            {
                c.Connect(pop3Server, pop3Port);
                c.Authenticate(username, password, pop3UseSsl);

                if (c.Messages.Count > 0)
                {
                    foreach (POP3_ClientMessage mail in c.Messages)
                    {
                        if (mailMsgIds.Contains(mail.UID))
                        {
                            Logger.Info(_logMsg.Clear().SetPrefixMsg("Mark For Deletion").Add("UID", mail.UID));
                            mail.MarkForDeletion();
                        }
                    }
                }
            }
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    // release managed resources
                }

                // release unmanaged resources
                // disposal of injected dependencies is managed by the IOC container
                if (_popClient != null)
                {
                    _popClient.Dispose();
                    _popClient = null;
                }
            }

            _disposed = true;
        }