Tcl GMail: Search for Messages with Subject Containing a Word

Back to Index

Return messages matching the specified query. See https://support.google.com/mail/answer/7190?hl=en for additional information about search operators. This example searches for all emails having the whole word "ADVChina" in the subject.

Documentation: https://support.google.com/mail/answer/7190?hl=en

CURL Command

curl -X GET https://www.googleapis.com/gmail/v1/users/me/messages?q=subject:ADVChina \
    --header "Authorization: Bearer GMAIL_TOKEN"

Tcl Example


load ./chilkat.dll

set rest [new_CkRest]

#  URL: https://www.googleapis.com/gmail/v1/users/me/messages?q=subject:ADVChina
set bTls 1
set port 443
set bAutoReconnect 1
set success [CkRest_Connect $rest "www.googleapis.com" $port $bTls $bAutoReconnect]
if {[expr $success != 1]} then {
    puts "ConnectFailReason: [CkRest_get_ConnectFailReason $rest]"
    puts [CkRest_lastErrorText $rest]
    delete_CkRest $rest
    exit
}

CkRest_AddHeader $rest "Authorization" "Bearer GMAIL_TOKEN"

set sbResponseBody [new_CkStringBuilder]

set success [CkRest_FullRequestNoBodySb $rest "GET" "/gmail/v1/users/me/messages?q=subject:ADVChina" $sbResponseBody]
if {[expr $success != 1]} then {
    puts [CkRest_lastErrorText $rest]
    delete_CkRest $rest
    delete_CkStringBuilder $sbResponseBody
    exit
}

set respStatusCode [CkRest_get_ResponseStatusCode $rest]
if {[expr $respStatusCode >= 400]} then {
    puts "Response Status Code = $respStatusCode"
    puts "Response Header:"
    puts [CkRest_responseHeader $rest]
    puts "Response Body:"
    puts [CkStringBuilder_getAsString $sbResponseBody]
    delete_CkRest $rest
    delete_CkStringBuilder $sbResponseBody
    exit
}

set jsonResponse [new_CkJsonObject]

CkJsonObject_LoadSb $jsonResponse $sbResponseBody

#  See the Online Tool for Generating JSON Parse Code

set resultSizeEstimate [CkJsonObject_IntOf $jsonResponse "resultSizeEstimate"]
set i 0
set count_i [CkJsonObject_SizeOfArray $jsonResponse "messages"]
while {[expr $i < $count_i]} {
    CkJsonObject_put_I $jsonResponse $i
    set id [CkJsonObject_stringOf $jsonResponse "messages[i].id"]
    set threadId [CkJsonObject_stringOf $jsonResponse "messages[i].threadId"]
    set i [expr $i + 1]
}

delete_CkRest $rest
delete_CkStringBuilder $sbResponseBody
delete_CkJsonObject $jsonResponse

Sample JSON Response Body

{
  "messages": [
    {
      "id": "166e50fed0b9b0cb",
      "threadId": "166e50fed0b9b0cb"
    },
    {
      "id": "166c12e5fee013fe",
      "threadId": "166c12e5fee013fe"
    },
    {
      "id": "1669cc9a926bb8c1",
      "threadId": "1669cc9a926bb8c1"
    },
    {
      "id": "16678c485e7f0a0c",
      "threadId": "16678c485e7f0a0c"
    }
  ],
  "resultSizeEstimate": 4
}