2014-09-11 76 views
0

您好我正嘗試使用C#中的ImapX庫連接到gmail。 但是得到像這樣的錯誤無法建立連接,因爲目標機器在創建TcpClient(在ImapX中)時主動拒絕它74.125.25.109:993。 我在stackoverflow上瀏覽了幾個相同的問題,但沒有一個對我有幫助。由於目標機器主動拒絕,無法建立連接74.125.25.109:993

這是我的代碼。

static void Main(string[] args) 
{ 
    var client = new ImapClient("imap.gmail.com",993, true); 
    client.SslProtocol = System.Security.Authentication.SslProtocols.Ssl2; 
    client.UseSsl = true; 
    if (client.Connect()) // This method creates new instance of TcpClient which throws error so returning false from catch block method has been described below. 
    { 

     if (client.Login("[email protected]", "example123")) 
     { 
      // login successful 
     } 
     Console.WriteLine("Connection Successful...!"); 
     Console.ReadLine(); 
    } 
    else 
    { 
     Console.WriteLine("Connection UnSuccessful...!"); 
     Console.ReadLine(); 
     // connection not successful 
    } 
} 

這裏是ImapX庫中的客戶端方法。

public bool Connect(string host, int port, SslProtocols sslProtocol = SslProtocols.None, 
    bool validateServerCertificate = true) 
{ 
    _host = host; 
    _port = port; 
    _sslProtocol = sslProtocol; 
    _validateServerCertificate = validateServerCertificate; 

    if (IsConnected) 
     throw new InvalidStateException("The client is already connected. Please disconnect first."); 

    try 
    { 

     _client = new TcpClient(_host, _port); 
     if (_sslProtocol == SslProtocols.None) 
     { 
      _ioStream = _client.GetStream(); 
      _streamReader = new StreamReader(_ioStream); 
     } 
     else 
     { 
      _ioStream = new SslStream(_client.GetStream(), false, CertificateValidationCallback, null); 
      (_ioStream as SslStream).AuthenticateAsClient(_host, null, _sslProtocol, false); 
      _streamReader = new StreamReader(_ioStream); 
     } 


     string result = _streamReader.ReadLine(); 

     _lastActivity = DateTime.Now; 

     if (result != null && result.StartsWith(ResponseType.ServerOk)) 
     { 
      Capability(); 
      return true; 
     } 
     else if (result != null && result.StartsWith(ResponseType.ServerPreAuth)) 
     { 
      IsAuthenticated = true; 
      Capability(); 
      return true; 
     } 
     else 
      return false; 
    } 
    catch (Exception) 
    { 
     return false; 
    } 
    finally 
    { 
     if (!IsConnected) 
      CleanUp(); 
    } 
} 

在此先感謝。

+0

如果我使用Telenet,那麼我會變成這樣。 Microsoft Telnet> open imap.gmail.com 993 連接到imap.gmail.com ...無法打開與主機的連接,端口99 3:連接失敗 – 2014-09-11 09:10:48

+0

您是否能夠連接某些郵件客戶端sw,例如雷鳥?你有沒有配置任何代理? – 2014-09-11 09:12:38

+0

@FrantišekŽiačik我不確定有關雷鳥,而是使用Windows Live郵件作爲我的郵件客戶端,我沒有任何代理配置。 – 2014-09-11 09:17:06

回答

0

當你使用ImapX與Gmail時,下面的代碼就足以建立連接:

var client = new ImapClient("imap.gmail.com", true); 
if (client.Connect()) { 
    // ... 
} 

它將使用SSL與標準的993端口。如果你想手動指定SSL版本,對於GMail,你需要使用SslProtocols.Default,這相當於SslProtocols.Ssl3 | SslProtocols.Tls

+0

你說得對。問題出在我的機器和網絡不允許我通過端口993連接到imap.gmail.com。我嘗試了另一臺機器並開始工作。謝謝你的時間。 – 2014-11-17 03:55:26

相關問題