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 Tcl Downloads
load ./chilkat.dll
set success 0
# Assumes Chilkat is unlocked. See Global Unlock Sample.
set token [new_CkJsonObject]
set success [CkJsonObject_LoadFile $token "gmail-mail-token.json"]
if {$success != 1} then {
puts "Could not read gmail-mail-token.json from the private working directory."
delete_CkJsonObject $token
exit
}
if {expr [[CkJsonObject_JsonTypeOf $token "access_token"] != 1] || [[CkJsonObject_StringOfEquals $token "access_token" "" 1] == 1]} then {
puts "An OAuth access token is required. Authorize or refresh the account first."
delete_CkJsonObject $token
exit
}
set mailbox "user@example.com"
set imap [new_CkImap]
CkImap_put_Ssl $imap 1
CkImap_put_Port $imap 993
CkImap_put_RequireSslCertVerify $imap 1
CkImap_put_AuthMethod $imap "XOAUTH2"
set success [CkImap_Connect $imap "imap.gmail.com"]
if {$success != 1} then {
puts "Could not establish the Gmail IMAP TLS connection."
delete_CkJsonObject $token
delete_CkImap $imap
exit
}
set success [CkImap_Login $imap $mailbox [CkJsonObject_stringOf $token "access_token"]]
if {$success != 1} then {
CkImap_Disconnect $imap
puts "IMAP authentication failed. Check the mailbox, token scope, expiry, and Workspace policy."
delete_CkJsonObject $token
delete_CkImap $imap
exit
}
# Authentication is finished before logging begins.
CkImap_ClearSessionLog $imap
CkImap_put_KeepSessionLog $imap 1
set success [CkImap_ExamineMailbox $imap "INBOX"]
set diagnostic [CkImap_sessionLog $imap]
CkImap_put_KeepSessionLog $imap 0
CkImap_ClearSessionLog $imap
CkImap_Logout $imap
CkImap_Disconnect $imap
if {$success != 1} then {
puts "EXAMINE failed. Inspect the captured post-login response privately."
delete_CkJsonObject $token
delete_CkImap $imap
exit
}
# This limited log contains EXAMINE only, never the authentication exchange.
puts "$diagnostic"
delete_CkJsonObject $token
delete_CkImap $imap