Sample code for 30+ languages & platforms
Zig

Find Certificate for Email Encryption

Demonstrates finding the recipient's certificate in the Windows certificate store and using it to send encrypted email.

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;

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

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

    // Set the SMTP server.
    mailman.setSmtpHost("smtp.example.com");

    // Create a new email object
    const email = try chilkat.Email.init();
    defer email.deinit();

    email.setSubject("This email is encrypted");
    email.setBody("This is a digitally encrypted mail");
    email.setFrom("Joe <joe@example.com>");
    // Emails are encrypted using the recipient's certificate.
    const recipient_email_addr = "jane@example2.com";
    email.addTo("Jane", recipient_email_addr) catch {};

    // Indicate that the email is to be sent encrypted.
    email.setSendEncrypted(true);

    // This example demonstrates finding the email encryption certificate
    // on a Windows system where the certificate is stored in the Windows
    // certificate store.

    const cert = try chilkat.Cert.init();
    defer cert.deinit();
    // The recipient's certificate is used to encrypt.
    // (Because the recipient is the only one in possession of the private key to decrypt.)
    success = if (cert.loadByEmailAddress(recipient_email_addr)) true else |_| false;
    if (!success) {
        std.debug.print("{s}\n", .{try cert.getLastErrorText(alloc)});
        return;
    }

    // Specify the certificate to be used for encryption.
    success = if (email.setEncryptCert(cert)) true else |_| false;

    success = if (mailman.sendEmail(email)) true else |_| false;
    if (!success) {
        std.debug.print("{s}\n", .{try mailman.getLastErrorText(alloc)});
    } else {
        std.debug.print("Encrypted Mail Sent!\n", .{});
    }
}