Sample code for 30+ languages & platforms
Zig

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

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

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

    const imap = try chilkat.Imap.init();
    defer imap.deinit();

    // Open and authenticate an SSH tunnel on a Socket object.  This tunnel can be shared with
    // other Chilkat objects.
    const ssh_tunnel = try chilkat.Socket.init();
    defer ssh_tunnel.deinit();
    const ssh_port = 22;
    ssh_tunnel.sshOpenTunnel("ssh.example.com", ssh_port) catch {
        std.debug.print("{s}\n", .{try ssh_tunnel.getLastErrorText(alloc)});
        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.
    const ssh_password: [:0]const u8 = "";

    ssh_tunnel.sshAuthenticatePw("sshUser", ssh_password) catch {
        std.debug.print("{s}\n", .{try ssh_tunnel.getLastErrorText(alloc)});
        return;
    };

    // Tell the Imap object to use the existing tunnel.
    imap.useSshTunnel(ssh_tunnel) catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

    // Now connect and log in to the IMAP server through the tunnel.
    imap.setSsl(true);
    imap.setPort(993);
    imap.connect("imap.example.com") catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

    imap.login("user@example.com", "myPassword") catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };

    imap.disconnect() catch {
        std.debug.print("{s}\n", .{try imap.getLastErrorText(alloc)});
        return;
    };
}