/// <summary> /// 从邮件中获取新的更新信息 /// </summary> protected void GetEmailUpdateInfo() { //获取邮件配置信息 FrameConfig FC = new FrameConfig(); string ConfigStr = FC.GetDetail("HostMail").ConfigValue; FrameCommon FComm = new FrameCommon(); string UserName = FComm.FindValueFromStr(ConfigStr, "UserName="******"Password="******"POP3Host=").Trim(); int Pop3Port = Convert.ToInt32(FComm.FindValueFromStr(ConfigStr, "POP3Port=").Trim()); bool IsSSL = FComm.FindValueFromStr(ConfigStr, "EnableSsl=").Trim() == "1" ? true : false; //连接邮件服务器 using (POP3_Client MyClient = new POP3_Client()) { MyClient.Connect(Pop3Host, Pop3Port, IsSSL); MyClient.Authenticate(UserName, Password, false); string SystemGuid = FComm.GetSystemGuid(); for (int i = 0; i < MyClient.Messages.Count; i++) { POP3_ClientMessage mail = MyClient.Messages[i]; Mime m = Mime.Parse(mail.MessageToByte()); if (m.Attachments.Length > 0 && m.MainEntity.Subject.ToLower().IndexOf(SystemGuid.ToLower()) > -1) //如果有附件,且为该系统的标识 { string UpdateSubject = m.MainEntity.Subject; DateTime UpdateTime = m.MainEntity.Date; string UpdateContent = m.BodyText; int FileCount = m.Attachments.Length; string UpdateGuid = System.Guid.NewGuid().ToString(); string FilePath = "/UpdateBackUp/" + UpdateTime.ToString("yyyyMMdd") + "-" + new System.Random().Next(1000, 9999).ToString() + "/"; //生成路径 string FilenameList = ""; //将基本信息存入数据库 foreach (MimeEntity entry in m.Attachments) { string fileName = entry.ContentDisposition_FileName; //获取文件名称 if (fileName != null && fileName.Trim() != "") //有些文件取不到,如txt { FilenameList = FilenameList + fileName + ";"; string DirPath = Server.MapPath(FilePath); System.IO.Directory.CreateDirectory(DirPath); string FileURL = DirPath + fileName; FileInfo fi = new FileInfo(FileURL); byte[] data = entry.Data; FileStream pFileStream = null; pFileStream = new FileStream(FileURL, FileMode.Create); pFileStream.Write(data, 0, data.Length); pFileStream.Close(); } } mail.MarkForDeletion(); new FrameUpdate().InsertUpdate(UpdateGuid, UpdateTime, UpdateSubject, UpdateContent, FileCount, FilenameList, FilePath); } } MyClient.Disconnect(); } this.Refresh(); }
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; }
/// <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.SessionLog += new LogEventHandler(clnt_SessionLog); clnt.LogCommands = LogCommands; clnt.Connect(server,port,useSSL); clnt.Authenticate(user,passw,false); POP3_MessagesInfo messagesInfo = clnt.GetMessagesInfo(); foreach(POP3_MessageInfo messageInfo in messagesInfo.Messages){ // Download message byte[] message = clnt.GetMessage(messageInfo.MessageNumber); // Store message m_pServer.ProcessUserMsg("","",userName,"Inbox",new MemoryStream(message),null); // Delete message clnt.DeleteMessage(messageInfo.MessageNumber); } } } catch{ } } } m_LastFetch = DateTime.Now; } catch(Exception x){ Error.DumpError(m_pServer.Name,x); } m_Fetching = false; }
public void display() { //需要首先设置这些信息 HyoaClass.Hyoa_mail_config Hyoa_mail_config = new HyoaClass.Hyoa_mail_config(); DataTable dtconfig = Hyoa_mail_config.Getmailconfigbyuserid(this.Session["hyuid"].ToString()); if (dtconfig.Rows.Count > 0) { string pop3Server = dtconfig.Rows[0]["hy_pop3url"].ToString();// "pop.163.com"; //邮箱服务器 如:"pop.sina.com.cn";或 "pop.qq.com" 好像sina的比较快 int pop3Port = System.Int32.Parse(dtconfig.Rows[0]["hy_pop3port"].ToString()); //110; //端口号码 用"110"好使。最好看一下你的邮箱服务器用的是什么端口号 bool pop3UseSsl = false; string lsmailid = dtconfig.Rows[0]["hy_mailid"].ToString(); string username = lsmailid.Substring(0, lsmailid.IndexOf("@"));//"ztmfang2008"; //你的邮箱用户名 string password = Decrypt(dtconfig.Rows[0]["hy_mailpwd"].ToString()); //"20120328"; //你的邮箱密码 List<string> gotEmailIds = new List<string>(); List<Mime> result = new List<Mime>(); using (POP3_Client pop3 = new POP3_Client()) { //与Pop3服务器建立连接 pop3.Connect(pop3Server, pop3Port, pop3UseSsl); //验证身份 pop3.Authenticate(username, password, false); //获取邮件信息列表 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); //this.Response.Write("<script>alert('" + info.UID + "');</script>"); //解析从Pop3服务器发送过来的邮件信息 Mime m = Mime.Parse(bytes); HyoaClass.Hyoa_global Hyoa_global = new HyoaClass.Hyoa_global(); HyoaClass.Hyoa_mail Hyoa_mail = new HyoaClass.Hyoa_mail(); HyoaClass.Hyoa_fileatt Hyoa_fileatt = new HyoaClass.Hyoa_fileatt(); //this.Response.Write("<script>alert('aaa');</script>"); string lsid = Hyoa_global.GetRandom(); string lsdocid = info.UID.ToString(); DataTable dtmail = Hyoa_mail.Getmailbydocid(lsdocid); if (dtmail.Rows.Count > 0) { } else { Hyoa_mail.ID = lsid; Hyoa_mail.DOCID = lsdocid; Hyoa_mail.hy_type = "收件"; Hyoa_mail.hy_foldername = "收件箱"; Hyoa_mail.hy_fsrid = m.MainEntity.From.ToAddressListString().ToString(); Hyoa_mail.hy_fsrname = m.MainEntity.From.ToAddressListString().ToString(); Hyoa_mail.hy_jsrid = this.Session["hyuid"].ToString(); Hyoa_mail.hy_wbjsrid = m.MainEntity.To.ToAddressListString().ToString(); Hyoa_mail.hy_jsrname = this.Session["hyuname"].ToString(); Hyoa_mail.hy_title = m.MainEntity.Subject.ToString(); Hyoa_mail.hy_body = m.BodyHtml.ToString(); Hyoa_mail.hy_datetime = m.MainEntity.Date.ToString(); Hyoa_mail.hy_ifsavetofjx = ""; Hyoa_mail.hy_yxj = ""; Hyoa_mail.hy_yjbg = ""; Hyoa_mail.hy_zycd = ""; Hyoa_mail.hy_hz = ""; Hyoa_mail.Insert(); //this.Response.Write("<script>alert('bbb');</script>"); //获取附件 foreach (MimeEntity entry in m.Attachments) { string lsfileattid = Hyoa_global.GetRandom(); string fileName = entry.ContentDisposition_FileName; //获取文件名称 string path = Server.MapPath("~\\fileatt\\" + lsfileattid); Directory.CreateDirectory(path); path += "\\" + fileName; if (File.Exists(path)) { Random random = new Random(); int newfile = random.Next(1, 100000); path = Server.MapPath("~\\fileatt\\" + lsfileattid + "\\" + 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(); //向附件表插入记录 Hyoa_fileatt.ID = lsfileattid; Hyoa_fileatt.hy_fatherid = lsdocid; Hyoa_fileatt.hy_filename = fileName; Hyoa_fileatt.hy_filepath = path.Substring(path.IndexOf("fileatt\\")); Hyoa_fileatt.hy_filesize = data.Length.ToString(); Hyoa_fileatt.hy_userid = this.Session["hyuid"].ToString(); Hyoa_fileatt.hy_djsj = m.MainEntity.Date.ToString(); Hyoa_fileatt.hy_fatherfield = ""; Hyoa_fileatt.Insert(); //this.Response.Write("<script>alert('ccc');</script>"); } } //Response.Write("<br>From:" + m.MainEntity.From.ToAddressListString()); //Response.Write("<br>To:" + m.MainEntity.To.ToAddressListString()); //Response.Write("<br>Time:" + m.MainEntity.Date); //发送时间 //Response.Write("<br>Subject:" + m.MainEntity.Subject); //主题 //Response.Write("<br>Plain Body:" + m.BodyText); //内容 //Response.Write("<br>Html Body:" + m.BodyHtml); //HTML格式内容 } this.Response.Write("<script>alert('邮件接收完成!');window.opener.location.reload();window.close();</script>"); } } else { this.Response.Write("<script>alert('请先配置外网邮件信息!');</script>"); } }
private void Server_AuthenticateUser(object sender,LumiSoft.Net.POP3.Server.AuthUser_EventArgs e) { try { e.Validated = m_pAPI.AuthUser(e.UserName,e.PasswData,e.AuthData,e.AuthType); if(e.Validated == false){ return; } //----- Remote pop3 servers ---------------------------------------// DataSet ds = m_pAPI.GetUserRemotePop3Servers(e.UserName); // Connect to external pop3 servers ArrayList extrnPop3Servers = new ArrayList(); foreach(DataRow dr in ds.Tables["RemotePop3Servers"].Rows){ try { string server = dr["Server"].ToString(); int port = Convert.ToInt32(dr["Port"]); string user = dr["UserName"].ToString(); string passw = dr["Password"].ToString(); POP3_Client clnt = new POP3_Client(); clnt.Connect(server,port); clnt.Authenticate(user,passw,false); extrnPop3Servers.Add(clnt); } catch(Exception x){ } } if(extrnPop3Servers.Count > 0){ e.Session.Tag = extrnPop3Servers; } //---------------------------------------------------------------------// } catch(Exception x) { e.Validated = false; Error.DumpError(x,new System.Diagnostics.StackTrace()); } }
/// <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.Authenticate(user,passw,false); 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; }