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 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); }
protected void BuildMessages() { // Only fetch messages when list is null because otherwise we would end up // downloading the mailbox headers twice, which can be quite annoying with large mailboxes if (messages == null) { messages = connection.Client.List(); } }
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); }
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> /// <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); }
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) { } } }
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)); } }
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 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("登陆失败"); } }