Received an unexpected EOF or 0 bytes from the transport stream
When you are getting the following error:
Received an unexpected EOF or 0 bytes from the transport stream.
while using ConnectSSL method, most likely your server incorrectly advertises TLS support. You might be required to use SSLv2 or SSLv3.
This article describes how to force SSLv3 or SSLv2 in Mail.dll or in regular .NET SslStream class.
Force SSLv3 or SSLv2 in Mail.dll
// C# version
using (Imap client = new Imap())
{
// Force to use SSL3
client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Ssl3;
// Ignore certificate errors
client.ServerCertificateValidate += (sender, e) => { e.IsValid = true; };
client.ConnectSSL("imap.gmail.com");
client.Login("user@gmail.com", "password");
client.SelectInbox();
foreach(long uid in client.Search(Flag.Unseen))
{
var eml = client.GetMessageByUID(uid);
IMail email = new MailBuilder().CreateFromEml(eml);
Console.WriteLine(email.Subject);
}
client.Close();
}
' VB.NET version
Using client As New Imap()
' Force to use SSL3
client.SSLConfiguration.EnabledSslProtocols = SslProtocols.Ssl3
' Ignore certificate errors
AddHandler client.ServerCertificateValidate, AddressOf Validate
client.ConnectSSL("imap.gmail.com")
client.Login("user@gmail.com", "password")
client.SelectInbox()
For Each uid As Long In client.Search(Flag.Unseen)
Dim eml = client.GetMessageByUID(uid)
Dim email As IMail = New MailBuilder().CreateFromEml(eml)
Console.WriteLine(email.Subject)
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
Force SSLv3 or SSLv2 in SslStream class
// C# version
const string host = "imap.gmail.com";
Socket socket = new Socket(
AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
socket.Connect(host, 993);
using(SslStream ssl = new SslStream(new NetworkStream(socket), true))
{
ssl.AuthenticateAsClient(
host,
new X509CertificateCollection(),
SslProtocols.Ssl3,
true);
using(StreamReader reader = new StreamReader(ssl))
{
Console.WriteLine(reader.ReadLine());
}
}
socket.Close();
' VB.NET version Const host As String = "imap.gmail.com" Dim socket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) socket.Connect(host, 993) Using ssl As New SslStream(New NetworkStream(socket), True) ssl.AuthenticateAsClient(host, New X509CertificateCollection(), SslProtocols.Ssl3, True) Using reader As New StreamReader(ssl) Console.WriteLine(reader.ReadLine()) End Using End Using socket.Close()