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(); } }
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); }
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(); } }
/// <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; } }
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); } }
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); }
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); }
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); }
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); }
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(); } }
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(); }
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 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); }
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); }
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); }
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); } } }
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); }
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; }
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) {} } } } } }
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); }
/// <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); } }
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)); } } } } } }
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); }
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(); } } } } }
public static void Main() { POP3_Client Mailbox = new POP3_Client(new IntegratedSocket("pop.yourisp.com", 110), "yourusername", "yourpassword"); Mailbox.Connect(); Debug.Print("Message count: " + Mailbox.MessageCount.ToString()); Debug.Print("Box size in bytes: " + Mailbox.BoxSize.ToString()); uint[] Id, Size; Mailbox.ListMails(out Id, out Size); for (int Index = 0; Index < Id.Length; ++Index) { string[] Headers = Mailbox.FetchHeaders(Id[Index], new string[] { "subject", "from", "date" }); Debug.Print("Mail ID " + Id[Index].ToString() + " is " + Size[Index].ToString() + " bytes"); Debug.Print("Subject: " + Headers[0]); Debug.Print("From: " + Headers[1]); Debug.Print("Date: " + Headers[2]); Debug.Print("======================================================================"); } Mailbox.Close(); }
/// <summary> /// 获取指定邮箱的收件箱 /// </summary> /// <param name="pop3Server">POP3邮件服务器</param> /// <param name="pop3port"></param> /// <param name="emailAddress"></param> /// <param name="password"></param> /// <returns></returns> public List <POP3_ClientMessage> GetEmailInfos(string pop3Server, int pop3Port, bool pop3UseSsl, string emailAddress, string password) { List <POP3_ClientMessage> emailMessage = new List <POP3_ClientMessage>(); POP3_ClientMessageCollection result = null; using (POP3_Client pop3 = new POP3_Client()) { //与Pop3服务器建立连接 pop3.Connect(pop3Server, pop3Port, pop3UseSsl); //验证身份 pop3.Login(emailAddress, password); //获取邮件信息列表 result = pop3.Messages; foreach (POP3_ClientMessage message in pop3.Messages) { emailMessage.Add(message); SaveEmail(message); //Mail_Message mime_header = Mail_Message.ParseFromByte(message.HeaderToByte()); } } return(emailMessage); }
/// <summary> /// 获取 /// </summary> /// <param name="account">配置</param> /// <param name="receiveCount">已收邮件数、注意:如果已收邮件数和邮件数量一致则不获取</param> /// <returns></returns> public static List <MailModel> Get(MailAccount account, int receiveCount) { try { var filePath = DirFileHelper.GetAbsolutePath("~/Resource/EmailFile/"); var resultList = new List <MailModel>(); using (POP3_Client pop3Client = new POP3_Client()) { pop3Client.Connect(account.POP3Host, account.POP3Port, account.Ssl); pop3Client.Login(account.Account, account.Password); var messages = pop3Client.Messages; if (receiveCount == messages.Count) { return(resultList); } for (int i = messages.Count - 1; receiveCount <= i; i--) { var messageItem = messages[i]; var messageHeader = Mail_Message.ParseFromByte(messageItem.MessageToByte()); resultList.Add(new MailModel() { UID = messageItem.UID, To = messageHeader.From == null ? "" : messageHeader.From[0].Address, ToName = messageHeader.From == null ? "" : messageHeader.From[0].DisplayName, Subject = messageHeader.Subject, BodyText = messageHeader.BodyHtmlText, Attachment = GetFile(filePath, messageHeader.GetAttachments(true, true), messageItem.UID), Date = messageHeader.Date, }); } } return(resultList); } catch (Exception ex) { throw ex; } }
/// <summary> /// Reads the mail. /// </summary> public MailboxReaderResult ReadMail() { var result = new MailboxReaderResult(); IList <Project> projects = new List <Project>(); LogInfo("MailboxReader: Begin read mail."); try { using (var pop3Client = new POP3_Client()) { // configure the logger pop3Client.Logger = new Logger(); pop3Client.Logger.WriteLog += LogPop3Client; // connect to the server pop3Client.Connect(Config.Server, Config.Port, Config.UseSsl); // authenticate pop3Client.Login(Config.Username, Config.Password); // process the messages on the server foreach (POP3_ClientMessage message in pop3Client.Messages) { var mailHeader = Mail_Message.ParseFromByte(message.HeaderToByte()); if (mailHeader != null) { var messageFrom = string.Empty; if (mailHeader.From.Count > 0) { messageFrom = string.Join("; ", mailHeader.From.ToList().Select(p => p.Address).ToArray()).Trim(); } var recipients = mailHeader.To.Mailboxes.Select(mailbox => mailbox.Address).ToList(); if (mailHeader.Cc != null) { recipients.AddRange(mailHeader.Cc.Mailboxes.Select(mailbox => mailbox.Address)); } if (mailHeader.Bcc != null) { recipients.AddRange(mailHeader.Bcc.Mailboxes.Select(mailbox => mailbox.Address)); } // loop through the mailboxes foreach (var address in recipients) { var pmbox = ProjectMailboxManager.GetByMailbox(address); // cannot find the mailbox skip the rest if (pmbox == null) { LogWarning(string.Format("MailboxReader: could not find project mailbox: {0} skipping.", address)); continue; } var project = projects.FirstOrDefault(p => p.Id == pmbox.ProjectId); if (project == null) { project = ProjectManager.GetById(pmbox.ProjectId); // project is disabled skip if (project.Disabled) { LogWarning(string.Format("MailboxReader: Project {0} - {1} is flagged as disabled skipping.", project.Id, project.Code)); continue; } projects.Add(project); } var entry = new MailboxEntry { Title = mailHeader.Subject.Trim(), From = messageFrom, ProjectMailbox = pmbox, Date = mailHeader.Date, Project = project, Content = "Email Body could not be parsed." }; var mailbody = Mail_Message.ParseFromByte(message.MessageToByte()); if (string.IsNullOrEmpty(mailbody.BodyHtmlText)) // no html must be text { entry.Content = mailbody.BodyText.Replace("\n\r", "<br/>").Replace("\r\n", "<br/>").Replace("\r", ""); } else { //TODO: Enhancements could include regular expressions / string matching or not matching // for particular strings values in the subject or body. // strip the <body> out of the message (using code from below) var bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline); var match = bodyExtractor.Match(mailbody.BodyHtmlText); var emailContent = match.Success && match.Groups["content"] != null ? match.Groups["content"].Value : mailbody.BodyHtmlText; entry.Content = emailContent.Replace("<", "<").Replace(">", ">"); entry.IsHtml = true; } if (Config.ProcessAttachments && project.AllowAttachments) { foreach (var attachment in mailbody.GetAttachments(Config.ProcessInlineAttachedPictures).Where(p => p.ContentType != null)) { entry.MailAttachments.Add(attachment); } } //save this message SaveMailboxEntry(entry); // add the entry if the save did not throw any exceptions result.MailboxEntries.Add(entry); LogInfo(string.Format( "MailboxReader: Message #{0} processing finished, found [{1}] attachments, total saved [{2}].", message.SequenceNumber, entry.MailAttachments.Count, entry.AttachmentsSavedCount)); // delete the message?. if (!Config.DeleteAllMessages) { continue; } try { message.MarkForDeletion(); } catch (Exception) { } } } else { LogWarning(string.Format("pop3Client: Message #{0} header could not be parsed.", message.SequenceNumber)); } } } } catch (Exception ex) { LogException(ex); result.LastException = ex; result.Status = ResultStatuses.FailedWithException; } LogInfo("MailboxReader: End read mail."); return(result); }