/// <summary> /// 接受邮件,处理所有正确存在邮件 /// </summary> public MailResult ReceiveMail(string asmName, string typeName, string methodName, bool delete, string stateText) { MailResult result = new MailResult(); result.StateText = stateText; string strPort = ""; if (strPort == "" || strPort == string.Empty) { strPort = "110"; } POPClient popClient = new POPClient(); try { popClient.Connect(PopServer, Convert.ToInt32(strPort)); popClient.Authenticate(UserName, Password); int count = popClient.GetMessageCount(); int resultCount = 0; for (int i = count; i >= 1; i--) { OpenPOP.MIMEParser.Message msg = popClient.GetMessage(i, false); if (msg != null) { resultCount++; //获取DLL所在路径: string dllPath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath; dllPath = Path.GetDirectoryName(dllPath); //依据所要执行类类型名,获取类实例: string asmNames = asmName;//程序集名称(*.dll) string dllFile = Path.Combine(dllPath, asmNames); Assembly asm = Assembly.LoadFrom(dllFile); //获取类方法并执行: object obj = asm.CreateInstance(typeName, false); Type type = obj.GetType(); //类名 MethodInfo method = type.GetMethod(methodName); //方法名称 //如果需要参数则依此行 object[] args = new object[] { (object)msg, (object)result }; //执行并调用方法 method.Invoke(obj, args); if (delete) { popClient.DeleteMessage(i); //邮件保存成功,删除服务器备份 } } } result.Count = resultCount; } catch (Exception ex) { throw ex; } finally { popClient.Disconnect(); } return(result); }
//public static MyEvents loggerEvents = new MyEvents(); //private void Log(string log) //{ // //EventsArgs args = new EventsArgs(log); // //loggerEvents.LogText(args); //} public string EmailVerification(string Email, string Password, out bool IsLogin) { string Host = string.Empty; string InviteUrl = string.Empty; int Port = 0; MailAddress address = new MailAddress(Uri.UnescapeDataString(Email)); string EmailHostName = address.Host.ToLower(); HostDetails HD = EmailHost.GetHostDetails(EmailHostName); Host = HD.Host; Port = HD.Port; if (!string.IsNullOrEmpty(Host)) { if (popClient.Connected) { popClient.Disconnect(); } popClient.Connect(Host, Port, true); popClient.Authenticate(Uri.UnescapeDataString(Email), Password.Trim(), AuthenticationMethod.USERPASS); int Count = popClient.GetMessageCount(); IsLogin = true; for (int i = Count; i >= 1; i--) { OpenPOP.MIME.Message Message = popClient.GetMessage(i); string subject = string.Empty; subject = Message.Headers.Subject; bool contains = subject.IndexOf("Please activate your new Gumtree account", StringComparison.OrdinalIgnoreCase) >= 0; if (contains) { if (string.IsNullOrEmpty(InviteUrl)) { InviteUrl = GetInviteUrlFromString(Message.RawMessageBody); break; } else { break; } } } } else { IsLogin = false; } return(InviteUrl); }
private void backgroundWorkerGetAllMails_DoWork(object sender, DoWorkEventArgs e) { Utility.Log = true; popClient.Disconnect(); popClient.Connect(config.ServerAddr, int.Parse(config.Port)); popClient.Authenticate(config.Email, config.PWD); int Count = popClient.GetMessageCount(); int percent = 0; backgroundWorkerGetAllMails.ReportProgress(-1, Count); List <ApplyItem> list = new List <ApplyItem>(); for (int i = Count; i > 0; i--) { OpenPOP.MIMEParser.Message m = popClient.GetMessage(i, false); ApplyItem item = ApplyItemController.getApplyItem(m); percent = percent + 1; if (item != null) { list.Add(item); } backgroundWorkerGetAllMails.ReportProgress((int)percent * 100 / Count, item); } for (int k = 0; k < list.Count; k++) { } String path = Application.StartupPath + "\\Excel\\" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".xls"; ExcelCreator ec = new ExcelCreator(); if (ec.toExcel(list, path)) { e.Result = "path:" + path; } else { e.Result = "ER:生成excel失败"; } }
public List <SharpMessage> GetPage( int pageNumber, int pageSize, out int totalPages) { totalPages = 1; List <SharpMessage> inboxMessages = new List <SharpMessage>(); mailClient.Disconnect(); mailClient.UseSSL = this.useSSL; mailClient.Connect(this.popServerName, this.popServerPort); mailClient.Authenticate( this.userName, this.password, AuthenticationMethod.TRYBOTH); int totalMessages = mailClient.GetMessageCount(); if (pageSize > 0) { totalPages = totalMessages / pageSize; } if (totalMessages <= pageSize) { totalPages = 1; } else { int remainder; Math.DivRem(totalMessages, pageSize, out remainder); if (remainder > 0) { totalPages += 1; } } int lastMessageToGet; if (pageNumber == 1) { lastMessageToGet = totalMessages; } else { lastMessageToGet = totalMessages - (pageSize * pageNumber); } int firstMessageToGet = lastMessageToGet - pageSize; for (int i = lastMessageToGet; i >= firstMessageToGet; i -= 1) { SharpMessage message = mailClient.GetMessage(i, false); if (message != null) { inboxMessages.Add(message); } //message. } mailClient.Disconnect(); return(inboxMessages); }
//receive email from POP3 server public void ReceivePop3Mail() { POPClient popClient = new POPClient(); //new POP client to grab emails Hashtable msgs = new Hashtable(); //stores the email messages // receive emails try { popClient.Disconnect(); //housekeeping //connect to pop mail server and authenticate popClient.Connect("pop.gmail.com", 995, true); popClient.Authenticate("*****@*****.**", "sd1ma2sn3"); int Count = popClient.GetMessageCount(); //number of emails in the inbox msgs.Clear(); //clear out the message hashtable //iterate through messages for (int i = Count; i >= 0; i -= 1) { try { OpenPOP.MIMEParser.Message m = popClient.GetMessage(i, false);//grab a message and its header info if (m != null) { if (m.FromEmail == "*****@*****.**") { msgs.Add("msg" + i.ToString(), m);//put the message in the hashtable string htmlbody = m.MessageBody[0].ToString(); int starting_tag = 0, ending_tag = 0, ID = -1; starting_tag = htmlbody.IndexOf("תאריך ושעה"); ending_tag = htmlbody.IndexOf("לפרטים נוספים"); htmlbody = htmlbody.Substring(starting_tag, ending_tag - starting_tag + 1); htmlbody = htmlbody.Replace("\n", ""); htmlbody = htmlbody.Replace("\t", ""); DateTime date = DateTime.Parse(htmlbody.Substring(htmlbody.IndexOf("תאריך ושעה") + 12, htmlbody.IndexOf("<br>") - htmlbody.IndexOf("תאריך ושעה") - 12)); htmlbody = htmlbody.Remove(htmlbody.IndexOf("תאריך ושעה"), htmlbody.IndexOf("<br>") - htmlbody.IndexOf("תאריך ושעה") + 4); string name = htmlbody.Substring(htmlbody.IndexOf("שם הלקוח המעביר") + 17, htmlbody.IndexOf("<br>") - htmlbody.IndexOf("שם הלקוח המעביר") - 17); htmlbody = htmlbody.Remove(htmlbody.IndexOf("שם הלקוח המעביר"), htmlbody.IndexOf("<br>") - htmlbody.IndexOf("שם הלקוח המעביר") + 4); double amount = double.Parse(htmlbody.Substring(htmlbody.IndexOf("סכום") + 6, htmlbody.IndexOf("<br>") - htmlbody.IndexOf("סכום") - 6)); htmlbody = htmlbody.Remove(htmlbody.IndexOf("סכום"), htmlbody.IndexOf("<br>") - htmlbody.IndexOf("סכום") + 4); string payment_id = htmlbody.Substring(htmlbody.IndexOf("מספר פעולה") + 12, htmlbody.IndexOf("<br>") - htmlbody.IndexOf("מספר פעולה") - 12); //updateing DB ADO.ExecuteNonQuery("Insert INTO Payments (Full_name, Amount, buying_date, Payment_ID) values ('" + name + "'," + amount + ",'" + date + "','" + payment_id + "')"); } } else { } } catch (Exception ex) { } } } catch (Exception x) { } popClient.Disconnect(); }
public static List <PhotoData> GetPhotoData(bool deleteMessages) { var imagesData = new List <PhotoData>(); OpenPOP.POP3.POPClient client = new POPClient("mail.shockbyte.com.ar", 110, "*****@*****.**", "Password11", AuthenticationMethod.USERPASS); Console.WriteLine("Connected"); var count = client.GetMessageCount( ); Console.WriteLine("Message Count: " + count); for (int i = 1; i <= count; i++) { Console.WriteLine("Message"); var message = client.GetMessage(i, false); foreach (Attachment att in message.Attachments) { Console.WriteLine("Att: " + att.ContentFileName); var extPos = att.ContentFileName.LastIndexOf("."); if (extPos >= 0) { var ext = att.ContentFileName.Substring(extPos + 1).ToLowerInvariant( ); var photo = new PhotoData( ) { Data = att.DecodedAsBytes( ), From = message.From, Title = message.Subject, FileName = att.ContentFileName }; switch (ext) { case "jpg": case "jpeg": photo.ImageType = "image/jpeg"; imagesData.Add(photo); break; case "gif": photo.ImageType = "image/gif"; imagesData.Add(photo); break; case "png": photo.ImageType = "image/png"; imagesData.Add(photo); break; } } } } if (deleteMessages) { client.DeleteAllMessages( ); } client.Disconnect( ); return(imagesData); }
public bool EmailVerification(string Email, string Password, ref GlobusHttpHelper globushttpHelper) { bool IsActivated = false; try { Log("[ " + DateTime.Now + " ] => [ Please Wait Account Verification Start... ]"); System.Windows.Forms.Application.DoEvents(); Chilkat.Http http = new Chilkat.Http(); if (Email.Contains("@yahoo")) { #region Yahoo Verification Steps GlobusHttpHelper HttpHelper = new GlobusHttpHelper(); bool activate = false; try { bool emaildata = false; //Chilkat.Http http = new Chilkat.Http(); ///Chilkat Http Request to be used in Http Post... Chilkat.HttpRequest req = new Chilkat.HttpRequest(); bool success; // Any string unlocks the component for the 1st 30-days. success = http.UnlockComponent("THEBACHttp_b3C9o9QvZQ06"); if (success != true) { Console.WriteLine(http.LastErrorText); return(false); } http.CookieDir = "memory"; http.SendCookies = true; http.SaveCookies = true; //http.ProxyDomain = "127.0.0.1"; //http.ProxyPort = 8888; http.SetRequestHeader("Accept-Encoding", "gzip,deflate"); Chilkat.Imap iMap = new Imap(); string Username = Email; iMap.UnlockComponent("THEBACIMAPMAILQ_OtWKOHoF1R0Q"); //iMap. //iMap.HttpProxyHostname = "127.0.0.1"; //iMap.HttpProxyPort = 8888; iMap.Port = 993; iMap.Connect("imap.n.mail.yahoo.com"); iMap.Login(Email, Password); iMap.SelectMailbox("Inbox"); // Get a message set containing all the message IDs // in the selected mailbox. Chilkat.MessageSet msgSet; //msgSet = iMap.Search("FROM \"facebookmail.com\"", true); msgSet = iMap.GetAllUids(); if (msgSet.Count <= 0) { msgSet = iMap.GetAllUids(); } // Fetch all the mail into a bundle object. Chilkat.Email email = new Chilkat.Email(); //bundle = iMap.FetchBundle(msgSet); string strEmail = string.Empty; List <string> lstData = new List <string>(); if (msgSet != null) { for (int i = 0; i < msgSet.Count; i++) { try { email = iMap.FetchSingle(msgSet.GetId(i), true); strEmail = email.Subject; string emailHtml = email.GetHtmlBody(); lstData.Add(strEmail); string from = email.From.ToString().ToLower(); if (from.Contains("@linkedin.com")) { foreach (string href in GetUrlsFromString(email.Body)) { try { if (href.Contains("http://www.linkedin.com/e/csrf") || href.Contains("http://www.linkedin.com/e/ato") || href.Contains("http://www.linkedin.com/e/v2?e")) { string EscapeEmail = Uri.EscapeDataString(Email).Replace(".", "%2E").Trim(); { string ConfirmationResponse = globushttpHelper.getHtmlfromUrl1(new Uri(href)); IsActivated = true; break; } } } catch (Exception ex) { Console.WriteLine("6 :" + ex.StackTrace); } } } if (IsActivated) { Log("[ " + DateTime.Now + " ] => [ Account : " + Email + " verified ]"); break; } } catch (Exception ex) { Console.WriteLine("Error >>> " + ex.StackTrace); } } } } catch (Exception ex) { Console.WriteLine("7 :" + ex.StackTrace); Log("[ " + DateTime.Now + " ] => [ Email Verification Exception : " + ex.Message + "StackTrace --> >>>" + ex.StackTrace + " with : " + Email + " ]"); Log("[ " + DateTime.Now + " ] => [ Please check your Login Id and Password ]"); } return(IsActivated); #endregion } else { string Host = string.Empty; int Port = 0; if (Email.Contains("@gmail")) { Host = "pop.gmail.com"; Port = 995; } else if (Email.Contains("@hotmail")) { Host = "pop3.live.com"; Port = 995; } else if (Email.Contains("@gmx")) { Host = "pop.gmx.com"; Port = 995; } if (!string.IsNullOrEmpty(Host)) { try { if (popClient.Connected) { popClient.Disconnect(); } popClient.Connect(Host, Port, true); popClient.Authenticate(Email, Password); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); //retry once System.Threading.Thread.Sleep(1000); if (popClient.Connected) { popClient.Disconnect(); } popClient.Connect(Host, Port, true); popClient.Authenticate(Email, Password); } //if (!) //{ //} int Count = popClient.GetMessageCount(); for (int i = Count; i >= 1; i--) { try { OpenPOP.MIME.Message Message = popClient.GetMessage(i); string subject = string.Empty; subject = Message.Headers.Subject; string frowwm = Message.Headers.From.ToString(); bool GoIntoEmail = false; if (string.IsNullOrEmpty(subject)) { string from = Message.Headers.From.ToString().ToLower(); if (from.Contains("linkedin.com")) { GoIntoEmail = true; } } try { if (frowwm.Contains("linkedin.com")) //if(GoIntoEmail) { string Messagebody = Message.MessageBody[0]; foreach (string href in GetUrlsFromStringGmail(Messagebody)) { try { if (href.Contains("http://www.linkedin.com/e/csrf") || href.Contains("http://www.linkedin.com/e/ato") || href.Contains("http://www.linkedin.com/e/v2?e")) { string href1 = href.Replace("amp;", string.Empty); string EscapeEmail = Uri.EscapeDataString(Email).Replace(".", "%2E").Trim(); { string ConfirmationResponse = globushttpHelper.getHtmlfromUrl1(new Uri(href1)); IsActivated = true; break; } } } catch (Exception ex) { Console.WriteLine("5 :" + ex.StackTrace); }; } } } catch (Exception ex) { Console.WriteLine("10 :" + ex.StackTrace); Log("[ " + DateTime.Now + " ] => [ Email Verification Exception : " + ex.Message + "StackTrace --> >>>" + ex.StackTrace + " with : " + Email + " ]"); } if (IsActivated) { break; } } catch (Exception ex) { { Log("[ " + DateTime.Now + " ] => [ Email Verification Exception : " + ex.Message + "StackTrace --> >>>" + ex.StackTrace + " with : " + Email + " ]"); Log("[ " + DateTime.Now + " ] => [ Please check your Login Id and Password ]"); } } } } } return(IsActivated); } catch (Exception ex) { Console.WriteLine("4 :" + ex.StackTrace); return(IsActivated); } }
/// <summary> /// Download email messages from the POP3 server for a given Foe message processor. /// </summary> /// <param name="server">POP3 server information</param> /// <param name="processorEmail">The current Foe message processor's email address.</param> public static void DownloadMessages(PopServer server, string processorEmail) { // connect to POP3 server and download messages //FoeDebug.Print("Connecting to POP3 server..."); POPClient popClient = new POPClient(); popClient.IsUsingSsl = server.SslEnabled; popClient.Disconnect(); popClient.Connect(server.ServerName, server.Port); popClient.Authenticate(server.UserName, server.Password); FoeDebug.Print("Connected to POP3."); // get mail count int count = popClient.GetMessageCount(); FoeDebug.Print("Server reported " + count.ToString() + " messages."); // go through each message, from newest to oldest for (int i = count; i >= 1; i -= 1) { //FoeDebug.Print("Opening mail message..."); OpenPOP.MIMEParser.Message msg = popClient.GetMessage(i, true); if (msg != null) { // Get subject and verify sender identity // Subject line in the mail header should look like one of the followings: // // Normal request (for news feed and content): // Subject: Request <Request ID> by <User ID> // // Registration request: // Subject: Register <Request ID> by Newbie // // where: // Request ID is the request ID generated by the Foe client // User ID is the user's ID as assigned by the server //FoeDebug.Print("Message is not null. Getting message details."); string subject = msg.Subject; string fromEmail = msg.FromEmail; //FoeDebug.Print("Subject: " + subject); //FoeDebug.Print("From: " + fromEmail); // parse subject line string[] tokens = subject.Trim().Split(new char[] { ' ' }); if (tokens.Length == 4) { // check what type of request is it string requestType = tokens[0].ToUpper(); string requestId = tokens[1]; string userId = tokens[3]; FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message, "subject: " + subject + "requestType: " + requestType); if (requestType.ToUpper().CompareTo("REGISTE") == 0) { //FoeDebug.Print("This is a registration message."); // It's a registration request SaveRegistrationRequest(requestId, fromEmail, processorEmail); FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message, "Received registration request from " + fromEmail); } else if (requestType.ToUpper().CompareTo("CATALOG") == 0) { // get user info by email address FoeUser user = FoeServerUser.GetUser(fromEmail); // verify user's email against the user ID if ((user != null) && (userId == user.UserId) && (processorEmail == user.ProcessorEmail)) { FoeDebug.Print("User verified."); // the user's identity is verified SaveCatalogRequest(requestId, user.Email, processorEmail); } else { //FoeDebug.Print("User is not registered. Request not processed."); FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning, "Received content request from unregistered user " + fromEmail); } } else if (requestType.ToUpper().CompareTo("CONTENT") == 0) { //FoeDebug.Print("This is a content request message."); // It's a content request. // We need to verify the user's identify first. //FoeDebug.Print("Verifying user identity..."); // get user info by email address FoeUser user = FoeServerUser.GetUser(fromEmail); // verify user's email against the user ID if ((user != null) && (userId == user.UserId) && (processorEmail == user.ProcessorEmail)) { FoeDebug.Print("User verified."); // the user's identity is verified // get the full message body OpenPOP.MIMEParser.Message wholeMsg = popClient.GetMessage(i, false); string msgBody = (string)wholeMsg.MessageBody[0]; try { // decompress it byte[] compressedMsg = Convert.FromBase64String(msgBody); byte[] decompressedMsg = CompressionManager.Decompress(compressedMsg); string foe = Encoding.UTF8.GetString(decompressedMsg); string[] catalogs = foe.Trim().Split(new char[] { ',' }); // save request if (catalogs.Length == 0) { return; } SaveContentRequest(requestId, user.Email, catalogs, processorEmail); //FoeDebug.Print("Request saved and pending processing."); FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message, "Received content request from verified user " + fromEmail); } catch (Exception except) { // the message is likely malformed // so just ignore it FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning, "Received malformed content request from verified user " + fromEmail + "\r\n" + except.ToString() + "Raw message:\r\n" + msgBody + "\r\n"); //throw except; } } else { //FoeDebug.Print("User is not registered. Request not processed."); FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning, "Received content request from unregistered user " + fromEmail); } } else if (requestType.ToUpper().CompareTo("FEED") == 0) { //FoeDebug.Print("This is a content request message."); // It's a content request. // We need to verify the user's identify first. //FoeDebug.Print("Verifying user identity..."); // get user info by email address FoeUser user = FoeServerUser.GetUser(fromEmail); // verify user's email against the user ID if ((user != null) && (userId == user.UserId) && (processorEmail == user.ProcessorEmail)) { FoeDebug.Print("User verified."); // the user's identity is verified // get the full message body OpenPOP.MIMEParser.Message wholeMsg = popClient.GetMessage(i, false); string msgBody = (string)wholeMsg.MessageBody[0]; try { // decompress it byte[] compressedMsg = Convert.FromBase64String(msgBody); byte[] decompressedMsg = CompressionManager.Decompress(compressedMsg); string foe = Encoding.UTF8.GetString(decompressedMsg); string[] array = foe.Trim().Split(new char[] { ',' }); // save request if (array.Length == 0) { return; } SaveFeedRequest(requestId, user.Email, array, processorEmail); //FoeDebug.Print("Request saved and pending processing."); FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message, "Received feed request from verified user " + fromEmail); } catch (Exception except) { // the message is likely malformed // so just ignore it FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning, "Received malformed feed request from verified user " + fromEmail + "\r\n" + except.ToString() + "Raw message:\r\n" + msgBody + "\r\n"); //throw except; } } else { //FoeDebug.Print("User is not registered. Request not processed."); FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Warning, "Received content request from unregistered user " + fromEmail); } } else { // Non-Foe message FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message, "Received non-Foe message from " + fromEmail); } } else { // Non-Foe message FoeServerLog.Add(_className + ".DownloadMessages", FoeServerLog.LogType.Message, "Received non-Foe message from " + fromEmail); } // Delete the current message popClient.DeleteMessage(i); } } popClient.Disconnect(); }
/// <summary> /// Download and process email messages from the POP3 server. /// </summary> /// <param name="server">POP3 server information</param> public static void DownloadMessages() { Trace.WriteLine("Entered DownloadMessages()."); // Get POP3 server info PopServer server = GetPopServer(); Trace.WriteLine(" Retrieved POP server info."); // connect to POP3 server and download messages //FoeDebug.Print("Connecting to POP3 server..."); POPClient popClient = new POPClient(); popClient.IsUsingSsl = server.SslEnabled; popClient.Disconnect(); popClient.Connect(server.ServerName, server.Port); popClient.Authenticate(server.UserName, server.Password); Trace.WriteLine(" Connected to POP3."); // get mail count int count = popClient.GetMessageCount(); Trace.WriteLine(" There are " + count.ToString() + " messages in inbox."); // go through each message, from newest to oldest for (int i = count; i >= 1; i -= 1) { Trace.WriteLine(" Opening message #" + i.ToString()); OpenPOP.MIMEParser.Message msg = popClient.GetMessage(i, true); if (msg != null) { string subject = msg.Subject; string fromEmail = msg.FromEmail; Trace.WriteLine(" Message came from " + msg.FromEmail + " with subject \"" + msg.Subject + "\""); // Check if fromEmail is the same as processor's email on file if (fromEmail.ToLower() == FoeClientRegistry.GetEntry("processoremail").Value.ToLower()) { Trace.WriteLine(" Message came from the processor."); // parse subject line string[] tokens = subject.Trim().Split(new char[] { ' ' }); // There should be 5 or 6 tokens if (tokens.Length == 5) { Trace.WriteLine(" There are 5 tokens."); // Get the request ID for this reply string requestId = tokens[2]; // Check if request ID matches any request the client sent FoeClientRequestItem req = FoeClientRequest.Get(requestId); if (req != null) { Trace.WriteLine(" Message Request ID matched."); // Found the matching request // Download the full reply OpenPOP.MIMEParser.Message wholeMsg = popClient.GetMessage(i, false); string msgBody = (string)wholeMsg.MessageBody[0]; Trace.WriteLine(" Downloaded full message body."); try { // decompress it byte[] compressedMsg = Convert.FromBase64String(msgBody); Trace.WriteLine(" Decoded Base64 message."); byte[] decompressedMsg = CompressionManager.Decompress(compressedMsg); Trace.WriteLine(" Decompressed message."); string foe = Encoding.UTF8.GetString(decompressedMsg); Trace.WriteLine(" Retrieved original FOE message."); // Check what is the original request type if (req.Type.ToLower() == "registe") { Trace.WriteLine(" Registration reply. Processing message."); ProcessRegistrationReply(foe); Trace.WriteLine(" Registration reply processed."); } else if (req.Type.ToLower() == "catalog") { Trace.WriteLine(" Catalog reply. Processing message."); ProcessCatalogReply(foe); Trace.WriteLine(" Catalog reply processed."); } else if (req.Type.ToLower() == "feed") { Trace.WriteLine(" feed reply. Processing message."); ProcessCatalogReply(foe); Trace.WriteLine(" feed reply processed."); } } catch (Exception except) { // the message is likely malformed // so just ignore it Trace.WriteLine(" Exception detected: \r\n" + except.ToString()); } } else { Trace.WriteLine(" Message ID mismatched."); } } //content request's reply else if (tokens.Length == 6) { Trace.WriteLine(" There are 6 tokens."); // Get the request ID for this reply string catalog = tokens[1]; string requestId = tokens[3]; // Check if request ID matches any request the client sent FoeClientRequestItem req = FoeClientRequest.Get(requestId); if (req != null) { Trace.WriteLine(" Message Request ID matched."); // Found the matching request // Download the full reply OpenPOP.MIMEParser.Message wholeMsg = popClient.GetMessage(i, false); string msgBody = (string)wholeMsg.MessageBody[0]; Trace.WriteLine(" Downloaded full message body."); try { byte[] compressed = Convert.FromBase64String(msgBody); byte[] decompressed = CompressionManager.Decompress(compressed); string foe = Encoding.UTF8.GetString(decompressed); // Check what is the original request type if (req.Type.ToLower() == "content") { Trace.WriteLine(" Content reply. Processing message."); ProcessContentReply(catalog, foe); Trace.WriteLine(" Content reply processed."); } } catch (Exception except) { // the message is likely malformed // so just ignore it Trace.WriteLine(" Exception detected: \r\n" + except.ToString()); } } else { Trace.WriteLine(" Message ID mismatched."); } } else { Trace.WriteLine(" Message does not have 5 tokens."); } } else { Trace.WriteLine(" Message did not come from processor."); } } // Delete the current message popClient.DeleteMessage(i); Trace.WriteLine(" Deleted current message in inbox."); } popClient.Disconnect(); Trace.WriteLine(" Disconnected from POP server."); Trace.WriteLine(" Exiting DownloadMessages()."); }
private void HandleClientComm(object client) { var client = new POPClient(); client.Connect("pop.gmail.com", 995, true); client.Authenticate("*****@*****.**", "YourPasswordHere"); var count = client.GetMessageCount(); Message message = client.GetMessage(count); Console.WriteLine(message.Headers.Subject); TcpClient tcpClient = (TcpClient)client; NetworkStream clientStream = tcpClient.GetStream(); IPAddress ipOfClient = IPAddress.Parse(((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString()); Console.WriteLine(ipOfClient + " has connected..."); ASCIIEncoding encoder = new ASCIIEncoding(); byte[] buffer; byte[] message = new byte[4096]; int bytesRead; while (true) { bytesRead = 0; try { bytesRead = clientStream.Read(message, 0, 4096); } catch { break; } if (bytesRead == 0) { Console.WriteLine(ipOfClient + " has disconnected..."); break; } Console.Write("Message received from - " + ipOfClient + " : "); string incomingMsg = encoder.GetString(message, 0, bytesRead); Console.WriteLine(incomingMsg); if (incomingMsg == "List") { buffer = encoder.GetBytes("Currently connected are: "); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); buffer = null; foreach (TcpClient c in clients) { IPAddress cliIP = IPAddress.Parse(((IPEndPoint)c.Client.RemoteEndPoint).Address.ToString()); buffer = encoder.GetBytes(cliIP.ToString()); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); buffer = null; } } else { buffer = encoder.GetBytes("Hello Client!"); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); buffer = null; } } clients.Remove(client); tcpClient.Close(); }
public void Execute(XmlNode node) { if (node.Attributes == null) { return; } XmlAttribute server = node.Attributes["Server"]; XmlAttribute port = node.Attributes["Port"]; XmlAttribute username = node.Attributes["Username"]; XmlAttribute password = node.Attributes["Password"]; XmlAttribute connectionStringName = node.Attributes["ConnectionStringName"]; var popClient = new POPClient(); popClient.Connect(server.Value, int.Parse(port.Value), false); popClient.Authenticate(username.Value, password.Value); int count = popClient.GetMessageCount(); if (count <= 0) { popClient.Disconnect(); using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionStringName.Value].ConnectionString)) { connection.Open(); List <Product> productsFromBase = GetRelatedProductsFromBase(connection); List <Product> allHouseFlowers = GetFlowers(connection); foreach (var product in allHouseFlowers) { string diam = GetDiametr(product.ShortDescription); int diametr; if (Int32.TryParse(diam, out diametr)) { List <Product> neededRelatedProducts = GetNeededRelatedProducts(productsFromBase, diametr); List <Product> existingRelatedProducts = GetExistingRelatedProducts(connection, product.Id); foreach (var p in existingRelatedProducts) { neededRelatedProducts.RemoveAll(x => (x.Id == p.Id)); } UpdateRelatedProducts(connection, neededRelatedProducts, product); } } } return; } for (int i = count; i >= 1; i -= 1) { using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionStringName.Value].ConnectionString)) { connection.Open(); Message message = popClient.GetMessage(i); string[] rows = message.MessageBody[0].Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (string row in rows) { try { string[] cols = row.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries); if (cols[2].Contains(".")) { continue; } string sku = cols[0]; decimal price = decimal.Parse(cols[1]); int quantity = int.Parse(cols[2]); using (var command = new SqlCommand(UpdateProductVariantQuery, connection)) { command.Parameters.Add(new SqlParameter("@Sku", sku)); command.Parameters.Add(new SqlParameter("@Price", price)); command.Parameters.Add(new SqlParameter("@StockQuantity", quantity)); command.ExecuteNonQuery(); } if (cols.Length == 5) { int height; int diameter; bool heightParsed = int.TryParse(cols[3], out height); bool diameterParsed = int.TryParse(cols[4], out diameter); using (var command = new SqlCommand(UpdateProductVariantQuery, connection)) { command.Parameters.Add(new SqlParameter("@Sku", sku)); Product product = null; int saoHeightId = 0; if (heightParsed && height != 0) { product = GetProduct(connection, sku); if (height < 11) { saoHeightId = 54; } else if (height >= 11 && height < 16) { saoHeightId = 55; } else if (height >= 16 && height < 21) { saoHeightId = 56; } else if (height >= 21 && height < 26) { saoHeightId = 57; } else if (height >= 26 && height < 31) { saoHeightId = 58; } else if (height >= 31 && height < 50) { saoHeightId = 64; } else if (height >= 50) { saoHeightId = 60; } if (product != null && !SaoExists(connection, product.Id, saoHeightId)) { InsertSao(connection, product.Id, saoHeightId); } } int saoDiameterId = 0; if (diameterParsed && diameter != 0) { if (product == null) { product = GetProduct(connection, sku); } if (diameter < 11) { saoDiameterId = 16; } else if (diameter >= 11 && diameter < 16) { saoDiameterId = 18; } else if (diameter >= 16 && diameter < 21) { saoDiameterId = 48; } else if (diameter >= 21 && diameter < 26) { saoDiameterId = 49; } else if (diameter >= 26 && diameter < 31) { saoDiameterId = 50; } else if (diameter >= 31 && diameter < 50) { saoDiameterId = 51; } else if (diameter >= 50) { saoDiameterId = 52; } if (product != null && !SaoExists(connection, product.Id, saoDiameterId)) { InsertSao(connection, product.Id, saoDiameterId); } } if (product != null) { string oldShortDescription = product.ShortDescription; string oldFullDescription = product.FullDescription; if (diameterParsed && heightParsed) { if (!product.ShortDescription.ToLower().Contains("(см)")) { product.ShortDescription += (product.ShortDescription == string.Empty ? "" : "<br />") + string.Format("{0}X{1}(см)", height, diameter); } if (!product.FullDescription.ToLower().Contains("высота")) { product.FullDescription += (product.FullDescription == string.Empty ? "" : "<br />") + string.Format("Высота - {0} см", height); } if (!product.FullDescription.ToLower().Contains("диаметр")) { product.FullDescription += (product.FullDescription == string.Empty ? "" : "<br />") + string.Format("Диаметр - {0} см", diameter); } } else if (heightParsed) { if (!product.ShortDescription.Contains(string.Format("{0}X-(см)", height))) { product.ShortDescription += (product.ShortDescription == string.Empty ? "" : "<br />") + string.Format("{0}X-(см)", height); } if (!product.FullDescription.ToLower().Contains("высота")) { product.FullDescription += (product.FullDescription == string.Empty ? "" : "<br />") + string.Format("Высота - {0} см", height); } } else if (diameterParsed) { if (!product.ShortDescription.Contains(string.Format("-X{0}(см)", diameter))) { product.ShortDescription += (product.ShortDescription == string.Empty ? "" : "<br />") + string.Format("-X{0}(см)", diameter); } if (!product.FullDescription.ToLower().Contains("диаметр")) { product.FullDescription += (product.FullDescription == string.Empty ? "" : "<br />") + string.Format("Диаметр - {0} см", diameter); } } if (oldShortDescription != product.ShortDescription || oldFullDescription != product.FullDescription) { UpdateProduct(connection, product); } } } } } catch (Exception exc) { LogManager.InsertLog(LogTypeEnum.AdministrationArea, string.Format("Error while sync with 1C. The line is '{0}'.", row), exc); } } } popClient.DeleteMessage(i); popClient.Disconnect(); } NopCache.Clear(); }
public bool EmailVerification(string Email, string Password, ref GlobusHttpHelper globushttpHelper) { bool IsActivated = false; try { System.Windows.Forms.Application.DoEvents(); Chilkat.Http http = new Chilkat.Http(); if (Email.Contains("+")) { String[] emaildata = Email.Split('+'); Email = (emaildata[0] + "@" + emaildata[1].Split('@')[1]).Trim(); } if (Email.Contains("@yahoo")) { #region Yahoo Verification Steps GlobusHttpHelper HttpHelper = new GlobusHttpHelper(); bool activate = false; try { bool emaildata = false; //Chilkat.Http http = new Chilkat.Http(); ///Chilkat Http Request to be used in Http Post... Chilkat.HttpRequest req = new Chilkat.HttpRequest(); bool success; // Any string unlocks the component for the 1st 30-days. success = http.UnlockComponent("THEBACHttp_b3C9o9QvZQ06"); if (success != true) { Console.WriteLine(http.LastErrorText); return(false); } http.CookieDir = "memory"; http.SendCookies = true; http.SaveCookies = true; //http.IPDomain = "127.0.0.1"; //http.IPPort = 8888; http.SetRequestHeader("Accept-Encoding", "gzip,deflate"); Chilkat.Imap iMap = new Imap(); string Username = Email; iMap.UnlockComponent("THEBACIMAPMAILQ_OtWKOHoF1R0Q"); //iMap. //iMap.HttpIPHostname = "127.0.0.1"; //iMap.HttpIPPort = 8888; iMap.Port = 993; iMap.Connect("imap.n.mail.yahoo.com"); iMap.Login(Email, Password); iMap.SelectMailbox("Inbox"); // Get a message set containing all the message IDs // in the selected mailbox. Chilkat.MessageSet msgSet; //msgSet = iMap.Search("FROM \"facebookmail.com\"", true); msgSet = iMap.GetAllUids(); if (msgSet.Count <= 0) { msgSet = iMap.GetAllUids(); } // Fetch all the mail into a bundle object. Chilkat.Email email = new Chilkat.Email(); //bundle = iMap.FetchBundle(msgSet); string strEmail = string.Empty; List <string> lstData = new List <string>(); if (msgSet != null) { for (int i = msgSet.Count; i > 0; i--) //for (int i = 0; i < msgSet.Count; i++) { try { email = iMap.FetchSingle(msgSet.GetId(i), true); strEmail = email.Subject; string emailHtml = email.GetHtmlBody(); lstData.Add(strEmail); string from = email.From.ToString().ToLower(); if (from.Contains("twitter.com") || from.Contains("account-verification")) { #region <old User Parser //foreach (string href in GetUrlsFromString(email.Body)) //{ // try // { // if (href.Contains("https://twitter.com/account/confirm_email/") ) // { // string ConfirmationResponse = globushttpHelper.getHtmlfromUrl(new Uri(href), "", ""); // IsActivated = true; // } // } // catch (Exception ex) // { // Console.WriteLine("6 :" + ex.StackTrace); // } //} #endregion string[] arr = Regex.Split(email.Body, "href"); foreach (string strhref in arr) { if (!strhref.Contains("<!DOCTYPE")) { if (strhref.Contains("https://twitter.com/account/confirm_email")) { string AncherTag = System.Text.RegularExpressions.Regex.Split(strhref, ">")[1]; string tempString = AncherTag.Substring(AncherTag.IndexOf("https")); string DataUrl = tempString.Replace("<>", "").Replace(">", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty).Replace("</a", string.Empty); string ConfirmationResponse = globushttpHelper.getHtmlfromUrl(new Uri(DataUrl), "", ""); IsActivated = true; break; } } } } if (IsActivated) { Log("[ " + DateTime.Now + " ] => [ Account : " + Email + " verified ]"); break; } } catch { }; } } } catch (Exception ex) { Console.WriteLine("7 :" + ex.StackTrace); Log("[ " + DateTime.Now + " ] => [ Email Verification Exception : " + ex.Message + " with : " + Email + " ]"); } return(IsActivated); #endregion } else { string Host = string.Empty; int Port = 0; if (Email.Contains("@gmail")) { Host = "pop.gmail.com"; Port = 995; } else if (Email.Contains("@hotmail")) { Host = "pop3.live.com"; Port = 995; } else if (Email.Contains("@gmx")) { Host = "pop.gmx.com"; Port = 995; } if (!string.IsNullOrEmpty(Host)) { if (popClient.Connected) { popClient.Disconnect(); } popClient.Connect(Host, Port, true); popClient.Authenticate(Email, Password); int Count = popClient.GetMessageCount(); for (int i = Count; i >= 1; i--) { try { OpenPOP.MIME.Message Message = popClient.GetMessage(i); string subject = string.Empty; subject = Message.Headers.Subject; bool GoIntoEmail = false; if (string.IsNullOrEmpty(subject)) { string from = Message.Headers.From.ToString().ToLower(); if (from.Contains("twitter.com")) { GoIntoEmail = true; } } try { if (GoIntoEmail || subject.Contains("Twitter")) //if(GoIntoEmail) { string Messagebody = Message.MessageBody[0]; foreach (string href in GetUrlsFromStringGmail(Messagebody)) { try { if (href.Contains("https://twitter.com/account/confirm_email/")) { string ConfirmationResponse = globushttpHelper.getHtmlfromUrl(new Uri(href), "", ""); IsActivated = true; break; } } catch (Exception ex) { Console.WriteLine("5 :" + ex.StackTrace); }; } } } catch (Exception ex) { Console.WriteLine("10 :" + ex.StackTrace); Log("[ " + DateTime.Now + " ] => [ Email Verification Exception : " + ex.Message + " with : " + Email + " ]"); } if (IsActivated) { break; } } catch (Exception ex) { Log("[ " + DateTime.Now + " ] => [ Email Verification Exception : " + ex.Message + " with : " + Email + " ]"); } } } } return(IsActivated); } catch (Exception ex) { Console.WriteLine("4 :" + ex.StackTrace); return(IsActivated); } }
/// <summary> /// Download and process email messages from the POP3 server. /// </summary> /// <param name="server">POP3 server information</param> public static void DownloadMessages() { // Get POP3 server info PopServer server = GetPopServer(); // connect to POP3 server and download messages //FoeDebug.Print("Connecting to POP3 server..."); POPClient popClient = new POPClient(); popClient.IsUsingSsl = server.SslEnabled; popClient.Disconnect(); popClient.Connect(server.ServerName, server.Port); popClient.Authenticate(server.UserName, server.Password); FoeDebug.Print("Connected to POP3."); // get mail count int count = popClient.GetMessageCount(); // go through each message, from newest to oldest for (int i = count; i >= 1; i -= 1) { OpenPOP.MIMEParser.Message msg = popClient.GetMessage(i, true); if (msg != null) { string subject = msg.Subject; string fromEmail = msg.FromEmail; // Check if fromEmail is the same as processor's email on file if (fromEmail.ToLower() == FoeClientRegistry.GetEntry("processoremail").Value.ToLower()) { // parse subject line string[] tokens = subject.Trim().Split(new char[] { ' ' }); // There should be 5 tokens if (tokens.Length == 5) { // Get the request ID for this reply string requestId = tokens[2]; // Check if request ID matches any request the client sent FoeClientRequestItem req = FoeClientRequest.Get(requestId); if (req != null) { // Found the matching request // Download the full reply OpenPOP.MIMEParser.Message wholeMsg = popClient.GetMessage(i, false); string msgBody = (string)wholeMsg.MessageBody[0]; try { // decompress it byte[] compressedMsg = Convert.FromBase64String(msgBody); byte[] decompressedMsg = CompressionManager.Decompress(compressedMsg); string foeXml = Encoding.UTF8.GetString(decompressedMsg); // Check what is the original request type if (req.Type.ToLower() == "reg") { ProcessRegistrationReply(foeXml); } else if (req.Type.ToLower() == "content") { ProcessContentReply(foeXml); } else if (req.Type.ToLower() == "catalog") { ProcessCatalogReply(foeXml); } } catch (Exception) { // the message is likely malformed // so just ignore it } } } } } // Delete the current message popClient.DeleteMessage(i); } popClient.Disconnect(); }