Sample code for 30+ languages & platforms
Zig

Using Replace Patterns in Email

See more Email Object Examples

Demonstrates how to use the replace patterns (mail-merge) feature in Chilkat MailMan.

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

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

    // ---------------------------------------------------------------------
    // Create an email template for sending.
    const email_template = try chilkat.Email.init();
    defer email_template.deinit();

    // We're going to replace "FIRST_NAME" with an actual name.
    // We arbitrarily chose "FIRST_NAME".  We can choose anything, such as "CUSTOMER_NAME" or "THE_RECIPIENT_NAME"...
    email_template.setSubject("Hello FIRST_NAME,");

    email_template.setFrom("john@example.com");
    email_template.addTo("FIRST_NAME", "RECIPIENT_EMAIL") catch {};

    email_template.setHtmlBody("<html><body><h2>Hello FIRST_NAME,</h2><p>Your order for PRODUCT_NAME has been shipped.</p></body></html>");

    // If the email is saved to a file, we can see what it contains:
    email_template.saveEml("qa_output/emailTemplate.eml") catch {};

    // For example:

    // MIME-Version: 1.0
    // Date: Tue, 26 Apr 2022 07:10:52 -0500
    // Message-ID: <715CF231A9F07B0B9FDB073518CD94138D791866@XYZ>
    // Content-Type: text/html; charset=us-ascii
    // Content-Transfer-Encoding: 7bit
    // X-Priority: 3 (Normal)
    // Subject: Hello FIRST_NAME,
    // From: john@example.com
    // To: FIRST_NAME <RECIPIENT_EMAIL>
    //
    // <html><body><h2>Hello FIRST_NAME,</h2><p>Your order for PRODUCT_NAME has been shipped.</p></body></html>

    // ---------------------------------------------------------------------
    // Demonstrate replace patterns by setting and then rendering to MIME.

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

    email_template.setReplacePattern("FIRST_NAME", "Elon") catch {};
    email_template.setReplacePattern("RECIPIENT_EMAIL", "elon.musk@example.com") catch {};
    email_template.setReplacePattern("PRODUCT_NAME", "Twitter Corporation") catch {};

    // Render to MIME to see what we get.
    // Note: When the MailMan sends an email, it renders the email to MIME and then sends.
    // The rendering process is to do replacements, or possibly sign, encrypt, etc.
    // When MailMan.SendEmail is called, internally the email is rendered, and the rendered email is sent.
    // The equivalent to MailMan.Send email is to call email.RenderToMime followed by MailMan.SendMime.
    const mime = try mailman.renderToMime(alloc, email_template);
    std.debug.print("{s}\n", .{mime});

    // This is the rendered MIME:

    // MIME-Version: 1.0
    // Date: Tue, 26 Apr 2022 07:25:49 -0500
    // Message-ID: <750582BCDC891C67B48CEE2293C08B902C3891E9@XYZ>
    // Content-Type: text/html; charset=us-ascii
    // Content-Transfer-Encoding: 7bit
    // X-Priority: 3 (Normal)
    // Subject: Hello Elon,
    // From: john@example.com
    // To: Elon <elon.musk@example.com>
    //
    // <html><body><h2>Hello Elon,</h2><p>Your order for Twitter Corporation has been shipped.</p></body></html>

    // Note: When rendering, the Date and Message-ID headers are automatically regenerated.

    // ---------------------------------------------------------------------
    // An application can see what replacement patterns it previously set by calling SetReplacePattern multiple times.
    var count: i32 = email_template.getNumReplacePatterns();
    std.debug.print("Number of replace patterns: {d}\n", .{count});

    var i: i32 = 0;
    while (i < count) {
        // Note: The GetReplaceString method was found to not be working correctly.  It was returning the same value as GetReplacePattern.
        // It is fixed in Chilkat v9.5.0.91
        std.debug.print("{s}: {s}\n", .{ try email_template.getReplacePattern(alloc, i), try email_template.getReplaceString(alloc, i) });
        i = i + 1;
    }

    // Or lookup a replacement pattern by name:
    const name = "FIRST_NAME";
    std.debug.print("{s} = {s}\n", .{ name, try email_template.getReplaceString2(alloc, name) });

    // Sample output:

    // Number of replace patterns: 3
    // FIRST_NAME: Elon
    // RECIPIENT_EMAIL: elon.musk@example.com
    // PRODUCT_NAME: Twitter Corporation
    // FIRST_NAME = Elon

    // ---------------------------------------------------------------------
    // Finally... demonstrate sending emails using the replacement patterns.
    //

    // Set our mail server settings..
    mailman.setSmtpHost("smtp.mail.us-west-2.awsapps.com");
    mailman.setSmtpSsl(true);
    mailman.setSmtpPort(465);

    mailman.setSmtpUsername("john@example.com");
    mailman.setSmtpPassword("the_password");

    // Imagine we have data in JSON format, and we wish to send the templated email to each recipient...
    //

    // {
    //     "mail_merge" : [
    //         {
    //             "to": "mary@example.com",
    //             "name": "Mary",
    //             "product": "Widget 1"
    //         },
    //         {
    //             "to": "robert@example.com",
    //             "name": "Robert",
    //             "product": "Widget 2"
    //         }
    //         ...
    //     ]
    // }

    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    json.loadFile("qa_data/json/mail_merge.json") catch {
        std.debug.print("{s}\n", .{try json.getLastErrorText(alloc)});
        return;
    };

    var email_addr: [:0]const u8 = "";
    var first_name: [:0]const u8 = "";
    var product: [:0]const u8 = "";

    i = 0;
    count = json.sizeOfArray("mail_merge");
    while (i < count) {
        json.setI(i);
        email_addr = try json.stringOf(alloc, "mail_merge[i].to");
        first_name = try json.stringOf(alloc, "mail_merge[i].name");
        product = try json.stringOf(alloc, "mail_merge[i].product");

        email_template.setReplacePattern("FIRST_NAME", first_name) catch {};
        email_template.setReplacePattern("RECIPIENT_EMAIL", email_addr) catch {};
        email_template.setReplacePattern("PRODUCT_NAME", product) catch {};

        mailman.sendEmail(email_template) catch {
            std.debug.print("{s}\n", .{try mailman.getLastErrorText(alloc)});
            return;
        };

        std.debug.print("Send email to {s}\n", .{email_addr});

        i = i + 1;
    }

    std.debug.print("Success.\n", .{});
}