Sample code for 30+ languages & platforms
Visual FoxPro Requires Chilkat v11.1.0+

Gmail IMAP: Read, Add, or Remove Message Labels

See more GMail SMTP/IMAP/POP Examples

Locate a message in INBOX by its decimal Gmail message ID, then read its labels or add/remove one custom label with X-GM-LABELS. The default action is read. Changing action to add or remove modifies the mailbox. Obtain the message ID from the message and thread IDs example.

The code changes only the specified custom label and preserves other labels. A message shown under several labels is still one Gmail message. System labels have different semantics; use the archive/Trash example for those operations. If the message left INBOX, select its current mailbox before searching.

This focused raw-command example accepts printable ASCII custom labels beginning with a letter or digit, escapes quotes and backslashes, and displays the returned label list in IMAP syntax. Non-ASCII names require IMAP modified UTF-7 encoding. The response is not parsed by splitting on spaces because quoted names can contain spaces.

Use the mailbox that authorized the full-mail scope https://mail.google.com/. Obtain the protocol OAuth token and refresh it before running this example. The token is loaded from gmail-mail-token.json in a private working directory; a narrow Gmail REST token is insufficient.

Google documentation

Chilkat Visual FoxPro Downloads

Visual FoxPro
LOCAL lnSuccess
LOCAL lnReplacements
LOCAL loStatusText
LOCAL loStatusMatch
LOCAL lnCompleted
LOCAL loToken
LOCAL lcMailbox
LOCAL loImap
LOCAL lcCapabilities
LOCAL lcGmailMessageId
LOCAL loIdText
LOCAL loValidation
LOCAL lnMatches
LOCAL loTarget
LOCAL loJoined1
LOCAL lcUid
LOCAL lcAction
LOCAL lcLabel
LOCAL loLabelText
LOCAL lcResponse
LOCAL lcCommand
LOCAL lcOperation
LOCAL loJoined2
LOCAL loJoined3

lnSuccess = 0

*  Assumes Chilkat is unlocked. See Global Unlock Sample.

loStatusText = CreateObject('Chilkat.StringBuilder')
loStatusMatch = CreateObject('Chilkat.JsonObject')

loToken = CreateObject('Chilkat.JsonObject')
lnSuccess = loToken.LoadFile("gmail-mail-token.json")
IF (lnSuccess <> 1) THEN
    ? "Could not load the protocol token from the private working directory."
    RELEASE loStatusText
    RELEASE loStatusMatch
    RELEASE loToken
    CANCEL
ENDIF

IF ((loToken.JsonTypeOf("access_token") <> 1) OR (loToken.StringOfEquals("access_token","",1) = 1)) THEN
    ? "Authorize or refresh the mailbox first."
    RELEASE loStatusText
    RELEASE loStatusMatch
    RELEASE loToken
    CANCEL
ENDIF

lcMailbox = "user@example.com"
loImap = CreateObject('Chilkat.Imap')
loImap.Ssl = 1
loImap.Port = 993
loImap.RequireSslCertVerify = 1
loImap.AuthMethod = "XOAUTH2"
lnSuccess = loImap.Connect("imap.gmail.com")
IF (lnSuccess <> 1) THEN
    ? "Could not establish the Gmail IMAP TLS connection."
    RELEASE loStatusText
    RELEASE loStatusMatch
    RELEASE loToken
    RELEASE loImap
    CANCEL
ENDIF

lnSuccess = loImap.Login(lcMailbox,loToken.StringOf("access_token"))
IF (lnSuccess <> 1) THEN
    loImap.Disconnect()
    ? "IMAP authentication failed. Check the mailbox, scope, expiry, and account policy."
    RELEASE loStatusText
    RELEASE loStatusMatch
    RELEASE loToken
    RELEASE loImap
    CANCEL
ENDIF

lcCapabilities = loImap.Capability()
IF ((loImap.LastMethodSuccess <> 1) OR (loImap.HasCapability("X-GM-EXT-1",lcCapabilities) <> 1)) THEN
    loImap.Logout()
    loImap.Disconnect()
    ? "Gmail IMAP extensions are unavailable."
    RELEASE loStatusText
    RELEASE loStatusMatch
    RELEASE loToken
    RELEASE loImap
    CANCEL
ENDIF

lnSuccess = loImap.SelectMailbox("INBOX")
IF (lnSuccess <> 1) THEN
    loImap.Logout()
    loImap.Disconnect()
    ? "Could not open INBOX."
    RELEASE loStatusText
    RELEASE loStatusMatch
    RELEASE loToken
    RELEASE loImap
    CANCEL
ENDIF

*  Obtain this decimal string from the Gmail message/thread ID example.
lcGmailMessageId = "1278455344230334865"
loIdText = CreateObject('Chilkat.StringBuilder')
loIdText.Append(lcGmailMessageId)
loValidation = CreateObject('Chilkat.JsonObject')
lnMatches = loIdText.RegexMatch("\A[1-9][0-9]{0,19}\z",loValidation,1000)
IF (lnMatches <> 1) THEN
    loImap.Logout()
    loImap.Disconnect()
    ? "Expected a decimal Gmail message ID string."
    RELEASE loStatusText
    RELEASE loStatusMatch
    RELEASE loToken
    RELEASE loImap
    RELEASE loIdText
    RELEASE loValidation
    CANCEL
ENDIF

loTarget = CreateObject('Chilkat.MessageSet')
loJoined1 = CreateObject('Chilkat.StringBuilder')
loJoined1.Append("X-GM-MSGID ")
loJoined1.Append(lcGmailMessageId)
lnSuccess = loImap.QueryMbx(loJoined1.GetAsString(),1,loTarget)
IF (lnSuccess <> 1) THEN
    loImap.Logout()
    loImap.Disconnect()
    ? "Could not find the Gmail message in the selected mailbox."
    RELEASE loStatusText
    RELEASE loStatusMatch
    RELEASE loToken
    RELEASE loImap
    RELEASE loIdText
    RELEASE loValidation
    RELEASE loTarget
    RELEASE loJoined1
    CANCEL
ENDIF

IF (loTarget.Count <> 1) THEN
    loImap.Logout()
    loImap.Disconnect()
    ? "Expected one message in the selected mailbox. Matches: " + STR(loTarget.Count)
    RELEASE loStatusText
    RELEASE loStatusMatch
    RELEASE loToken
    RELEASE loImap
    RELEASE loIdText
    RELEASE loValidation
    RELEASE loTarget
    RELEASE loJoined1
    CANCEL
ENDIF

lcUid = loTarget.ToCompactString()
*  Choose read, add, or remove. Only add/remove changes the message.
lcAction = "read"
lcLabel = "Example label"
IF ((lcAction <> "read") AND (lcAction <> "add") AND (lcAction <> "remove")) THEN
    loImap.Logout()
    loImap.Disconnect()
    ? "Choose read, add, or remove."
    RELEASE loStatusText
    RELEASE loStatusMatch
    RELEASE loToken
    RELEASE loImap
    RELEASE loIdText
    RELEASE loValidation
    RELEASE loTarget
    RELEASE loJoined1
    CANCEL
ENDIF

loLabelText = CreateObject('Chilkat.StringBuilder')
loLabelText.Append(lcLabel)
*  This raw-command example accepts printable ASCII custom labels only.
*  For non-ASCII labels, encode modified UTF-7 before quoting the command argument.
lnMatches = loLabelText.RegexMatch("\A[A-Za-z0-9][\x20-\x7e]*\z",loValidation,1000)
IF (lnMatches <> 1) THEN
    loImap.Logout()
    loImap.Disconnect()
    ? "Use a printable ASCII custom label starting with a letter or digit."
    RELEASE loStatusText
    RELEASE loStatusMatch
    RELEASE loToken
    RELEASE loImap
    RELEASE loIdText
    RELEASE loValidation
    RELEASE loTarget
    RELEASE loJoined1
    RELEASE loLabelText
    CANCEL
ENDIF

lnReplacements = loLabelText.Replace("\","\\")
lnReplacements = loLabelText.Replace('"','\"')

IF (lcAction <> "read") THEN
    lcOperation = "+X-GM-LABELS.SILENT"
    IF (lcAction = "remove") THEN
        lcOperation = "-X-GM-LABELS.SILENT"
    ENDIF

    loJoined2 = CreateObject('Chilkat.StringBuilder')
    loJoined2.Append("UID STORE ")
    loJoined2.Append(lcUid)
    loJoined2.Append(" ")
    loJoined2.Append(lcOperation)
    loJoined2.Append(' ("')
    loJoined2.Append(loLabelText.GetAsString())
    loJoined2.Append('")')
    lcCommand = loJoined2.GetAsString()
    lcResponse = loImap.SendRawCommand(lcCommand)
    loStatusText.SetString(lcResponse)
    *  A completed raw exchange can still return NO or BAD. Require tagged OK.
    lnCompleted = loStatusText.RegexMatch("(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z",loStatusMatch,1000)

    IF ((loImap.LastMethodSuccess <> 1) OR (lnCompleted <> 1)) THEN
        loImap.Logout()
        loImap.Disconnect()
        ? "Label update failed. Check the custom label and mailbox permissions."
        RELEASE loStatusText
        RELEASE loStatusMatch
        RELEASE loToken
        RELEASE loImap
        RELEASE loIdText
        RELEASE loValidation
        RELEASE loTarget
        RELEASE loJoined1
        RELEASE loLabelText
        RELEASE loJoined2
        CANCEL
    ENDIF

ENDIF

loJoined3 = CreateObject('Chilkat.StringBuilder')
loJoined3.Append("UID FETCH ")
loJoined3.Append(lcUid)
loJoined3.Append(" (X-GM-LABELS)")
lcResponse = loImap.SendRawCommand(loJoined3.GetAsString())
loStatusText.SetString(lcResponse)
*  A completed raw exchange can still return NO or BAD. Require tagged OK.
lnCompleted = loStatusText.RegexMatch("(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z",loStatusMatch,1000)

IF ((loImap.LastMethodSuccess <> 1) OR (lnCompleted <> 1)) THEN
    loImap.Logout()
    loImap.Disconnect()
    ? "Could not read the message labels."
    RELEASE loStatusText
    RELEASE loStatusMatch
    RELEASE loToken
    RELEASE loImap
    RELEASE loIdText
    RELEASE loValidation
    RELEASE loTarget
    RELEASE loJoined1
    RELEASE loLabelText
    RELEASE loJoined2
    RELEASE loJoined3
    CANCEL
ENDIF

*  Display the server's label-list syntax, including quoted/encoded names.
*  This is a FETCH response, not an authentication/session log.
? lcResponse
loImap.Logout()
loImap.Disconnect()

RELEASE loStatusText
RELEASE loStatusMatch
RELEASE loToken
RELEASE loImap
RELEASE loIdText
RELEASE loValidation
RELEASE loTarget
RELEASE loJoined1
RELEASE loLabelText
RELEASE loJoined2
RELEASE loJoined3