IMAP: Inspect LastResponse and LastResponseCode
See more IMAP Examples
Authenticate successfully, then examine an intentionally absent mailbox to demonstrate a server rejection without using an invalid password. Capture LastResponse and LastResponseCode immediately, before cleanup overwrites them.
A server may return a response code such as NONEXISTENT, but exact wording and codes vary. These properties are not a substitute for checking the method result: a failure before a command is sent can leave a stale response. Inspect diagnostic errors privately and avoid publishing authentication data.
First authorize the mailbox for https://mail.google.com/ and refresh the token as needed. Read the current token from gmail-mail-token.json in a private working directory. Narrow Gmail REST scopes do not authorize these protocols. Keep the token and authentication logs private.
See the Gmail SMTP, IMAP, and POP3 guide for current authentication choices and Gmail-specific examples.
Chilkat CkPerl Downloads
use chilkat();
$success = 0;
# Assumes Chilkat is unlocked. See Global Unlock Sample.
$token = chilkat::CkJsonObject->new();
$success = $token->LoadFile("gmail-mail-token.json");
if ($success != 1) {
print "Could not read gmail-mail-token.json from the private working directory." . "\r\n";
exit;
}
if (($token->JsonTypeOf("access_token") != 1) or ($token->StringOfEquals("access_token","",1) == 1)) {
print "An OAuth access token is required. Authorize or refresh the account 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, token scope, expiry, and Workspace policy." . "\r\n";
exit;
}
# Choose a mailbox name that does not exist in this test account.
$success = $imap->ExamineMailbox("__example_nonexistent_mailbox__");
# Read these immediately: logout and other commands replace the last response.
$response = $imap->lastResponse();
$responseCode = $imap->lastResponseCode();
$imap->Logout();
$imap->Disconnect();
if ($success == 1) {
print "That mailbox exists. Choose an absent name to demonstrate a server error." . "\r\n";
exit;
}
print "LastResponseCode: " . $responseCode . "\r\n";
print "LastResponse: " . $response . "\r\n";
# A local failure before a command is sent can leave an earlier response here.
# Inspect LastErrorText privately when diagnosing transport or local failures.