PHP Extension 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"

PHP Extension Example

<?php

// The version number (9_5_0) should match version of the Chilkat extension used, omitting the micro-version number.
// For example, if using Chilkat v9.5.0.48, then include as shown here:
include("chilkat_9_5_0.php");

$rest = new CkRest();

//  URL: https://www.googleapis.com/gmail/v1/users/me/messages?q=subject:ADVChina
$bTls = true;
$port = 443;
$bAutoReconnect = true;
$success = $rest->Connect('www.googleapis.com',$port,$bTls,$bAutoReconnect);
if ($success != true) {
    print 'ConnectFailReason: ' . $rest->get_ConnectFailReason() . "\n";
    print $rest->lastErrorText() . "\n";
    exit;
}

$rest->AddHeader('Authorization','Bearer GMAIL_TOKEN');

$sbResponseBody = new CkStringBuilder();
$success = $rest->FullRequestNoBodySb('GET','/gmail/v1/users/me/messages?q=subject:ADVChina',$sbResponseBody);
if ($success != true) {
    print $rest->lastErrorText() . "\n";
    exit;
}

$respStatusCode = $rest->get_ResponseStatusCode();
if ($respStatusCode >= 400) {
    print 'Response Status Code = ' . $respStatusCode . "\n";
    print 'Response Header:' . "\n";
    print $rest->responseHeader() . "\n";
    print 'Response Body:' . "\n";
    print $sbResponseBody->getAsString() . "\n";
    exit;
}

$jsonResponse = new CkJsonObject();
$jsonResponse->LoadSb($sbResponseBody);

//  See the Online Tool for Generating JSON Parse Code

$resultSizeEstimate = $jsonResponse->IntOf('resultSizeEstimate');
$i = 0;
$count_i = $jsonResponse->SizeOfArray('messages');
while ($i < $count_i) {
    $jsonResponse->put_I($i);
    $id = $jsonResponse->stringOf('messages[i].id');
    $threadId = $jsonResponse->stringOf('messages[i].threadId');
    $i = $i + 1;
}


?>

Sample JSON Response Body

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