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

Gmail IMAP: Archive a Message or Move It to Trash

See more GMail SMTP/IMAP/POP Examples

This example changes one message in INBOX. Choose archive to move it to the discovered All Mail folder, or trash to move it to the discovered Trash folder. It resolves a decimal Gmail message ID to a mailbox UID and uses MoveMessages with the server's MOVE capability.

Archiving removes a message from INBOX while retaining it in All Mail. Moving it to Trash is a different action; Gmail normally permanently deletes messages after 30 days there. This example does not empty Trash or permanently delete mail. A message can retain other custom labels when archived.

Folder names are discovered by special-use attributes. Avoid a generic delete/EXPUNGE sequence whose Gmail outcome can depend on account settings and which can affect unrelated messages. If a connection fails during a move, inspect the source and destination before retrying. A concurrent move or deletion can make the UID disappear.

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 PHP ActiveX Downloads

PHP ActiveX
<?php

$success = 0;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.

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

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

$mailbox = 'user@example.com';
$imap = new COM("Chilkat.Imap");
$imap->Ssl = 1;
$imap->Port = 993;
$imap->RequireSslCertVerify = 1;
$imap->AuthMethod = 'XOAUTH2';
$success = $imap->Connect('imap.gmail.com');
if ($success != 1) {
    print 'Could not establish the Gmail IMAP TLS connection.' . "\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.' . "\n";
    exit;
}

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

//  Choose archive or trash. This example changes one message's location.
$action = 'archive';
if (($action != 'archive') and ($action != 'trash')) {
    $imap->Logout();
    $imap->Disconnect();
    print 'Choose archive or trash.' . "\n";
    exit;
}

if ($imap->HasCapability('MOVE',$capabilities) != 1) {
    $imap->Logout();
    $imap->Disconnect();
    print 'The server must support IMAP MOVE.' . "\n";
    exit;
}

$folders = new COM("Chilkat.Mailboxes");
$success = $imap->MbxList(0,'','*',$folders);
if ($success != 1) {
    $imap->Logout();
    $imap->Disconnect();
    print 'Could not list Gmail folders.' . "\n";
    exit;
}

$role = '\\All';
if ($action == 'trash') {
    $role = '\\Trash';
}

$destination = '';
$count = 0;
$i = 0;
while (($i < $folders->Count)) {
    if (($folders->HasFlag($i,$role) == 1) and ($folders->IsSelectable($i) == 1)) {
        $destination = $folders->getName($i);
        $count = $count + 1;
    }

    $i = $i + 1;
}

if ($count != 1) {
    $imap->Logout();
    $imap->Disconnect();
    print 'Could not identify the destination folder uniquely.' . "\n";
    exit;
}

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

//  Obtain this decimal string from the Gmail message/thread ID example.
$gmailMessageId = '1278455344230334865';
$idText = new COM("Chilkat.StringBuilder");
$idText->Append($gmailMessageId);
$validation = new COM("Chilkat.JsonObject");
$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.' . "\n";
    exit;
}

$target = new COM("Chilkat.MessageSet");
$joined1 = new COM("Chilkat.StringBuilder");
$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.' . "\n";
    exit;
}

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

$uid = $target->toCompactString();
//  MoveMessages uses UID MOVE and maintains the Imap object's mailbox state.
//  No broad EXPUNGE is issued, and unrelated deleted flags are not committed.
$success = $imap->MoveMessages($target,$destination);
if ($success != 1) {
    $imap->Logout();
    $imap->Disconnect();
    print 'Move failed; verify the mailbox state before retrying after a connection loss.' . "\n";
    exit;
}

print 'Completed ' . $action . ' for Gmail message ' . $gmailMessageId . "\n";
$imap->Logout();
$imap->Disconnect();

?>