IMAP with TLS

Jun 6, 2013 at 9:00 AM
Do you have an example of connecting to an IMAP server using TLS?

I've tried doing the obvious and specify Tls as the protocol in the SslHandShake but I always get the following IOException:

"The handshake failed due to an unexpected packet format."

Any help appreciated.
Jul 8, 2013 at 2:30 PM
Could You post a code which You wrote, maybe someone find a right way.
Jul 9, 2013 at 3:58 PM
Edited Jul 9, 2013 at 4:02 PM
I actually did find a way of getting this to work for my particular situation.

Having connected I found that if I send a starttls command before the SSL handshake is performed I can login successfully and access mailboxes. It's not particularly pretty as I have to use reflection to call DoSslHandShake but it does work!

The following code is just scratch code I used while trying to find a solution and needs tidying up before production use:
Imap4Client imap = new Imap4Client();

var ssl = imap.GetType().GetMethod("DoSslHandShake", 
              BindingFlags.Instance | 
              BindingFlags.Public | 
              BindingFlags.NonPublic);

var a = imap.Connect("yourhost.com", 143);
var b = imap.Command("starttls");

var handshake = new SslHandShake("yourhost.com", 
                            System.Security.Authentication.SslProtocols.Tls, 
                            null, null, null, false);

var c = ssl.Invoke(imap, new[] { handshake });
            
var d = imap.Login("username", "password");


Mailbox inbox = imap.SelectMailbox("inbox");

MessageCollection mc = new MessageCollection();

for (int n = 1; n < inbox.MessageCount + 1; n++)
{
        ActiveUp.Net.Mail.Message newMessage = inbox.Fetch.MessageObject(n);
        mc.Add(newMessage);
}

if (imap.IsConnected)
        imap.Disconnect();
Jul 11, 2013 at 6:12 AM
Nice Work. I try to write this, but I could not properly test it. Type of SslProtocols.xyz (I dont know if tls, or tls11, tls12), this maybe specify customer in configuration file (by switchig, I set a type of protocol)
public static Imap4Client Login(string mailServer, int port, bool ssl, bool tls, string login, string password)
{
            SslHandShake sslhandshake;                         
            Imap4Client client = new Imap4Client();
            if (ssl)
            {
                client.ConnectSsl(mailServer, port);
            }
            else if (tls)
            {
                sslhandshake = new SslHandShake(mailServer, System.Security.Authentication.SslProtocols.Tls12);
                client.ConnectSsl(mailServer, port, sslhandshake);
            }
            else
            {
                client.Connect(mailServer, port);
            }
            client.Login(login, password);
            return client;
 }