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 <C_CkHttpW.h>
#include <C_CkStringBuilderW.h>
#include <C_CkJsonObjectW.h>
#include <C_CkEmailW.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkHttpW http;
    const wchar_t *id;
    const wchar_t *userId;
    const wchar_t *url;
    HCkStringBuilderW sbJson;
    HCkJsonObjectW json;
    HCkStringBuilderW sbRaw;
    HCkEmailW email;

    success = FALSE;

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

    http = CkHttpW_Create();
    CkHttpW_putAuthToken(http,L"GMAIL-ACCESS-TOKEN");

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

    CkHttpW_SetUrlVar(http,L"userId",L"me");
    CkHttpW_SetUrlVar(http,L"id",id);

    // Fetch the email.
    url = L"https://www.googleapis.com/gmail/v1/users/{$userId}/messages/{$id}?format=raw";
    sbJson = CkStringBuilderW_Create();
    success = CkHttpW_DownloadSb(http,url,L"utf-8",sbJson);
    if (success != TRUE) {
        wprintf(L"%s\n",CkHttpW_lastErrorText(http));
        CkHttpW_Dispose(http);
        CkStringBuilderW_Dispose(sbJson);
        return;
    }

    json = CkJsonObjectW_Create();
    CkJsonObjectW_LoadSb(json,sbJson);
    CkJsonObjectW_putEmitCompact(json,FALSE);

    if (CkHttpW_getLastStatus(http) != 200) {
        wprintf(L"%s\n",CkJsonObjectW_emit(json));
        wprintf(L"Failed.\n");
        CkHttpW_Dispose(http);
        CkStringBuilderW_Dispose(sbJson);
        CkJsonObjectW_Dispose(json);
        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..
    sbRaw = CkStringBuilderW_Create();
    CkJsonObjectW_StringOfSb(json,L"raw",sbRaw);
    CkStringBuilderW_Decode(sbRaw,L"base64url",L"utf-8");

    email = CkEmailW_Create();
    CkEmailW_SetFromMimeSb(email,sbRaw);

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


    CkHttpW_Dispose(http);
    CkStringBuilderW_Dispose(sbJson);
    CkJsonObjectW_Dispose(json);
    CkStringBuilderW_Dispose(sbRaw);
    CkEmailW_Dispose(email);

    }