Sample code for 30+ languages & platforms
Unicode C++

SendGrid HTML Email with Embedded Images

See more SendGrid Examples

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

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkHttpRequestW.h>
#include <CkHttpW.h>
#include <CkBinDataW.h>
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkHttpResponseW.h>

void ChilkatSample(void)
    {
    bool success = false;

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

    CkHttpRequestW req;
    CkHttpW http;

    // 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;" />
    CkBinDataW bdJpg;
    success = bdJpg.LoadFile(L"qa_data/jpg/starfish.jpg");
    if (success == false) {
        wprintf(L"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.
    CkStringBuilderW sbHtml;
    sbHtml.Append(L"<html><body><b>This is a test<b><br /><img src=\"data:image/jpeg;base64,");
    // Append the base64 image data to sbHtml.
    bdJpg.GetEncodedSb(L"base64",sbHtml);
    sbHtml.Append(L"\" alt=\"\" style=\"border-width:0px;\" /></body></html>");

    CkJsonObjectW json;
    json.UpdateString(L"personalizations[0].to[0].email",L"matt@chilkat.io");
    json.UpdateString(L"personalizations[0].to[0].name",L"Matt");
    json.UpdateString(L"from.email",L"admin@chilkatsoft.com");
    json.UpdateString(L"subject",L"Test HTML email with images");
    json.UpdateString(L"content[0].type",L"text/html");
    json.UpdateSb(L"content[0].value",sbHtml);

    http.put_AuthToken(L"SENDGRID_API_KEY");

    CkHttpResponseW resp;
    success = http.HttpJson(L"POST",L"https://api.sendgrid.com/v3/mail/send",json,L"application/json",resp);
    if (success == false) {
        wprintf(L"%s\n",http.lastErrorText());
        return;
    }

    wprintf(L"response status code: %d\n",resp.get_StatusCode());
    // 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.)
    wprintf(L"%s\n",resp.bodyStr());
    }