IMAP: Capture a Session Log After Authentication
See more IMAP Examples
Use Gmail OAuth2 to demonstrate logging only a read-only EXAMINE exchange. Start logging after successful login, clear any earlier log, capture the result, then disable and clear logging before closing the session.
Authentication logs can contain bearer credentials, and later protocol traffic can contain private mailbox data. Keep diagnostic output private and redact it before sharing. This example deliberately excludes login and message retrieval from its captured log.
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;
}
# Authentication is finished before logging begins.
$imap->ClearSessionLog();
$imap->put_KeepSessionLog(1);
$success = $imap->ExamineMailbox("INBOX");
$diagnostic = $imap->sessionLog();
$imap->put_KeepSessionLog(0);
$imap->ClearSessionLog();
$imap->Logout();
$imap->Disconnect();
if ($success != 1) {
print "EXAMINE failed. Inspect the captured post-login response privately." . "\r\n";
exit;
}
# This limited log contains EXAMINE only, never the authentication exchange.
print $diagnostic . "\r\n";