/// <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(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(); } }
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 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(); } }
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); } } } } }
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 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 }; } }
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) {} } } } } }
/// <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 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); }
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, 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)); } } } } } }
/// <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); }
/// <summary> /// Starts messages fetching. /// </summary> public void StartFetching() { if (m_Fetching) { return; } m_Fetching = true; try { DataView dvUsers = m_pApi.GetUsers("ALL"); using (DataView dvServers = m_pApi.GetUserRemoteServers("")) { foreach (DataRowView drV in dvServers) { try { if (!ConvertEx.ToBoolean(drV["Enabled"])) { continue; } // Find user name from user ID string userName = ""; dvUsers.RowFilter = "UserID='" + drV["UserID"] + "'"; if (dvUsers.Count > 0) { userName = dvUsers[0]["UserName"].ToString(); } else { continue; } string server = drV.Row["RemoteServer"].ToString(); int port = Convert.ToInt32(drV.Row["RemotePort"]); string user = drV.Row["RemoteUserName"].ToString(); string passw = drV.Row["RemotePassword"].ToString(); bool useSSL = ConvertEx.ToBoolean(drV["UseSSL"]); // Connect and login to pop3 server using (POP3_Client clnt = new POP3_Client()) { clnt.Logger = new LumiSoft.Net.Log.Logger(); clnt.Logger.WriteLog += new EventHandler <WriteLogEventArgs>(Pop3_WriteLog); clnt.Connect(server, port, useSSL); clnt.Login(user, passw); foreach (POP3_ClientMessage message in clnt.Messages) { // Store message m_pServer.ProcessUserMsg("", "", userName, "Inbox", new MemoryStream(message.MessageToByte()), null); message.MarkForDeletion(); } } } catch { } } } m_LastFetch = DateTime.Now; } catch (Exception x) { Error.DumpError(m_pServer.Name, x); } m_Fetching = false; }
public static void GetEmails() { using (POP3_Client c = new POP3_Client()) { c.Connect("pop.qq.com", 995, true); c.Login("*****@*****.**", "evyacsgisnylbiac"); Console.WriteLine(c.Messages.Count.ToString()); List <string> successList = new List <string>(); List <string> failedList = new List <string>(); if (c.Messages.Count > 0) { for (var i = 0; i < c.Messages.Count; i++) { try { var t = Mail_Message.ParseFromByte(c.Messages[i].MessageToByte()); var from = t.From; var to = t.To; var date = t.Date; var subject = t.Subject; var bodyText = t.BodyText; if (subject == "圕哥邮件通知") { Console.WriteLine(bodyText); if (bodyText.StartsWith("参赛人信息")) { successList.Add(bodyText); } else { failedList.Add(bodyText); } } } catch (Exception e) { Console.WriteLine(e.Message); } } string folder = AppDomain.CurrentDomain.BaseDirectory.ToString(); if (successList.Count > 0) { DataTable dt = new DataTable(); dt.Columns.Add("姓名"); dt.Columns.Add("学院"); dt.Columns.Add("学号"); dt.Columns.Add("电话"); dt.Columns.Add("QQ"); foreach (string line in successList) { string[] item = line.Replace("参赛人信息:", "").Split(','); DataRow dr = dt.NewRow(); dr["姓名"] = item[0].Replace("姓名:", ""); dr["学院"] = item[1].Replace("学院:", ""); dr["学号"] = item[2].Replace("学号:", ""); dr["电话"] = item[3].Replace("电话号码:", ""); dr["QQ"] = item[4].Replace("QQ:", ""); dt.Rows.Add(dr); } Console.WriteLine("导出愿意参赛.xlsx"); Excel succExcle = new Excel(dt); succExcle.Save(folder + "愿意参赛.xlsx"); } if (failedList.Count > 0) { DataTable dt = new DataTable(); dt.Columns.Add("姓名"); dt.Columns.Add("学号"); foreach (string line in failedList) { string[] item = line.Replace("拒绝参赛:", "").Split(','); DataRow dr = dt.NewRow(); dr["姓名"] = item[0].Replace("姓名:", ""); dr["学号"] = item[1].Replace("学号:", ""); dt.Rows.Add(dr); } Console.WriteLine("导出拒绝参赛.xlsx"); Excel succExcle = new Excel(dt); succExcle.Save(folder + "拒绝参赛.xlsx"); } Console.WriteLine("同意参加" + successList.Count.ToString() + "人"); Console.WriteLine("拒绝参赛" + failedList.Count.ToString() + "人"); Console.WriteLine("高完"); } } }
public void functionPOP() { using (POP3_Client c = new POP3_Client()) { try { //连接POP3服务器 c.Connect("outlook.office365.com", 995, true); //验证用户身份 c.Login(UserName, Pwd); //邮件密码/smtp、pop3授权码 MessageBox.Show("数量:" + c.Messages.Count.ToString()); if (c.Messages.Count > 0) { //遍历收件箱里的每一封邮件 var message = c.Messages[0]; //foreach (POP3_ClientMessage message in c.Messages) //{ //try //{ //mail.MarkForDeletion(); //删除邮件 //收件人、发件人、主题、时间等等走在mime_header里获得 Mail_Message mime_header = Mail_Message.ParseFromByte(message.HeaderToByte()); //发件人 if (mime_header.From != null) { string displayname = mime_header.From[0].DisplayName; string from = mime_header.From[0].Address; MessageBox.Show($"displayname:{displayname}--from{from}"); } //收件人 if (mime_header.To != null) { StringBuilder sb = new StringBuilder(); foreach (Mail_t_Mailbox recipient in mime_header.To.Mailboxes) { string displayname = recipient.DisplayName; string address = recipient.Address; if (!string.IsNullOrEmpty(displayname)) { sb.AppendFormat("{0}({1});", displayname, address); } else { sb.AppendFormat("{0};", address); } } } //抄送 if (mime_header.Cc != null) { StringBuilder sb = new StringBuilder(); foreach (Mail_t_Mailbox recipient in mime_header.Cc.Mailboxes) { string displayname = recipient.DisplayName; string address = recipient.Address; if (!string.IsNullOrEmpty(displayname)) { sb.AppendFormat("{0}({1});", displayname, address); } else { sb.AppendFormat("{0};", address); } } } //发送邮件时间 DateTime dateTime = mime_header.Date; string ContentID = mime_header.ContentID; string MessageID = mime_header.MessageID; string OrgMessageID = mime_header.OriginalMessageID; string Subject = mime_header.Subject; byte[] messageBytes = message.MessageToByte(); Mail_Message mime_message = Mail_Message.ParseFromByte(messageBytes); if (mime_message == null) { //continue; return; } string Body = mime_message.BodyText; //try //{ if (!string.IsNullOrEmpty(mime_message.BodyHtmlText)) { //邮件内容 string BodyHtml = mime_message.BodyHtmlText; //MessageBox.Show(BodyHtml); } //} //catch //{ //} //} //catch (Exception ex) //{ //} } //} //} } catch (Exception e) { MessageBox.Show(e.Message); } } }
/// <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 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)); } // first check if this is a comment (comments are implemented using plus addressing) // a comment will have a replyto address like [email]+iid-[number]@domain.com bool isProcessed = false; if (HostSettingManager.Get <bool>(HostSettingNames.Pop3AllowReplyToEmail, false)) { isProcessed = ProcessNewComment(recipients, message, mailHeader, result); } if (!isProcessed) { isProcessed = ProcessNewIssue(recipients, message, mailHeader, projects, result); } if (isProcessed) { LogInfo(string.Format( "MailboxReader: Message #{0} processing finished, found [{1}] attachments, total saved [{2}].", message.SequenceNumber, 0, 0)); try { // delete the message?. if (Config.DeleteAllMessages) { 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); }
private void button10_Click(object sender, EventArgs e) { POPserver = textBox8.Text; user = textBox9.Text; password = textBox6.Text; TcpClient receiver = new TcpClient(); try { receiver.Connect(POPserver, 110); liststatus.Items.Add("连接成功"); } catch { MessageBox.Show("无法连接到服务器"); } nwStream = receiver.GetStream(); if (nwStream == null) { throw new Exception("无法取得回复"); } string returnMsg = ReadStream(ref nwStream); checkerror(returnMsg); liststatus.Items.Add("连接应答" + returnMsg + "\r\n"); try { WriteStream(ref nwStream, "USER " + user); returnMsg = ReadStream(ref nwStream); checkerror(returnMsg); liststatus.Items.Add("POP3server:" + returnMsg + "\r\n"); WriteStream(ref nwStream, "PASS " + password); returnMsg = ReadStream(ref nwStream); checkerror(returnMsg); liststatus.Items.Add("POP3server:" + returnMsg + "\r\n"); WriteStream(ref nwStream, "STAT"); returnMsg = ReadStream(ref nwStream); checkerror(returnMsg); liststatus.Items.Add("POP3server:" + returnMsg + "\r\n"); string[] totalstat = returnMsg.Split(new char[] { ' ' }); mailnumber = Int32.Parse(totalstat[1]); textBox10.Text = "共" + totalstat[1] + "封邮件"; //接收邮件 POP3_Client pop = new POP3_Client(); pop.Connect(POPserver, 995, true); liststatus.Items.Add("连接成功"); pop.Login(user, password); POP3_ClientMessageCollection messages = pop.Messages; for (int i = 0; i < mailnumber; i++) { POP3_ClientMessage message = messages[i]; if (message != null) { Byte[] messageBytes = message.MessageToByte(); Mail_Message mimemessage = Mail_Message.ParseFromByte(messageBytes); pop3client cli = new pop3client(mimemessage.From[0].DisplayName, mimemessage.From[0].Address, mimemessage.Date.ToLongDateString(), mimemessage.Subject, mimemessage.BodyText, mimemessage.GetAttachments(true, true), i + 1); mailreceive.Add(cli); // mailreceive[i].sender1= mimemessage.From[0].DisplayName; //mailreceive[i].senderaddress = mimemessage.From[0].Address; //mailreceive[i].senderdate = mimemessage.Date.ToLongDateString(); // mailreceive[i].subject = mimemessage.Subject; //mailreceive[i].content = mimemessage.BodyText; //mailreceive[i].attachment = mimemessage.GetAttachments(true, true); //mailreceive[i].num = i + 1; listView1.Items.Add(new ListViewItem(new string[] { (i + 1).ToString(), mailreceive[i].sender1, mailreceive[i].subject, mailreceive[i].senderdate, "无" })); foreach (MIME_Entity entity in mailreceive[i].attachment) { string filename = entity.ContentDisposition.Param_FileName; cli.getfilename(filename); listView1.Items[i].SubItems.Add(" "); listView1.Items[i].SubItems[4].Text = filename; } } } } catch (InvalidOperationException ex) { Console.WriteLine("登陆失败"); } }
private void LumiSoftMail() { string sendmail, HtmlBody = "", date; //网络连接判断 if (!IsNetConnect()) { return; } POP3_Client popMail = new POP3_Client(); try { popMail.Timeout = HtmlTextPath.EMAIL_TIME_OUT; if (string.IsNullOrEmpty(MAIL_USER_NAME) || string.IsNullOrEmpty(MAIL_USER_PWD) || string.IsNullOrEmpty(MAIL_POP) || string.IsNullOrEmpty(MAIL_SENDER) || string.IsNullOrEmpty(PRT_COUNT) || string.IsNullOrEmpty(COMPANY_NAME)) { QueryUser(); } try { popMail.Connect(MAIL_POP, HtmlTextPath.EMAIL_PORT, false); } catch (Exception ex) { Console.Out.WriteLine("ex:" + ex); SetRichTextValue(DateTime.Now.ToString("o") + @"######Internet connection failed######"); return; //throw; } //登录邮箱地址 popMail.Login(MAIL_USER_NAME, MAIL_USER_PWD); } catch (Exception ex) { Console.Out.WriteLine("ex:" + ex); //richTextBox1.Text += System.Environment.NewLine + "ex:" + ex; //Console.Out.WriteLine("Can not connect email server" + DateTime.Now.ToString("o")); //richTextBox1.Text += System.Environment.NewLine + "Can not connect email server:" + DateTime.Now.ToString("o"); //SetRichTextValue("MAIL_USER_NAME:" + MAIL_USER_NAME + "MAIL_USER_PWD:" + MAIL_USER_PWD + "MAIL_POP:" + MAIL_POP + "MAIL_SENDER:" + MAIL_SENDER + "PRT_COUNT:" + PRT_COUNT + "COMPANY_NAME:" + COMPANY_NAME); SetRichTextValue(DateTime.Now.ToString("o") + @"######Can not connect email server######"); return; } Console.Out.WriteLine(DateTime.Now.ToString("o")); SetRichTextValue(DateTime.Now.ToString("o")); POP3_ClientMessageCollection messagesCollection = popMail.Messages; POP3_ClientMessage message = null; //存放需删除的邮件 List <POP3_ClientMessage> lstMessage = new List <POP3_ClientMessage>(); string strMessage = ""; if (0 < messagesCollection.Count) { //for (int i = messagesCollection.Count - 1; i >= 0; i--) for (var index = 0; index < popMail.Messages.Count; index++) { POP3_ClientMessage mail = popMail.Messages[index]; try { message = mail; } catch (Exception) { popMail.Timeout = HtmlTextPath.EMAIL_TIME_OUT; popMail.Connect(MAIL_POP, HtmlTextPath.EMAIL_PORT, true); popMail.Login(MAIL_USER_NAME, MAIL_USER_PWD); } Mail_Message mailMessage = null; try { if (message != null) { byte[] messBytes = message.MessageToByte(); mailMessage = Mail_Message.ParseFromByte(messBytes); } else { continue; } } catch (Exception) { SetRichTextValue(DateTime.Now.ToString("o") + @"ERR GET MSG TO BYTE"); continue; //Console.WriteLine(@"ERR GET MSG TO BYTE:" + DateTime.Now.ToString("o")); //throw; } sendmail = mailMessage.From[0].Address; HtmlBody = mailMessage.BodyHtmlText; if (!sendmail.Equals(MAIL_SENDER)) { message.MarkForDeletion(); SetRichTextValue(DateTime.Now.ToString("o") + @"######===" + sendmail + "===Message discarded#####"); continue; } //PrtOrder(HtmlBody.Replace("脳", "×").Replace("拢", "£")); //PrtOrderWithTemplate(HtmlBody); if (VERSION.Equals("2")) { HtmlBody = HtmlBody.Replace("<body style=\"", "<body style=\"font-family:Arial; "); } else if (VERSION.Equals("3")) { HtmlBody = HtmlBody.Replace("<body", "<body style=\"font-family:Arial; \""); } //读取Html失败时,跳出循环 if (!GetPrtInfo(HtmlBody)) { message.MarkForDeletion(); SetRichTextValue(DateTime.Now.ToString("o") + @"######===" + orderId + "===OLD Message discarded#####"); continue; } ////DataGridView中的订单号不能重复 //for (int j = 0; j < dgvOrder.RowCount; j++) //{ // if (dgvOrder.Rows[j].Cells[0].Value != null) // { // if (!string.IsNullOrEmpty(dgvOrder.Rows[j].Cells[0].Value.ToString())) // { // if (dgvOrder.Rows[j].Cells[0].Value.ToString().Equals(orderId)) // { // message.MarkForDeletion(); // SetRichTextValue(DateTime.Now.ToString("o") + @"######===" + orderId + "===DGV Message discarded#####"); // continue; // } // } // } //} //存在订单时不打印 //if (SqlHelper.QueryId(@"SELECT mailID FROM Mail_ID WHERE orderID='" + orderId + "'")) //{ // SetRichTextValue(DateTime.Now.ToString("o") + @"######Duplicate order ID######"); // continue; //} if (VERSION.Equals("2")) { HtmlBody = HtmlBody.Replace("h1", "h4").Replace("<p>", "").Replace("</p>", "<br />") .Replace("<p style=\"width:94%;\">", "").Replace("<strong>", "").Replace("</strong>", ""); //HtmlBody = HtmlBody.Replace("h1", "h5"); HtmlBody = HtmlBody.Replace("<h4>", "").Replace("</h4>", "").Replace("<b>", "") .Replace("</b>", "") .Replace("border-top:hidden;", "").Replace("style=\"border-top:hidden;\"", ""); } else if (VERSION.Equals("3")) { //中文字体更大一号字体 HtmlBody = HtmlBody.Replace("<span style=\"font-size:18px;\">", "<span style=\"font-size:24px;\">"); HtmlBody = HtmlBody.Replace("h1", "h4").Replace("<p>", "").Replace("</p>", "<br />") .Replace("<p style=\"width:94%;\">", "").Replace("<strong>", "").Replace("</strong>", ""); //HtmlBody = HtmlBody.Replace("h1", "h5"); HtmlBody = HtmlBody.Replace("<h4>", "").Replace("</h4>", "").Replace("<b>", "") .Replace("</b>", "") .Replace("border-top:hidden;", "").Replace("style=\"border-top:hidden;\"", ""); } //打印完成后插入数据 if (!SqlHelper.InsertId( @"INSERT INTO Mail_ID(mailID, orderID, orderType, orderTime, orderHtmlBody) VALUES('" + mail.UID + "', '" + orderId + "', '" + orderType + "', '" + orderDate + "', '')")) { MessageBox.Show(@"WRITE Data Error!", @"ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { //int index = this.dgvOrder.Rows.Add(); this.dgvOrder.Rows.Insert(0, dgvOrder.Rows); dgvOrder.Rows[0].Cells[0].Value = orderId; dgvOrder.Rows[0].Cells[1].Value = orderDate; dgvOrder.Rows[0].Cells[2].Value = orderType; dgvOrder.Rows[0].Cells[3].Value = HtmlBody; dgvOrder.Refresh(); } //播放语音提示 if (File.Exists(Environment.CurrentDirectory + wavNewMail)) { SoundPlayer player = new SoundPlayer(Environment.CurrentDirectory + wavNewMail); player.Play(); } SetRichTextValue(@"#Time Printing order number=" + orderId); PrtContent(HtmlBody); //完成后添加删除邮件 lstMessage.Add(message); } for (int i = lstMessage.Count - 1; i >= 0; i--) { try { lstMessage[i].MarkForDeletion(); Console.WriteLine(@"DELETE MAIL DONE:" + DateTime.Now.ToString("o")); } catch (Exception) { Console.WriteLine(@"DELETE MAIL FAILURE:" + DateTime.Now.ToString("o")); //throw; } } if (popMail != null) { //popMail = null; try { popMail.Disconnect(); } catch (Exception) { //Console.Out.WriteLine("Error if (popMail != null)"); SetRichTextValue(@"Error POPMail != null"); } } } else { try { SetRichTextValue(DateTime.Now.ToString("o") + @"#No mail received#"); popMail.Disconnect(); } catch (Exception) { //Console.Out.WriteLine("Error else"); SetRichTextValue(@"Error ELSE"); } } }
private void ReceiveMail(string OApop3Server, Int32 OApop3ServerPort, string OAUsername, string OAUserPwd, string OutPath, string EmailSubject, string EmailAddress) { using (POP3_Client pop3 = new POP3_Client()) { try { pop3.Connect(OApop3Server, OApop3ServerPort, true); } catch (Exception ex) { } pop3.Connect(OApop3Server, OApop3ServerPort, true); pop3.Login(OAUsername, OAUserPwd);//两个参数,前者为Email的账号,后者为Email的密码 POP3_ClientMessageCollection messages = pop3.Messages; LogHelper.WriteLog(LogLevel.LOG_LEVEL_INFO, string.Format("共{0}封邮件", messages.Count), typeof(AMSDownloadForm)); for (int i = 0; i < messages.Count; i++) { POP3_ClientMessage message = messages[i];//转化为POP3 LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("正在检查第{0}封邮件...", i + 1), typeof(AMSDownloadForm)); if (message != null) { byte[] messageBytes = null; try { messageBytes = message.MessageToByte(); } catch (Exception ex) { LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, string.Format("第{0}封邮件,message.MessageToByte() 失败 错误日志参考下一条信息", i), typeof(AMSDownloadForm)); LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(AMSDownloadForm)); } Mail_Message mime_message = Mail_Message.ParseFromByte(messageBytes); string sender = mime_message.From == null ? "sender is null" : mime_message.From[0].DisplayName; string senderAddress = mime_message.From == null ? "senderAddress is null" : mime_message.From[0].Address; string subject = mime_message.Subject ?? "subject is null"; string recDate = mime_message.Date == DateTime.MinValue ? "date not specified" : mime_message.Date.ToString(); string content = mime_message.BodyText ?? "content is null"; LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("正在检查第{0}封邮件, 邮件发送时间{1}", i + 1, mime_message.Date), typeof(AMSDownloadForm)); //Console.WriteLine("内容为{0}", content); // 判断此邮件是否是需要下载的邮件 // 发件人 & 发件主体 && 收件时间 DateTime dt = DateTime.Now; if (string.Equals(senderAddress, EmailAddress) && string.Equals(subject, EmailSubject.Replace("yyyyMMdd", dt.ToString("yyyyMMdd"))) && mime_message.Date.Date == dt.Date) { MIME_Entity[] attachments = mime_message.GetAttachments(true, true); foreach (MIME_Entity entity in attachments) { if (entity.ContentDisposition != null) { string fileName = entity.ContentDisposition.Param_FileName; if (!string.IsNullOrEmpty(fileName)) { DirectoryInfo dir = new DirectoryInfo(OutPath); if (!dir.Exists) { dir.Create(); } DirectoryInfo dir2 = new DirectoryInfo(OutPath + @"\" + DateTime.Now.ToString("yyyyMMdd") + @"\"); if (!dir2.Exists) { dir2.Create(); } string path = Path.Combine(dir.FullName, fileName); MIME_b_SinglepartBase byteObj = (MIME_b_SinglepartBase)entity.Body; Stream decodedDataStream = byteObj.GetDataStream(); using (FileStream fs = new FileStream(path, FileMode.Create)) { LumiSoft.Net.Net_Utils.StreamCopy(decodedDataStream, fs, 4000); } LogHelper.WriteLog(LogLevel.LOG_LEVEL_INFO, string.Format("{0}已经被下载。", fileName), typeof(AMSDownloadForm)); // 下载完成之后解压 (new FastZip()).ExtractZip(dir.FullName + fileName, dir2.FullName, ""); if (dir2.GetFiles().Length > 0 && dir2.GetDirectories().Length > 0) { MessageDxUtil.ShowTips("下载解压文件成功"); } } } } if (MessageDxUtil.ShowTips("下载成功") == DialogResult.OK) { Process.Start("explorer.exe", OutPath); } break; } // 时间超过了也退出 if (mime_message.Date.Date < dt.Date) { MessageDxUtil.ShowTips("根网清算文件未到,请稍后处理"); break; } } } LogHelper.WriteLog(LogLevel.LOG_LEVEL_INFO, "执行结束", typeof(AMSDownloadForm)); } }
static void pop3() { List <string> gotemailids = new List <string>(); using (LumiSoft.Net.POP3.Client.POP3_Client pop3 = new POP3_Client()) { try { //与pop3服务器建立连接 pop3.Connect("pop.qq.com", 110, false); //验证身份 pop3.Login("*****@*****.**", "myhaiyan"); //获取邮件信息列表 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 m = Mime.Parse(bytes); if (m != null) { string mailfrom = ""; string mailfromname = ""; if (m.MainEntity.From != null) { for (int i = 0; i < m.MainEntity.From.Mailboxes.Length; i++) { if (i == 0) { mailfrom = (m.MainEntity.From).Mailboxes[i].EmailAddress; } else { mailfrom += string.Format(",{0}", (m.MainEntity.From).Mailboxes[i].EmailAddress); } mailfromname = (m.MainEntity.From).Mailboxes[0].DisplayName != "" ? (m.MainEntity.From).Mailboxes[0].DisplayName : (m.MainEntity.From).Mailboxes[0].LocalPart; } } string mailto = ""; string mailtotocollection = ""; if (m.MainEntity.To != null) { mailtotocollection = m.MainEntity.To.ToAddressListString(); for (int i = 0; i < m.MainEntity.To.Mailboxes.Length; i++) { if (i == 0) { mailto = (m.MainEntity.To).Mailboxes[i].EmailAddress; } else { mailto += string.Format(",{0}", (m.MainEntity.To).Mailboxes[i].EmailAddress); } } } } //获取附件 foreach (MimeEntity entry in m.Attachments) { string filename = entry.ContentDisposition_FileName; //获取文件名称 string path = AppDomain.CurrentDomain.BaseDirectory + @"attch\" + filename; if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + @"attch")) { Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + @"attch"); } if (File.Exists(path)) { Random random = new Random(); int newfile = random.Next(1, 100000); path = AppDomain.CurrentDomain.BaseDirectory + @"attch\" + newfile.ToString(); Directory.CreateDirectory(path); path += @"\" + filename; } byte[] data = entry.Data; FileStream pfilestream = null; pfilestream = new FileStream(path, FileMode.Create); pfilestream.Write(data, 0, data.Length); pfilestream.Close(); } } } catch (Exception ex) { } } }
public void AnalysisLog_Thread() { DateTime dt_start = DatePicker_Start.Value; DateTime dt_end = DatePicker_End.Value; if (dt_start.Date > dt_end.Date) { return; } ListView[] all_item = new ListView[12]; for (int item_index = 0; item_index < 12; item_index++) { all_item[item_index] = new ListView(); } POP3_Client pop3 = new POP3_Client(); try { pop3.Connect("pop.qiye.163.com", WellKnownPorts.POP3, false); pop3.Login("*****@*****.**", "Lxrs1243"); m_pPop3 = pop3; try { int count = 0; this.Invoke(new Action(delegate() //多线程的处理 { timer1.Enabled = true; time_count = 0; toolStripProgressBar1.Value = 0; toolStripProgressBar1.Minimum = 0; toolStripProgressBar1.Maximum = m_pPop3.Messages.Count; toolStripProgressBar1.Step = 1; })); foreach (POP3_ClientMessage message in m_pPop3.Messages) { this.Invoke(new Action(delegate() //多线程的处理 { toolStripProgressBar1.Value++; })); Mail_Message mime = Mail_Message.ParseFromByte(message.HeaderToByte()); ListViewItem item = new ListViewItem(); if (string.IsNullOrEmpty(mime.Subject) || !mime.Subject.Contains("工作日")) { continue; } if (mime.Date > dt_start.Date && mime.Date < dt_end.AddDays(1).Date) { item.Text = mime.Subject.ToString(); //1.subject item.SubItems.Add(mime.Date.ToString()); //2.date } else { continue; } if (mime.From != null) //3.sender { string addr = mime.From.ToString(); string show_name = addr.Substring(addr.IndexOf("<") + 1, addr.IndexOf(">") - addr.IndexOf("<") - 1); bool exist = false; foreach (KeyValuePair <string, string> kvp in config._names) { if (kvp.Value.Equals(show_name)) { item.SubItems.Add(kvp.Key); exist = true; break; } } if (!exist) { item.SubItems.Add(show_name); } } else { item.SubItems.Add("<none>"); } item.SubItems.Add(((decimal)(message.Size / (decimal)1000)).ToString("f2") + " kb"); //4. size Mail_Message mimeBody = Mail_Message.ParseFromByte(message.MessageToByte()); if (mimeBody.BodyText != null) { item.SubItems.Add(mimeBody.BodyText); //5.content } else { mimeBody = Mail_Message.ParseFromByte(message.MessageToByte()); string content = null; this.Invoke(new Action(delegate() //多线程的处理 { HtmlToText convert = new HtmlToText(); content = convert.Convert(mimeBody.BodyHtmlText); })); item.SubItems.Add(content); //5.content } string date_time = item.SubItems[1].Text; int index = date_time.IndexOf("/"); string month = date_time.Substring(index + 1, date_time.IndexOf("/", index + 1) - index - 1); month.Trim(); all_item[Convert.ToInt16(month) - 1].Items.Add(item); if (count > 10) { break; } //count++; } } catch (Exception x) { MessageBox.Show(this, "Error: " + x.Message, "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception x) { MessageBox.Show(this, "POP3 server returned: " + x.Message + " !", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error); pop3.Dispose(); } Excel.Application oXL; Excel._Workbook oWB; Excel._Worksheet oSheet; Excel.Range oRng; try { oXL = new Excel.Application(); oXL.Visible = true; oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value)); int month_count = 0; int month = 0; for (; month < 12; month++) { if (all_item[month].Items.Count == 0) { continue; } month_count++; if (month_count <= 3) { oSheet = (Excel._Worksheet)oWB.Worksheets[month_count]; } else { oSheet = oWB.Worksheets.Add(); } //oSheet.Visible = Excel.XlSheetVisibility.xlSheetVisible; oSheet.Activate(); oSheet.Name = (month + 1).ToString() + "月份"; oRng = oSheet.get_Range("A1:BA1", Missing.Value); if (TB_DAILYW.Text != "") { oRng.ColumnWidth = Convert.ToInt16(TB_DAILYW.Text); } else { oRng.ColumnWidth = 40; } // oRng.Interior.ColorIndex = 35; oRng = oSheet.get_Range("A1:A30", Missing.Value); if (TB_DAILYH.Text != "") { oRng.RowHeight = Convert.ToInt16(TB_DAILYH.Text); } else { oRng.RowHeight = 25; } // oRng.Interior.ColorIndex = 36; oRng.Font.Bold = true; oRng = oSheet.get_Range("A1:BA50", Missing.Value); oRng.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft; // oRng.Borders.Weight = Excel.XlBorderWeight.xlThin; oRng = oSheet.get_Range("B2:BA50", Missing.Value); oRng.VerticalAlignment = Excel.XlVAlign.xlVAlignTop; int iRow = 1, iColumn = 1; ArrayList send_name = new ArrayList(); ArrayList send_date = new ArrayList(); string name = null; send_name.Add("No1"); send_date.Add("No1"); foreach (ListViewItem item in all_item[month].Items) { for (int i = 0; i < item.SubItems.Count; i++) { if (i == 1) //date { string date_time = item.SubItems[1].Text; string date = date_time.Substring(0, date_time.IndexOf(":") - 2).Trim(); date.Trim(); bool date_exist = false; for (int j = 0; j < send_date.Count; j++) { if (send_date[j].ToString() == date) { date_exist = true; iColumn = j + 1; } } if (!date_exist) { send_date.Add(date); iColumn = send_date.Count; } oSheet.Cells[1, iColumn] = date; } if (i == 2) //sender { name = item.SubItems[2].Text.ToString().Trim(); bool name_exist = false; for (int j = 0; j < send_name.Count; j++) { if (send_name[j].ToString() == name) { name_exist = true; iRow = j + 1; } } if (!name_exist) { send_name.Add(name); iRow = send_name.Count; } oSheet.Cells[iRow, 1] = name.Replace(" ", ""); } if (i == 4) //content { string content = item.SubItems[4].Text; if (content.Contains(name)) { content = content.Substring(0, content.IndexOf(name)); } if (content.Contains(name.Substring(0, 1) + " " + name.Substring(1))) { content = content.Substring(0, content.IndexOf(name.Substring(0, 1) + " " + name.Substring(1))); } string[] words = null; this.Invoke(new Action(delegate() { words = richTextBox1.Text.Split(';'); for (int index = 0; index < words.Count(); index++) { if (words[index] != "") { content = content.Replace(words[index], ""); } } })); string[] sentence = null; if (!content.Contains("\r\n") && content.Contains("\n")) { sentence = Regex.Split(content, "\n"); } else { sentence = Regex.Split(content, "\r\n"); } content = ""; foreach (string sen in sentence) { const string pattern = @"[~ ,,::.\.><]"; //删除数字和小数点,其他保留 Regex rx = new Regex(pattern); string result = rx.Replace(sen, ""); if (result != "") { content += sen.Trim() + "\r\n"; } } oSheet.Cells[iRow, iColumn] = content; } } } oXL.UserControl = true; } } catch (Exception theException) { String errorMessage; errorMessage = "Error: "; errorMessage = String.Concat(errorMessage, theException.Message); errorMessage = String.Concat(errorMessage, " Line: "); errorMessage = String.Concat(errorMessage, theException.Source); MessageBox.Show(errorMessage, "Error"); } timer1.Enabled = false; }