Sample code for 30+ languages & platforms
Zig

SendGrid HTML Email with Embedded Images

See more SendGrid Examples

Demonstrates how to send an HTML email with embedded images using SendGrid.

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 requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code

    const req = try chilkat.HttpRequest.init();
    defer req.deinit();
    const http = try chilkat.Http.init();
    defer http.deinit();

    // First.. load a JPG file and build an HTML img tag with the JPG data inline encoded.
    // Our HTML img tag will look like this:
    // <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEA3ADcAA..." alt="" style="border-width:0px;" />
    const bd_jpg = try chilkat.BinData.init();
    defer bd_jpg.deinit();
    bd_jpg.loadFile("qa_data/jpg/starfish.jpg") catch {
        std.debug.print("Failed to load JPG file.\n", .{});
        return;
    };

    // Note: HTML containing embedded base64 image data may not be visible in all email clients.
    // For example, GMail might not display the image, but viewing in Outlook might be OK.
    const sb_html = try chilkat.StringBuilder.init();
    defer sb_html.deinit();
    sb_html.append("<html><body><b>This is a test<b><br /><img src=\"data:image/jpeg;base64,") catch {};
    // Append the base64 image data to sbHtml.
    bd_jpg.getEncodedSb("base64", sb_html) catch {};
    sb_html.append("\" alt=\"\" style=\"border-width:0px;\" /></body></html>") catch {};

    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    json.updateString("personalizations[0].to[0].email", "matt@chilkat.io") catch {};
    json.updateString("personalizations[0].to[0].name", "Matt") catch {};
    json.updateString("from.email", "admin@chilkatsoft.com") catch {};
    json.updateString("subject", "Test HTML email with images") catch {};
    json.updateString("content[0].type", "text/html") catch {};
    json.updateSb("content[0].value", sb_html) catch {};

    http.setAuthToken("SENDGRID_API_KEY");

    const resp = try chilkat.HttpResponse.init();
    defer resp.deinit();
    http.httpJson("POST", "https://api.sendgrid.com/v3/mail/send", json, "application/json", resp) catch {
        std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("response status code: {d}\n", .{resp.getStatusCode()});
    // Display the response.
    // If successful, the response code is 202 and the response body string is empty.
    // (The response body string may also be empty for error response codes.)
    std.debug.print("{s}\n", .{try resp.getBodyStr(alloc)});
}