Sample code for 30+ languages & platforms
Rust

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 Rust Downloads

Rust

// 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.

let imap = chilkat::Imap::new();

// Open and authenticate an SSH tunnel on a Socket object.  This tunnel can be shared with
// other Chilkat objects.
let ssh_tunnel = chilkat::Socket::new();
let ssh_port = 22;
if ssh_tunnel.ssh_open_tunnel("ssh.example.com", ssh_port).is_err() {
    println!("{}", ssh_tunnel.last_error_text());
    return;
}

// 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.
let ssh_password = String::new();

if ssh_tunnel.ssh_authenticate_pw("sshUser", &ssh_password).is_err() {
    println!("{}", ssh_tunnel.last_error_text());
    return;
}

// Tell the Imap object to use the existing tunnel.
if imap.use_ssh_tunnel(&ssh_tunnel).is_err() {
    println!("{}", imap.last_error_text());
    return;
}

// Now connect and log in to the IMAP server through the tunnel.
imap.set_ssl(true);
imap.set_port(993);
if imap.connect("imap.example.com").is_err() {
    println!("{}", imap.last_error_text());
    return;
}

if imap.login("user@example.com", "myPassword").is_err() {
    println!("{}", imap.last_error_text());
    return;
}

if imap.disconnect().is_err() {
    println!("{}", imap.last_error_text());
    return;
}