Sample code for 30+ languages & platforms
CkPerl Requires Chilkat v11.1.0+

Gmail IMAP: Read, Add, or Remove Message Labels

See more GMail SMTP/IMAP/POP Examples

Locate a message in INBOX by its decimal Gmail message ID, then read its labels or add/remove one custom label with X-GM-LABELS. The default action is read. Changing action to add or remove modifies the mailbox. Obtain the message ID from the message and thread IDs example.

The code changes only the specified custom label and preserves other labels. A message shown under several labels is still one Gmail message. System labels have different semantics; use the archive/Trash example for those operations. If the message left INBOX, select its current mailbox before searching.

This focused raw-command example accepts printable ASCII custom labels beginning with a letter or digit, escapes quotes and backslashes, and displays the returned label list in IMAP syntax. Non-ASCII names require IMAP modified UTF-7 encoding. The response is not parsed by splitting on spaces because quoted names can contain spaces.

Use the mailbox that authorized the full-mail scope https://mail.google.com/. Obtain the protocol OAuth token and refresh it before running this example. The token is loaded from gmail-mail-token.json in a private working directory; a narrow Gmail REST token is insufficient.

Google documentation

Chilkat CkPerl Downloads

CkPerl
use chilkat();

$success = 0;

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

$statusText = chilkat::CkStringBuilder->new();
$statusMatch = chilkat::CkJsonObject->new();

$token = chilkat::CkJsonObject->new();
$success = $token->LoadFile("gmail-mail-token.json");
if ($success != 1) {
    print "Could not load the protocol token from the private working directory." . "\r\n";
    exit;
}

if (($token->JsonTypeOf("access_token") != 1) or ($token->StringOfEquals("access_token","",1) == 1)) {
    print "Authorize or refresh the mailbox first." . "\r\n";
    exit;
}

$mailbox = 'user@example.com';
$imap = chilkat::CkImap->new();
$imap->put_Ssl(1);
$imap->put_Port(993);
$imap->put_RequireSslCertVerify(1);
$imap->put_AuthMethod("XOAUTH2");
$success = $imap->Connect("imap.gmail.com");
if ($success != 1) {
    print "Could not establish the Gmail IMAP TLS connection." . "\r\n";
    exit;
}

$success = $imap->Login($mailbox,$token->stringOf("access_token"));
if ($success != 1) {
    $imap->Disconnect();
    print "IMAP authentication failed. Check the mailbox, scope, expiry, and account policy." . "\r\n";
    exit;
}

$capabilities = $imap->capability();
if (($imap->get_LastMethodSuccess() != 1) or ($imap->HasCapability("X-GM-EXT-1",$capabilities) != 1)) {
    $imap->Logout();
    $imap->Disconnect();
    print "Gmail IMAP extensions are unavailable." . "\r\n";
    exit;
}

$success = $imap->SelectMailbox("INBOX");
if ($success != 1) {
    $imap->Logout();
    $imap->Disconnect();
    print "Could not open INBOX." . "\r\n";
    exit;
}

#  Obtain this decimal string from the Gmail message/thread ID example.
$gmailMessageId = "1278455344230334865";
$idText = chilkat::CkStringBuilder->new();
$idText->Append($gmailMessageId);
$validation = chilkat::CkJsonObject->new();
$matches = $idText->RegexMatch("\\A[1-9][0-9]{0,19}\\z",$validation,1000);
if ($matches != 1) {
    $imap->Logout();
    $imap->Disconnect();
    print "Expected a decimal Gmail message ID string." . "\r\n";
    exit;
}

$target = chilkat::CkMessageSet->new();
$joined1 = chilkat::CkStringBuilder->new();
$joined1->Append("X-GM-MSGID ");
$joined1->Append($gmailMessageId);
$success = $imap->QueryMbx($joined1->getAsString(),1,$target);
if ($success != 1) {
    $imap->Logout();
    $imap->Disconnect();
    print "Could not find the Gmail message in the selected mailbox." . "\r\n";
    exit;
}

if ($target->get_Count() != 1) {
    $imap->Logout();
    $imap->Disconnect();
    print "Expected one message in the selected mailbox. Matches: " . $target->get_Count() . "\r\n";
    exit;
}

$uid = $target->toCompactString();
#  Choose read, add, or remove. Only add/remove changes the message.
$action = "read";
$label = "Example label";
if (($action != "read") and ($action != "add") and ($action != "remove")) {
    $imap->Logout();
    $imap->Disconnect();
    print "Choose read, add, or remove." . "\r\n";
    exit;
}

$labelText = chilkat::CkStringBuilder->new();
$labelText->Append($label);
#  This raw-command example accepts printable ASCII custom labels only.
#  For non-ASCII labels, encode modified UTF-7 before quoting the command argument.
$matches = $labelText->RegexMatch("\\A[A-Za-z0-9][\\x20-\\x7e]*\\z",$validation,1000);
if ($matches != 1) {
    $imap->Logout();
    $imap->Disconnect();
    print "Use a printable ASCII custom label starting with a letter or digit." . "\r\n";
    exit;
}

$replacements = $labelText->Replace("\\","\\\\");
$replacements = $labelText->Replace("\"","\\\"");

if ($action != "read") {
    $operation = "+X-GM-LABELS.SILENT";
    if ($action == "remove") {
        $operation = "-X-GM-LABELS.SILENT";
    }

    $joined2 = chilkat::CkStringBuilder->new();
    $joined2->Append("UID STORE ");
    $joined2->Append($uid);
    $joined2->Append(" ");
    $joined2->Append($operation);
    $joined2->Append(" (\"");
    $joined2->Append($labelText->getAsString());
    $joined2->Append("\")");
    $command = $joined2->getAsString();
    $response = $imap->sendRawCommand($command);
    $statusText->SetString($response);
    #  A completed raw exchange can still return NO or BAD. Require tagged OK.
    $completed = $statusText->RegexMatch("(?i)(?:\\A|\\r\\n)[^*+ \\r\\n]+ OK[^\\r\\n]*\\r?\\n?\\z",$statusMatch,1000);

    if (($imap->get_LastMethodSuccess() != 1) or ($completed != 1)) {
        $imap->Logout();
        $imap->Disconnect();
        print "Label update failed. Check the custom label and mailbox permissions." . "\r\n";
        exit;
    }

}

$joined3 = chilkat::CkStringBuilder->new();
$joined3->Append("UID FETCH ");
$joined3->Append($uid);
$joined3->Append(" (X-GM-LABELS)");
$response = $imap->sendRawCommand($joined3->getAsString());
$statusText->SetString($response);
#  A completed raw exchange can still return NO or BAD. Require tagged OK.
$completed = $statusText->RegexMatch("(?i)(?:\\A|\\r\\n)[^*+ \\r\\n]+ OK[^\\r\\n]*\\r?\\n?\\z",$statusMatch,1000);

if (($imap->get_LastMethodSuccess() != 1) or ($completed != 1)) {
    $imap->Logout();
    $imap->Disconnect();
    print "Could not read the message labels." . "\r\n";
    exit;
}

#  Display the server's label-list syntax, including quoted/encoded names.
#  This is a FETCH response, not an authentication/session log.
print $response . "\r\n";
$imap->Logout();
$imap->Disconnect();