public bool Stop() { manager.ClearModules(); if (!running) { return(false); } running = false; L.Log("E::Stop called"); send("QUIT :" + G.settings["identifier"]); Thread.Sleep(600); if (parser.ThreadState == ThreadState.Running) { parser.Abort(); } Thread.Sleep(600); stream.Flush(); stream.Close(); cli.Close(); manager.ClearChannels(); return(true); }
static void Main(string[] args) { try { // there should be no gap between the imap command and the \r\n // ssl.read() -- while ssl.readbyte!= eof does not work because there is no eof from server // cannot check for \r\n because in case of larger response from server ex:read email message // there are lot of lines so \r \n appears at the end of each line //ssl.timeout sets the underlying tcp connections timeout if the read or write //time out exceeds then the undelying connection is closed tcpc = new System.Net.Sockets.TcpClient("imap.mail.ru", 993); ssl = new System.Net.Security.SslStream(tcpc.GetStream()); ssl.AuthenticateAsClient("imap.mail.ru"); receiveResponse(""); Console.WriteLine("username : "******"password : "******"$ LOGIN " + username + " " + password + "\r\n"); // Getting amount of Inbox String inbox = receiveResponse("$ SELECT INBOX\r\n"); string[] words = inbox.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries); words[1] = words[1].Trim(new char[] { ' ', 'E' }); // " xx EXISTS" string subString = "EXISTS"; int indexOfSubstring = words[1].IndexOf(subString); words[1] = words[1].Substring(0, indexOfSubstring - 1); // "xx" int amount = Convert.ToInt32(words[1]); Console.WriteLine("Всего писем: " + amount + "\r\n"); for (int i = 0; i < amount; i++) { Console.WriteLine("Письмо №{0}" + ":", i + 1); GetMail(i); } //receiveResponse("$ LOGOUT\r\n"); } catch (Exception ex) { Console.WriteLine("error: " + ex.Message); } finally { if (ssl != null) { ssl.Close(); ssl.Dispose(); } if (tcpc != null) { tcpc.Close(); } } Console.ReadKey(); }
public void Disconnect() { if (ssl != null) { ssl.Close(); ssl.Dispose(); } if (tcpc != null) { tcpc.Close(); } }
/// <summary> /// Saving a mail message before beeing sent by the SMTP client /// </summary> /// <param name="self">The caller</param> /// <param name="imapServer">The address of the IMAP server</param> /// <param name="imapPort">The port of the IMAP server</param> /// <param name="userName">The username to log on to the IMAP server</param> /// <param name="password">The password to log on to the IMAP server</param> /// <param name="sentFolderName">The name of the folder where the message will be saved</param> /// <param name="mailMessage">The message being saved</param> public static void SendAndSaveMessageToIMAP(this System.Net.Mail.SmtpClient self, System.Net.Mail.MailMessage mailMessage, string imapServer, int imapPort, string userName, string password, string sentFolderName) { try { path = System.Environment.CurrentDirectory + "\\emailresponse.txt"; if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } sw = new System.IO.StreamWriter(System.IO.File.Create(path)); tcpc = new System.Net.Sockets.TcpClient(imapServer, imapPort); ssl = new System.Net.Security.SslStream(tcpc.GetStream()); ssl.AuthenticateAsClient(imapServer); SendCommandAndReceiveResponse(""); SendCommandAndReceiveResponse(string.Format("$ LOGIN {1} {2} {0}", System.Environment.NewLine, userName, password)); using (var m = mailMessage.RawMessage()) { m.Position = 0; var sr = new System.IO.StreamReader(m); var myStr = sr.ReadToEnd(); SendCommandAndReceiveResponse(string.Format("$ APPEND {1} (\\Seen) {{{2}}}{0}", System.Environment.NewLine, sentFolderName, myStr.Length)); SendCommandAndReceiveResponse(string.Format("{1}{0}", System.Environment.NewLine, myStr)); } SendCommandAndReceiveResponse(string.Format("$ LOGOUT{0}", System.Environment.NewLine)); } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine("error: " + ex.Message); } finally { if (sw != null) { sw.Close(); sw.Dispose(); } if (ssl != null) { ssl.Close(); ssl.Dispose(); } if (tcpc != null) { tcpc.Close(); } } self.Send(mailMessage); }
public void DcFromGmail() //---#2 log off { ReceiveResponse(prefix + " LOGOUT\r\n"); if (answer.Contains("OK")) { userAvailable = false; } else { userAvailable = true; } if (ssl != null) { ssl.Close(); ssl.Dispose(); } if (tcpc != null) { tcpc.Close(); } }
static void Main(string[] args) { try { path = Environment.CurrentDirectory + "\\emailresponse.txt"; if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } sw = new System.IO.StreamWriter(System.IO.File.Create(path)); // there should be no gap between the imap command and the \r\n // ssl.read() -- while ssl.readbyte!= eof does not work because there is no eof from server // cannot check for \r\n because in case of larger response from server ex:read email message // there are lot of lines so \r \n appears at the end of each line //ssl.timeout sets the underlying tcp connections timeout if the read or write //time out exceeds then the undelying connection is closed tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993); ssl = new System.Net.Security.SslStream(tcpc.GetStream()); ssl.AuthenticateAsClient("imap.gmail.com"); receiveResponse(""); receiveResponse("$ CAPABILITY\r\n"); Console.WriteLine("username : "******"password : "******"$ LOGIN " + username + " " + password + "\r\n"); Console.Clear(); receiveResponse("$ LIST " + "\"\"" + " \"*\"" + "\r\n"); receiveResponse("$ SELECT INBOX\r\n"); receiveResponse("$ STATUS INBOX (MESSAGES)\r\n"); Console.WriteLine("enter the email number to fetch :"); int number = int.Parse(Console.ReadLine()); fetchEmailHeader(number); fetchEmailBody(number); Console.WriteLine(receiveResponse("$ LOGOUT\r\n")); } catch (Exception ex) { Console.WriteLine("error: " + ex.Message); } finally { if (sw != null) { sw.Close(); sw.Dispose(); } if (ssl != null) { ssl.Close(); ssl.Dispose(); } if (tcpc != null) { tcpc.Close(); } } Console.ReadKey(); }
static string SendAPNS(string deviceToken, string content) { //ref:https://msdn.microsoft.com/en-us/library/txafckwd.aspx //ref2:http://stackoverflow.com/questions/16101100/string-format-input-string-was-not-in-correct-format-for-string-with-curly-brack //要多加雙括號"{{"才能讓參數寫入string的format string jsonContent = String.Format("{{\"aps:\":{{\"alert\":\"{0}\",\"badge\":8,\"sound\":\"default\"}}}}", deviceToken); //Json: { MID = 1000242, MsgID = 12345, RegID = "c1564dd73cd73a003d2ad143d96c9e6d651f8b48b45ba8c0ae9c5db87513fde8", Subj = "測試12 主題一:88個badge", Sum = 88, Title = "test2 Content" }; //str = "{\"aps\":{\"alert\":\"" + s2 + "\",\"badge\":10,\"sound\":\"default\"}}"; //string hostIP = "gateway.sandbox.push.apple.com";//"gateway.push.apple.com";//;//feedback.sandbox.push.apple.com//"feedback.sandbox.push.apple.com"; int port = 2195; //2196; string password = "******"; //AllPay //certificate load 需要去Apple申請App的憑證才有此檔 string certificatepath = "aps_production_allpay.p12";//"allpay_apns_dev.p12" ;//"AllPayEPAPNS.p12"//企業版prod;// //"allpay.p12";//bin/debug string certificateFullPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppleCertificate", certificatepath); certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(File.ReadAllBytes(certificateFullPath), password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); var certificates = new System.Security.Cryptography.X509Certificates.X509Certificate2Collection(); certificates.Add(certificate); //使用TCP Cient來建立connect(就是走簡易的http) TcpClient apnsClient = new TcpClient(); Stopwatch timer = new Stopwatch(); try { timer.Start(); apnsClient.Connect(hostIP, port); } catch (SocketException ex) { timer.Stop(); Console.WriteLine("TimeSpend:{0}ms ex:{1}", timer.ElapsedMilliseconds, ex.Message); } //主要認證憑證就是這段,可以使用event認證兩方的憑證,目前APNs這邊都只使用Apple給的憑證 System.Net.Security.SslStream apnsStream = new System.Net.Security.SslStream(apnsClient.GetStream(), false, new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate), new System.Net.Security.LocalCertificateSelectionCallback(SelectLocalCertificate)); try { apnsStream.AuthenticateAsClient(hostIP, certificates, System.Security.Authentication.SslProtocols.Tls, false); timer.Stop(); Console.WriteLine("做完認證的TimeSpend:{0}ms", timer.ElapsedMilliseconds); } catch (System.Security.Authentication.AuthenticationException ex) { Console.WriteLine("error:" + ex.Message); } if (!apnsStream.IsMutuallyAuthenticated) { Console.WriteLine("error:" + "Ssl Stream Failed to Authenticate"); } if (!apnsStream.CanWrite) { Console.WriteLine("error:" + "Ssl Stream is not Writable"); return(""); } //需要取得Apple手機給的token來當作裝置的識別碼,送的格式參考APPLE規定的JSON byte[] message = ToBytes(deviceToken, content); apnsStream.Write(message);//這邊就可以開始送資料了 apnsStream.Close(); return(Encoding.UTF8.GetString(message)); }