/// <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(); }
private void StartEmailDownload() { using (POP3_Client pop3 = new POP3_Client()) { pop3.Connect(this.qqEmailServer, 995, true); pop3.Login(this.emailAccount, this.password); POP3_ClientMessageCollection messages = pop3.Messages; Console.WriteLine("EmailCount:{0}", messages.Count); for (int i = 0; i < messages.Count; i++) { POP3_ClientMessage message = messages[i]; //转化为POP3 Console.WriteLine("\r\nChecking Email :{0} ...", i + 1); if (message != null) { byte[] messageBytes = message.MessageToByte(); Mail_Message mime_message = Mail_Message.ParseFromByte(messageBytes); string senderAddress = mime_message.From == null ? "<NULL>" : mime_message.From[0].Address; string subject = mime_message.Subject ?? "<NULL>"; Console.WriteLine(subject); DirectoryInfo dir = new DirectoryInfo(this.savePath); if (!dir.Exists) dir.Create(); MIME_Entity[] attachments = mime_message.GetAttachments(true); foreach (MIME_Entity entity in attachments) { if (entity.ContentDisposition != null) { string fileName = entity.ContentDisposition.Param_FileName; string extension = new FileInfo(fileName).Extension; if (!string.IsNullOrEmpty(fileName) && extension == ".pdf") { 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); } } } } } } } }
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> /// 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; }
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 override void init() { using (POP3_Client popClient = new POP3_Client()) { popClient.Connect(m_host, m_port); popClient.Login(m_user, m_pwd); foreach (POP3_ClientMessage message in popClient.Messages) { LumiSoft.Net.Mail.Mail_Message mime_header = LumiSoft.Net.Mail.Mail_Message.ParseFromByte(message.HeaderToByte()); if (mime_header != null && m_Filter(mime_header.Subject, null)) { m_htmlBody = mime_header.BodyHtmlText; return; } } } }
/// <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; }
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); } }