PureBasic
PureBasic
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 PureBasic Downloads
IncludeFile "CkHttp.pb"
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkJsonObject.pb"
IncludeFile "CkEmail.pb"
Procedure ChilkatExample()
success.i = 0
; This example requires the Chilkat API to have been previously unlocked.
; See Global Unlock Sample for sample code.
http.i = CkHttp::ckCreate()
If http.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkHttp::setCkAuthToken(http, "GMAIL-ACCESS-TOKEN")
; The id of the GMail message to download.
id.s = "166e50fed0b9b0cb"
userId.s = "me"
CkHttp::ckSetUrlVar(http,"userId","me")
CkHttp::ckSetUrlVar(http,"id",id)
; Fetch the email.
url.s = "https://www.googleapis.com/gmail/v1/users/{$userId}/messages/{$id}?format=raw"
sbJson.i = CkStringBuilder::ckCreate()
If sbJson.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
success = CkHttp::ckDownloadSb(http,url,"utf-8",sbJson)
If success <> 1
Debug CkHttp::ckLastErrorText(http)
CkHttp::ckDispose(http)
CkStringBuilder::ckDispose(sbJson)
ProcedureReturn
EndIf
json.i = CkJsonObject::ckCreate()
If json.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkJsonObject::ckLoadSb(json,sbJson)
CkJsonObject::setCkEmitCompact(json, 0)
If CkHttp::ckLastStatus(http) <> 200
Debug CkJsonObject::ckEmit(json)
Debug "Failed."
CkHttp::ckDispose(http)
CkStringBuilder::ckDispose(sbJson)
CkJsonObject::ckDispose(json)
ProcedureReturn
EndIf
; 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.i = CkStringBuilder::ckCreate()
If sbRaw.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkJsonObject::ckStringOfSb(json,"raw",sbRaw)
CkStringBuilder::ckDecode(sbRaw,"base64url","utf-8")
email.i = CkEmail::ckCreate()
If email.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkEmail::ckSetFromMimeSb(email,sbRaw)
; Now we can use the email API to do whatever we desire..
Debug "From: " + CkEmail::ckFromAddress(email)
Debug "Subject: " + CkEmail::ckSubject(email)
; ...
CkHttp::ckDispose(http)
CkStringBuilder::ckDispose(sbJson)
CkJsonObject::ckDispose(json)
CkStringBuilder::ckDispose(sbRaw)
CkEmail::ckDispose(email)
ProcedureReturn
EndProcedure