Recently, with the POP3 protocol, logging on to pop.qq.com and pop.163.com is no problem, so I thought about logging on to pop.gmail.com and the result failed. After investigation, we found that Gmail's POP3 port is not 110, but 995. So I changed the port, but the login still failed. After checking the information, we found that Gmail used SSL verification and cannot connect directly. Then how does C # implement SSL connections? After checking a lot of information, we found that it can be implemented through sslstream.
The following is the connection code of sslstream.
private StreamReader pop3StreamReader_ = null; private SslStream pop3Stream_ = null; public void connect(string host, int port) { try { TcpClient popServer = new TcpClient(host, port); pop3Stream_ = new SslStream(popServer.GetStream(), false); pop3Stream_.AuthenticateAsClient(host); isConnected_pro = true; pop3StreamReader_ = new StreamReader(pop3Stream_, encoding_pro); } catch (System.Exception ex) { exception_pro = ex; isConnected_pro = false; } }
Pop3streamreader _ is used to receive response data.
How do I send data after the SSL connection is successful? You can use the write method of sslstream. The following describes how to send data.
public bool send(string sendStr) { try { exception_pro = null; pop3Stream_.Write(encoding_pro.GetBytes(sendStr)); return true; } catch (System.Exception ex) { exception_pro = ex; return false; } }
How can I receive the data? You can use the Readline method of pop3streamreader.
The following describes how to receive data.
/// <summary> /// Receive one line data. /// </summary> /// <returns></returns> public string receive() { string receiveStr = ""; receiveStr = pop3StreamReader_.ReadLine(); return receiveStr; }
Below is a simple call to the above method
private void buttonSsl_Click(object sender, EventArgs e) { SslSp sslSp = new SslSp(); sslSp.connect("pop.gmail.com", 995); string receiveStr = sslSp.receive(); MessageBox.Show(receiveStr); sslSp.send("user mysuer\r\n"); receiveStr = sslSp.receive(); MessageBox.Show(receiveStr); sslSp.send("pass mypassword\r\n"); receiveStr = sslSp.receive(); MessageBox.Show(receiveStr);}
In actual applications, we recommend that you add a disconnect function for SSL connections to facilitate management.