PHP Requires Chilkat v11.0.0+
PHP
Mark a Gmail message as read or archive it
See more GMail REST API Examples
Choose read or archive and supply a Gmail message ID. Marking a message as read removes UNREAD. Archiving removes INBOX while keeping the message available elsewhere in the mailbox. Each run performs the selected action on one message. Removing a label that is already absent is safe to repeat.
Authorize the application with https://www.googleapis.com/auth/gmail.modify. The example reads the access token from gmail-token.json in a private working directory. Authorize a desktop application.
Chilkat PHP Downloads
<?php
use Chilkat2\Http;
use Chilkat2\HttpResponse;
use Chilkat2\JsonObject;
use Chilkat2\StringBuilder;
$success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
$token = new JsonObject();
try {
$token->LoadFile('gmail-token.json');
} catch (\Chilkat2\Exception $e) {
echo "Could not read gmail-token.json from the private working directory.\n";
exit;
}
if (($token->JsonTypeOf('access_token') != 1) || ($token->StringOfEquals('access_token', '', true))) {
echo "An OAuth access token is required.\n";
exit;
}
$http = new Http();
$http->RequireSslCertVerify = true;
$http->AuthToken = $token->StringOf('access_token');
$resp = new HttpResponse();
$reply = new JsonObject();
$action = 'read';
$request = new JsonObject();
if ($action === 'read') {
try {
$request->UpdateString('removeLabelIds[0]', 'UNREAD');
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
} else {
if ($action !== 'archive') {
echo "Choose read or archive.\n";
exit;
}
try {
$request->UpdateString('removeLabelIds[0]', 'INBOX');
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
}
$url = new StringBuilder();
$url->Append('https://gmail.googleapis.com/gmail/v1/users/me/messages/');
$url->Append('GMAIL_MESSAGE_ID');
$url->Append('/modify');
try {
$http->HttpJson('POST', $url->GetAsString(), $request, 'application/json', $resp);
$success = true;
} catch (\Chilkat2\Exception $e) {
$success = false;
}
if ($resp->StatusCode == 0) {
echo "Gmail did not return an HTTP response.\n";
exit;
}
if ((!$success) || (($resp->StatusCode < 200) || ($resp->StatusCode >= 300))) {
echo 'Gmail HTTP ', $resp->StatusCode, "\n";
try {
$reply->Load($resp->BodyStr);
$success = true;
} catch (\Chilkat2\Exception $e) {
$success = false;
}
if ($success) {
echo $reply->StringOf('error.message'), "\n";
}
exit;
}
try {
$reply->Load($resp->BodyStr);
} catch (\Chilkat2\Exception $e) {
echo "Expected a Gmail JSON response.\n";
exit;
}
if (($reply->JsonTypeOf('id') != 1) || ($reply->StringOfEquals('id', '', true))) {
echo "Expected id in the response.\n";
exit;
}
echo 'Completed ', $action, ' for message ', $reply->StringOf('id'), "\n";