Sample code for 30+ languages & platforms
Zig

Send Email to Distribution List

See more SMTP Examples

Sends the same email to a list of 1000 email addresses in 50 sends where each email has 20 recipients.

Note: Chilkat is not intended nor designed for mass emailing. A solution such as this might be used for a corporate emailing to employees, or an emailing to newsletter subscribers.

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.

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

    mailman.setSmtpHost("smtp.mymailserver.com");
    mailman.setSmtpPort(465);
    mailman.setSmtpSsl(true);
    mailman.setSmtpUsername("myUsername");
    mailman.setSmtpPassword("myPassword");

    // Create a new email object
    const email = try chilkat.Email.init();
    defer email.deinit();
    email.setSubject("This is a test");
    email.setBody("This is a test");
    email.setFrom("Senders Name <sender@example.com>");
    email.addTo("Subscribers", "subscribers@example.com") catch {};

    const bd_mime = try chilkat.BinData.init();
    defer bd_mime.deinit();
    mailman.renderToMimeBd(email, bd_mime) catch {};

    // Load a file containing one email address per line.
    const dist_list = try chilkat.StringTable.init();
    defer dist_list.deinit();
    dist_list.appendFromFile(1000, "utf-8", "qa_data/distList.txt") catch {
        std.debug.print("{s}\n", .{try dist_list.getLastErrorText(alloc)});
        return;
    };

    const sb_recipients = try chilkat.StringBuilder.init();
    defer sb_recipients.deinit();

    var i: i32 = 0;
    const sz_dist_list = dist_list.getCount();
    var j: i32 = 0;
    while (i < sz_dist_list) {
        // Build a list of comma-separated recipients.
        if (j > 0) {
            sb_recipients.append(",") catch {};
        }

        sb_recipients.append(try dist_list.stringAt(alloc, i)) catch {};

        i = i + 1;
        j = j + 1;

        // If we have 20 recipients, or we have the final recipient in the final chunk, then send.
        if ((j == 20) or (i == sz_dist_list)) {
            mailman.sendMimeBd("sender@example.com", try sb_recipients.getAsString(alloc), bd_mime) catch {
                std.debug.print("{s}\n", .{try mailman.getLastErrorText(alloc)});
                return;
            };

            j = 0;
            sb_recipients.clear();
        }
    }

    mailman.closeSmtpConnection() catch {
        std.debug.print("Connection to SMTP server not closed cleanly.\n", .{});
    };

    std.debug.print("Email sent to distirbution list.\n", .{});
}