Sample code for 30+ languages & platforms
B4X Requires Chilkat v11.0.0+

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.

Reference documentation

Chilkat B4X Downloads

B4X
Dim success As Boolean = False

'  Assumes Chilkat is unlocked. See Global Unlock Sample.

Dim token As ChilkatJsonObject
token.Initialize
success = token.LoadFile("gmail-mail-token.json")
If success <> True Then
    Log("Could not read gmail-mail-token.json from the private working directory.")
    Return
End If

If (token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token", "", True) = True) Then
    Log("An OAuth access token is required. Authorize or refresh the account first.")
    Return
End If

Dim mailbox As String = "user@example.com"
Dim imap As ChilkatImap
imap.Initialize("imap")
imap.Ssl = True
imap.Port = 993
imap.RequireSslCertVerify = True
imap.AuthMethod = "XOAUTH2"
success = imap.Connect("imap.gmail.com")
If success <> True Then
    Log("Could not establish the Gmail IMAP TLS connection.")
    Return
End If

success = imap.Login(mailbox, token.StringOf("access_token"))
If success <> True Then
    imap.Disconnect
    Log("IMAP authentication failed. Check the mailbox, token scope, expiry, and Workspace policy.")
    Return
End If

'  Authentication is finished before logging begins.
imap.ClearSessionLog
imap.KeepSessionLog = True
success = imap.ExamineMailbox("INBOX")
Dim diagnostic As String = imap.SessionLog
imap.KeepSessionLog = False
imap.ClearSessionLog
imap.Logout
imap.Disconnect
If success <> True Then
    Log("EXAMINE failed. Inspect the captured post-login response privately.")
    Return
End If

'  This limited log contains EXAMINE only, never the authentication exchange.
Log(diagnostic)