Zig
Zig
Send HTML Email with Attachments
See more SMTP Examples
Demonstrates how to send an HTML email with file attachments.Chilkat Zig Downloads
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.my-starttls-mail-server.com");
mailman.setSmtpUsername("MY-SMTP-USERNAME");
mailman.setSmtpPassword("MY-SMTP-PASSWORD");
mailman.setStartTLS(true);
mailman.setSmtpPort(587);
// Create a new email object
const email = try chilkat.Email.init();
defer email.deinit();
email.setSubject("Test SMTP API to Send HTML Email with Attachments");
email.setFrom("Joe Programmer <joe@my-starttls-mail-server.com>");
email.addTo("Chilkat Support", "support@chilkatsoft.com") catch {};
// Add a plain-text alternative body, which will likely never be seen.
// (It is shown if the receiving email client is incapable of displaying HTML email.)
email.addPlainTextAlternativeBody("This is a plain-text alternative body...") catch {};
// Our HTML will include an image, so add the related image here.
const content_id_starfish = email.addRelatedFile(alloc, "qa_data/jpg/starfish.jpg") catch {
std.debug.print("{s}\n", .{try email.getLastErrorText(alloc)});
return;
};
// The src attribute for the image tag is set to the contentIdStarfish:
const sb_html = try chilkat.StringBuilder.init();
defer sb_html.deinit();
sb_html.append("<html><body><p>This is an HTML email with an embedded image.</p>") catch {};
sb_html.append("<p><img src=\"cid:CONTENT_ID_STARFISH\" /></p></body></html>") catch {};
_ = sb_html.replace("CONTENT_ID_STARFISH", content_id_starfish);
email.addHtmlAlternativeBody(try sb_html.getAsString(alloc)) catch {};
// Finally, add some attachments to the email.
// Add a file attachment.
email.addFileAttachment2("qa_data/pdf/fishing.pdf", "application/pdf") catch {
std.debug.print("{s}\n", .{try email.getLastErrorText(alloc)});
return;
};
// Add an attachment where the content is contained in a string.
const content = "This is the content of the 2nd attached file.";
email.addStringAttachment("someText.txt", content) catch {};
// Send the HTML email.
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("HTML email with attachments sent!\n", .{});
}