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

Download a Specific GMail Message into a Chilkat Email Object

See more GMail REST API Examples

Demonstrates how to download a GMail message into a Chilkat Email object.

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkHttpW.h>
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkEmailW.h>

void ChilkatSample(void)
    {
    bool success = false;

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

    CkHttpW http;
    http.put_AuthToken(L"GMAIL-ACCESS-TOKEN");

    //  The id of the GMail message to download.
    const wchar_t *id = L"166e50fed0b9b0cb";
    const wchar_t *userId = L"me";

    http.SetUrlVar(L"userId",L"me");
    http.SetUrlVar(L"id",id);

    //  Fetch the email.
    const wchar_t *url = L"https://www.googleapis.com/gmail/v1/users/{$userId}/messages/{$id}?format=raw";
    CkStringBuilderW sbJson;
    success = http.DownloadSb(url,L"utf-8",sbJson);
    if (success != true) {
        wprintf(L"%s\n",http.lastErrorText());
        return;
    }

    CkJsonObjectW json;
    json.LoadSb(sbJson);
    json.put_EmitCompact(false);

    if (http.get_LastStatus() != 200) {
        wprintf(L"%s\n",json.emit());
        wprintf(L"Failed.\n");
        return;
    }

    //  The returned JSON contains something like this:

    //  {
    //    "id": "166e50fed0b9b0cb",
    //    "threadId": "166e50fed0b9b0cb",
    //    "labelIds": [
    //      "CATEGORY_SOCIAL",
    //      "INBOX"
    //    ],
    //    "snippet": "...",
    //    "historyId": "582477",
    //    "internalDate": "1541441317000",
    //    "sizeEstimate": 28603,
    //    "raw": "BASE64URL_CONTENT"
    //  }

    //  The RFC822 MIME of the email is contained in the "raw" as a base64URL encoded string.
    //  Let's decode and load into a Chilkat email object..
    CkStringBuilderW sbRaw;
    json.StringOfSb(L"raw",sbRaw);
    sbRaw.Decode(L"base64url",L"utf-8");

    CkEmailW email;
    email.SetFromMimeSb(sbRaw);

    //  Now we can use the email API to do whatever we desire..
    wprintf(L"From: %s\n",email.fromAddress());
    wprintf(L"Subject: %s\n",email.subject());
    //  ...
    }