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

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.

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

'  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.
Dim response As String = imap.LastResponse
Dim responseCode As String = imap.LastResponseCode
imap.Logout
imap.Disconnect
If success = True Then
    Log("That mailbox exists. Choose an absent name to demonstrate a server error.")
    Return
End If

Log("LastResponseCode: " & responseCode)
Log("LastResponse: " & response)
'  A local failure before a command is sent can leave an earlier response here.
'  Inspect LastErrorText privately when diagnosing transport or local failures.