Sample code for 30+ languages & platforms
Xbase++

Share an Existing SSH Tunnel (Socket) with IMAP

See more IMAP Examples

Demonstrates the Chilkat Imap.UseSshTunnel method, which uses an existing SSH tunnel, represented by a Socket object, for IMAP connections. The only argument is the Socket. Call it before Connect. This example opens and authenticates the tunnel on a Socket, then routes IMAP through it.

Background: A Socket object can open and hold an SSH tunnel that several Chilkat objects share. This is the approach when the tunnel is managed independently of any one protocol object — for example a long-lived tunnel reused across IMAP, POP3, and SMTP sessions — whereas SshOpenTunnel ties the tunnel's lifetime to the Imap object.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oImap
LOCAL oSshTunnel
LOCAL nSshPort
LOCAL cSshPassword

nSuccess := 0

//  Demonstrates the Imap.UseSshTunnel method, which uses an existing SSH tunnel (represented by
//  a Socket) for IMAP connections.  The only argument is the Socket.  Call it before Connect.

oImap := CreateObject("Chilkat.Imap")

//  Open and authenticate an SSH tunnel on a Socket object.  This tunnel can be shared with
//  other Chilkat objects.
oSshTunnel := CreateObject("Chilkat.Socket")
nSshPort := 22
nSuccess := oSshTunnel:SshOpenTunnel("ssh.example.com", nSshPort)
IF (nSuccess == 0)
    ? oSshTunnel:LastErrorText
    oImap:destroy()
    oSshTunnel:destroy()
    RETURN
ENDIF

//  The SSH password is not hard-coded in source.  Insert code here to obtain it from an
//  interactive prompt, environment variable, or a secrets vault.

nSuccess := oSshTunnel:SshAuthenticatePw("sshUser", cSshPassword)
IF (nSuccess == 0)
    ? oSshTunnel:LastErrorText
    oImap:destroy()
    oSshTunnel:destroy()
    RETURN
ENDIF

//  Tell the Imap object to use the existing tunnel.
nSuccess := oImap:UseSshTunnel(oSshTunnel)
IF (nSuccess == 0)
    ? oImap:LastErrorText
    oImap:destroy()
    oSshTunnel:destroy()
    RETURN
ENDIF

//  Now connect and log in to the IMAP server through the tunnel.
oImap:Ssl := 1
oImap:Port := 993
nSuccess := oImap:Connect("imap.example.com")
IF (nSuccess == 0)
    ? oImap:LastErrorText
    oImap:destroy()
    oSshTunnel:destroy()
    RETURN
ENDIF

nSuccess := oImap:Login("user@example.com", "myPassword")
IF (nSuccess == 0)
    ? oImap:LastErrorText
    oImap:destroy()
    oSshTunnel:destroy()
    RETURN
ENDIF

nSuccess := oImap:Disconnect()
IF (nSuccess == 0)
    ? oImap:LastErrorText
    oImap:destroy()
    oSshTunnel:destroy()
    RETURN
ENDIF

oImap:destroy()
oSshTunnel:destroy()