Sample code for 30+ languages & platforms
Zig

Send Email With Attachments

See more SMTP Examples

Demonstrates how to send an email with attachments.

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.

    // The mailman object is used for sending (SMTP) and receiving (POP3) email.
    const mailman = try chilkat.MailMan.init();
    defer mailman.deinit();

    // Set the SMTP server.
    mailman.setSmtpHost("smtp.my-tls-mail-server.com");

    // Set the SMTP login/password (if required)
    mailman.setSmtpUsername("MY_SMTP_USERNAME");
    mailman.setSmtpPassword("MY_SMTP_PASSWORD");

    // Connect to SMTP port 465 using TLS.
    mailman.setSmtpSsl(true);
    mailman.setSmtpPort(465);

    // 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("Chilkat Support <support@chilkatsoft.com>");
    try email.addTo("Chilkat Admin", "admin@chilkatsoft.com");
    // To add more recipients, call AddTo, AddCC, or AddBcc once per recipient.

    // Add some attachments.
    // The AddFileAttachment method returns the value of the content-type it chose for the attachment.
    var content_type: [:0]const u8 = email.addFileAttachment(alloc, "qa_data/jpg/starfish.jpg") catch {
        std.debug.print("{s}\n", .{try email.getLastErrorText(alloc)});
        return;
    };

    content_type = email.addFileAttachment(alloc, "qa_data/pdf/fishing.pdf") catch {
        std.debug.print("{s}\n", .{try email.getLastErrorText(alloc)});
        return;
    };

    // Call SendEmail to connect to the SMTP server and send.
    // The connection (i.e. session) to the SMTP server remains
    // open so that subsequent SendEmail calls may use the
    // same connection.
    mailman.sendEmail(email) catch {
        std.debug.print("{s}\n", .{try mailman.getLastErrorText(alloc)});
        return;
    };

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

    std.debug.print("Mail with attachments sent!\n", .{});
}