2014-09-11 126 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

相关问题