Sample code for 30+ languages & platforms
Zig

Use a TLS Client Certificate

See more SMTP Examples

Demonstrates the Chilkat MailMan.SetSslClientCert method, which sets the client-side certificate to use for SSL/TLS connections. This is typically not required — most SSL/TLS connections authenticate the server only. This example loads a client certificate from a PFX and uses it when connecting.

Background: In an ordinary TLS handshake only the server presents a certificate, and the client proves who it is later with a password. Mutual TLS adds a second leg: the client also presents a certificate, so it is authenticated cryptographically at the transport layer. Some corporate or high-security mail servers require this. Because the client must prove possession of the key, the certificate needs its private key — hence loading from a PFX.

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();

    var success: bool = false;

    // Demonstrates the MailMan.SetSslClientCert method, which sets the client-side certificate
    // to use for SSL/TLS connections.  This is typically not required -- most SSL/TLS
    // connections authenticate the server only.

    const mailman = try chilkat.MailMan.init();
    defer mailman.deinit();

    // Configure the SMTP server connection.
    mailman.setSmtpHost("smtp.example.com");
    mailman.setSmtpPort(465);
    mailman.setSmtpSsl(true);
    mailman.setSmtpUsername("user@example.com");
    mailman.setSmtpPassword("myPassword");

    // Load the client certificate (with its private key) from a PFX file.
    const cert = try chilkat.Cert.init();
    defer cert.deinit();
    success = if (cert.loadPfxFile("qa_data/certs/client.pfx", "pfx_password")) true else |_| false;
    if (!success) {
        std.debug.print("{s}\n", .{try cert.getLastErrorText(alloc)});
        return;
    }

    // Use this certificate to identify the client during the TLS handshake.
    success = if (mailman.setSslClientCert(cert)) true else |_| false;
    if (!success) {
        std.debug.print("{s}\n", .{try mailman.getLastErrorText(alloc)});
        return;
    }

    success = mailman.verifySmtpLogin();
    if (!success) {
        std.debug.print("{s}\n", .{try mailman.getLastErrorText(alloc)});
        return;
    }

    std.debug.print("Connected using a TLS client certificate.\n", .{});

    // Note: The path "qa_data/certs/client.pfx" is a relative local filesystem path,
    // relative to the current working directory of the running application.
}