A connection attempt failed

If you are getting following or similar exception:
“A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond” or “No connection could be made because the target machine actively refused it.” most likely you provided incorrect server, port, and SSL usage configuration to Connect, or ConnectSSL methods.

Default ports for email protocols are:

Plain text SSL/TLS
IMAP 143 993
POP3 110 995
SMTP 587 or 25 465

Most email providers (like Gmail, Hotmail, Yahoo and others) use default ports. Connect() and ConnectSSL() and fluent interface use those ports by default.

Please ask your email server administrator for server, port, and SSL/TLS usage, if those are not standard there is no way you can guess them.

Please also make sure that:

  • your application has enough security permissions to establish connection to the server.
  • you are using correct client class with protocol you plan to use (Pop3 class with POP3 protocol, Imap class with IMAP, and Smtp class with SMTP protocol)
  • you use correct port numbers, and rely on parameter-less Connect() and ConnectSSL() methods (they use default ports) whenever possible
  • you are using ConnectSSL when you require SSL/TLS, and Connect when you don’t
  • firewall and antivirus software are disabled or configured correctly (this includes Windows Defender)
  • the protocol you are trying to use is enabled on the server. Exchange or Gmail can have some protocols disabled by default

Following articles can help you with that:

Connecting using default ports

Plain text mode

Establishing connection using default port is simple, you just need to use Connect method:

// C#

client.Connect("mail.example.com");
' VB.NET

client.Connect("mail.example.com")

Implicit SSL/TLS mode

If SSL encryption is required, use ConnectSSL method:

// C#

client.ConnectSSL("mail.example.com");
' VB.NET

client.ConnectSSL("mail.example.com")

Explicit SSL mode (aka TLS)

If your server requires explicit SSL/TLS (sometimes called TLS), you need to connect using Connect method and then use StartTLS method:

// C#

client.Connect("mail.example.com");
client.StartTLS();
' VB.NET

client.ConnectSSL("mail.example.com")
client.StartTLS()

Connecting using non-standard ports

If you need to specify different port just use overloaded version of Connect or ConnectSSL method:

// C#

client.Connect("mail.example.com", 999);
' VB.NET

client.Connect("mail.example.com", 999)

If SSL/TLS encryption is required:

// C#

client.ConnectSSL("mail.example.com", 999);
' VB.NET

client.ConnectSSL("mail.example.com", 999)

If you need to specify different port using fluent interface use OnPort() method:

// C# version

Mail.Text(@"Hello")
  .To("to@mail.com")
  .From("from@mail.com")
  .Subject("Subject")
  .UsingNewSmtp()
  .Server(_server)
  .WithSSL()
  .OnPort(443)
  .WithCredentials("user", "password")
  .Send();

SSL/TLS

Please look at following articles for details:

Some servers require explicit SSL/TLS (sometimes called TLS). Usually this triggers “The handshake failed due to an unexpected packet format” exception, when you try to connect without SSL/TLS.

If your server uses self-signed certificates you may be getting “The remote certificate is invalid according to the validation procedure” error.

Please read SSL vs TLS vs STARTTLS, if you are confused about those.

Again when in doubt please ask your email server administrator for server, port, and SSL/TLS usage.

The handshake failed due to an unexpected packet format

Most likely your FTP server requires explicit SSL. So first try to connect without SSL:

// C#

client.Connect("ftp.example.org");
' VB.NET

client.Connect("ftp.example.org")

Then, before logging-in, start explicit SSL negotiation:

// C#

client.AuthSSL();
' VB.NET

client.AuthSSL()

Now, your connection is secured.

Remember that you can ignore SSL certificate errors using ServerCertificateValidate event:

// C# version

using (Ftp client = new Ftp())
{
    // Use this line to validate self-signed certificates:
    client.ServerCertificateValidate += ValidateCertificate;

    client.Connect("ftp.example.org");
    client.AuthSSL();
    client.Login("username", "password");

    foreach (FtpItem item in client.GetList())
    {
        if (item.IsFolder == true)
            Console.WriteLine("[{0}]", item.Name);
        else
            Console.WriteLine("{0}", item.Name);
    }
    client.Close();
}

private static void ValidateCertificate(
    object sender,
    ServerCertificateValidateEventArgs e)
{
    const SslPolicyErrors ignoredErrors =
        SslPolicyErrors.RemoteCertificateChainErrors |
        SslPolicyErrors.RemoteCertificateNameMismatch;

    if ((e.SslPolicyErrors & ~ignoredErrors) == SslPolicyErrors.None)
    {
        e.IsValid = true;
        return;
    }
    e.IsValid = false;
}
' VB.NET version

Using client As New Ftp()
    ' Use this line to validate self-signed certificates:
    AddHandler client.ServerCertificateValidate, AddressOf ValidateCerificate

    client.Connect("ftp.example.org")
    client.AuthSSL()
    client.Login("username", "password")

    For Each item As FtpItem In client.GetList()
        If item.IsFolder = True Then
            Console.WriteLine("[{0}]", item.Name)
        Else
            Console.WriteLine("{0}", item.Name)
        End If
    Next
    client.Close()
End Using

Private Sub ValidateCerificate( _
    ByVal sender As Object, _
    ByVal e As ServerCertificateValidateEventArgs)

    Const ignoredErrors As SslPolicyErrors = _
        SslPolicyErrors.RemoteCertificateChainErrors Or _
        SslPolicyErrors.RemoteCertificateNameMismatch

    If (e.SslPolicyErrors And Not ignoredErrors) = SslPolicyErrors.None Then
        e.IsValid = True
        Return
    End If
    e.IsValid = False
End Sub

You can download Ftp.dll FTP/FTPS client for .NET here.

The remote certificate is invalid according to the validation procedure

If you get “The remote certificate is invalid according to the validation procedure” exception while trying to establish SSL connection, most likely your server certificate is self-signed or you used incorrect host name to connect (Host name must match the name on certificate, for example ftp.example.com and example.com may point to the same server, but certificate is issued only to ftp.example.com and this is the address you should use).

Good news is that you can accept self-signed certificates using Ftp.dll FTP and FTPS .NET component.

First you need to subscribe to ServerCertificateValidate event.

Then you need to create Validatemethod that validates the certificate (ignores certificate chain and name mismatch errors).

// C# version

using (Ftp client = new Ftp())
{
    // Use custom certificate validation:
    client.ServerCertificateValidate +=
        new ServerCertificateValidateEventHandler(Validate);

    // Minimalistic version to accept any certificate:
    // 
    //client.ServerCertificateValidate +=
    //    (sender, e) => { e.IsValid = true; };
    // 

    client.ConnectSSL("ftp.example.org");
    client.Login("username", "password");

    foreach (FtpItem item in client.GetList())
    {
        if (item.IsFolder == true)
            Console.WriteLine("[{0}]", item.Name);
        else
            Console.WriteLine"{0}", item.Name);
    }
    client.Close();
}

private static void Validate(
    object sender,
    ServerCertificateValidateEventArgs e)
{
    const SslPolicyErrors ignoredErrors =
        // self-signed
        SslPolicyErrors.RemoteCertificateChainErrors
        // name mismatch
        |  SslPolicyErrors.RemoteCertificateNameMismatch;  

    if ((e.SslPolicyErrors & ~ignoredErrors) 
        == SslPolicyErrors.None)
    {
        e.IsValid = true;
        return;
    }
    e.IsValid = false;
}
' VB.NET version

Using client As New Ftp()
    ' Use custom certificate validation:
    AddHandler client.ServerCertificateValidate, AddressOf Validate

    client.ConnectSSL("ftp.example.org")
    client.Login("username", "password")

    For Each item As FtpItem In client.GetList()
        If item.IsFolder = True Then
            Console.WriteLine("[{0}]";, item.Name)
        Else
            Console.WriteLine("{0}", item.Name)
        End If
    Next
    client.Close()
End Using

Private Sub Validate( _
    ByVal sender As Object, _
    ByVal e As ServerCertificateValidateEventArgs)

    Const ignoredErrors As SslPolicyErrors = _
        ' self-signed
        SslPolicyErrors.RemoteCertificateChainErrors _    
        ' name mismatch
        Or SslPolicyErrors.RemoteCertificateNameMismatch        

    If (e.SslPolicyErrors And Not ignoredErrors) = SslPolicyErrors.None Then
        e.IsValid = True
        Return
    End If
    e.IsValid = False
End Sub

You can download Ftp.dll FTP/FTPS component for .NET here.

Folder management using FTP (create, delete, rename)

Use CreateFolder, Rename and DeleteFolder methods for folder management on remote FTP server:

// C# version

using (Ftp client = new Ftp())
{
    client.Connect("ftp.example.org");
    client.Login("user", "password");

    client.CreateFolder("reports");

    client.Rename("reports", "reports 2010");

    client.DeleteFolder("reports 2010");

    client.Close();
}
' VB.NET version

Using client As New Ftp()
	client.Connect("ftp.example.org")
	client.Login("user", "password")

	client.CreateFolder("reports")

	client.Rename("reports", "reports 2010")

	client.DeleteFolder("reports 2010")

	client.Close()
End Using

You can download Ftp.dll FTP/FTPS component for .NET here.

Move file to different folder using FTP

Just use Rename method to move files to different folder:

// C# version

using (Ftp client = new Ftp())
{
    client.Connect("ftp.example.org");
    client.Login("user", "password");

    client.Rename("report.txt", "reports/report_2010.txt");

    client.Close();
}
' VB.NET version

Using client As New Ftp()
	client.Connect("ftp.example.org")
	client.Login("user", "password")

	client.Rename("report.txt", "reports/report_2010.txt")

	client.Close()
End Using

You can download Ftp.dll FTP/FTPS library for .NET here.