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.
Chilkat PureBasic Downloads
IncludeFile "CkMessageSet.pb"
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkJsonObject.pb"
IncludeFile "CkImap.pb"
Procedure ChilkatExample()
success.i = 0
replacements.i
; Assumes Chilkat is unlocked. See Global Unlock Sample.
statusText.i = CkStringBuilder::ckCreate()
If statusText.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
statusMatch.i = CkJsonObject::ckCreate()
If statusMatch.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
completed.i
token.i = CkJsonObject::ckCreate()
If token.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
success = CkJsonObject::ckLoadFile(token,"gmail-mail-token.json")
If success <> 1
Debug "Could not load the protocol token from the private working directory."
CkStringBuilder::ckDispose(statusText)
CkJsonObject::ckDispose(statusMatch)
CkJsonObject::ckDispose(token)
ProcedureReturn
EndIf
If (CkJsonObject::ckJsonTypeOf(token,"access_token") <> 1) OR (CkJsonObject::ckStringOfEquals(token,"access_token","",1) = 1)
Debug "Authorize or refresh the mailbox first."
CkStringBuilder::ckDispose(statusText)
CkJsonObject::ckDispose(statusMatch)
CkJsonObject::ckDispose(token)
ProcedureReturn
EndIf
mailbox.s = "user@example.com"
imap.i = CkImap::ckCreate()
If imap.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkImap::setCkSsl(imap, 1)
CkImap::setCkPort(imap, 993)
CkImap::setCkRequireSslCertVerify(imap, 1)
CkImap::setCkAuthMethod(imap, "XOAUTH2")
success = CkImap::ckConnect(imap,"imap.gmail.com")
If success <> 1
Debug "Could not establish the Gmail IMAP TLS connection."
CkStringBuilder::ckDispose(statusText)
CkJsonObject::ckDispose(statusMatch)
CkJsonObject::ckDispose(token)
CkImap::ckDispose(imap)
ProcedureReturn
EndIf
success = CkImap::ckLogin(imap,mailbox,CkJsonObject::ckStringOf(token,"access_token"))
If success <> 1
CkImap::ckDisconnect(imap)
Debug "IMAP authentication failed. Check the mailbox, scope, expiry, and account policy."
CkStringBuilder::ckDispose(statusText)
CkJsonObject::ckDispose(statusMatch)
CkJsonObject::ckDispose(token)
CkImap::ckDispose(imap)
ProcedureReturn
EndIf
capabilities.s = CkImap::ckCapability(imap)
If (CkImap::ckLastMethodSuccess(imap) <> 1) OR (CkImap::ckHasCapability(imap,"X-GM-EXT-1",capabilities) <> 1)
CkImap::ckLogout(imap)
CkImap::ckDisconnect(imap)
Debug "Gmail IMAP extensions are unavailable."
CkStringBuilder::ckDispose(statusText)
CkJsonObject::ckDispose(statusMatch)
CkJsonObject::ckDispose(token)
CkImap::ckDispose(imap)
ProcedureReturn
EndIf
success = CkImap::ckSelectMailbox(imap,"INBOX")
If success <> 1
CkImap::ckLogout(imap)
CkImap::ckDisconnect(imap)
Debug "Could not open INBOX."
CkStringBuilder::ckDispose(statusText)
CkJsonObject::ckDispose(statusMatch)
CkJsonObject::ckDispose(token)
CkImap::ckDispose(imap)
ProcedureReturn
EndIf
; Obtain this decimal string from the Gmail message/thread ID example.
gmailMessageId.s = "1278455344230334865"
idText.i = CkStringBuilder::ckCreate()
If idText.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkStringBuilder::ckAppend(idText,gmailMessageId)
validation.i = CkJsonObject::ckCreate()
If validation.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
matches.i = CkStringBuilder::ckRegexMatch(idText,"\A[1-9][0-9]{0,19}\z",validation,1000)
If matches <> 1
CkImap::ckLogout(imap)
CkImap::ckDisconnect(imap)
Debug "Expected a decimal Gmail message ID string."
CkStringBuilder::ckDispose(statusText)
CkJsonObject::ckDispose(statusMatch)
CkJsonObject::ckDispose(token)
CkImap::ckDispose(imap)
CkStringBuilder::ckDispose(idText)
CkJsonObject::ckDispose(validation)
ProcedureReturn
EndIf
target.i = CkMessageSet::ckCreate()
If target.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
joined1.i = CkStringBuilder::ckCreate()
If joined1.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkStringBuilder::ckAppend(joined1,"X-GM-MSGID ")
CkStringBuilder::ckAppend(joined1,gmailMessageId)
success = CkImap::ckQueryMbx(imap,CkStringBuilder::ckGetAsString(joined1),1,target)
If success <> 1
CkImap::ckLogout(imap)
CkImap::ckDisconnect(imap)
Debug "Could not find the Gmail message in the selected mailbox."
CkStringBuilder::ckDispose(statusText)
CkJsonObject::ckDispose(statusMatch)
CkJsonObject::ckDispose(token)
CkImap::ckDispose(imap)
CkStringBuilder::ckDispose(idText)
CkJsonObject::ckDispose(validation)
CkMessageSet::ckDispose(target)
CkStringBuilder::ckDispose(joined1)
ProcedureReturn
EndIf
If CkMessageSet::ckCount(target) <> 1
CkImap::ckLogout(imap)
CkImap::ckDisconnect(imap)
Debug "Expected one message in the selected mailbox. Matches: " + Str(CkMessageSet::ckCount(target))
CkStringBuilder::ckDispose(statusText)
CkJsonObject::ckDispose(statusMatch)
CkJsonObject::ckDispose(token)
CkImap::ckDispose(imap)
CkStringBuilder::ckDispose(idText)
CkJsonObject::ckDispose(validation)
CkMessageSet::ckDispose(target)
CkStringBuilder::ckDispose(joined1)
ProcedureReturn
EndIf
uid.s = CkMessageSet::ckToCompactString(target)
; Choose read, add, or remove. Only add/remove changes the message.
action.s = "read"
label.s = "Example label"
If (action <> "read") AND (action <> "add") AND (action <> "remove")
CkImap::ckLogout(imap)
CkImap::ckDisconnect(imap)
Debug "Choose read, add, or remove."
CkStringBuilder::ckDispose(statusText)
CkJsonObject::ckDispose(statusMatch)
CkJsonObject::ckDispose(token)
CkImap::ckDispose(imap)
CkStringBuilder::ckDispose(idText)
CkJsonObject::ckDispose(validation)
CkMessageSet::ckDispose(target)
CkStringBuilder::ckDispose(joined1)
ProcedureReturn
EndIf
labelText.i = CkStringBuilder::ckCreate()
If labelText.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkStringBuilder::ckAppend(labelText,label)
; This raw-command example accepts printable ASCII custom labels only.
; For non-ASCII labels, encode modified UTF-7 before quoting the command argument.
matches = CkStringBuilder::ckRegexMatch(labelText,"\A[A-Za-z0-9][\x20-\x7e]*\z",validation,1000)
If matches <> 1
CkImap::ckLogout(imap)
CkImap::ckDisconnect(imap)
Debug "Use a printable ASCII custom label starting with a letter or digit."
CkStringBuilder::ckDispose(statusText)
CkJsonObject::ckDispose(statusMatch)
CkJsonObject::ckDispose(token)
CkImap::ckDispose(imap)
CkStringBuilder::ckDispose(idText)
CkJsonObject::ckDispose(validation)
CkMessageSet::ckDispose(target)
CkStringBuilder::ckDispose(joined1)
CkStringBuilder::ckDispose(labelText)
ProcedureReturn
EndIf
replacements = CkStringBuilder::ckReplace(labelText,"\","\\")
replacements = CkStringBuilder::ckReplace(labelText,Chr(34),"\" + Chr(34))
response.s
command.s
If action <> "read"
operation.s = "+X-GM-LABELS.SILENT"
If action = "remove"
operation = "-X-GM-LABELS.SILENT"
EndIf
joined2.i = CkStringBuilder::ckCreate()
If joined2.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkStringBuilder::ckAppend(joined2,"UID STORE ")
CkStringBuilder::ckAppend(joined2,uid)
CkStringBuilder::ckAppend(joined2," ")
CkStringBuilder::ckAppend(joined2,operation)
CkStringBuilder::ckAppend(joined2," (" + Chr(34))
CkStringBuilder::ckAppend(joined2,CkStringBuilder::ckGetAsString(labelText))
CkStringBuilder::ckAppend(joined2,Chr(34) + ")")
command = CkStringBuilder::ckGetAsString(joined2)
response = CkImap::ckSendRawCommand(imap,command)
CkStringBuilder::ckSetString(statusText,response)
; A completed raw exchange can still return NO or BAD. Require tagged OK.
completed = CkStringBuilder::ckRegexMatch(statusText,"(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z",statusMatch,1000)
If (CkImap::ckLastMethodSuccess(imap) <> 1) OR (completed <> 1)
CkImap::ckLogout(imap)
CkImap::ckDisconnect(imap)
Debug "Label update failed. Check the custom label and mailbox permissions."
CkStringBuilder::ckDispose(statusText)
CkJsonObject::ckDispose(statusMatch)
CkJsonObject::ckDispose(token)
CkImap::ckDispose(imap)
CkStringBuilder::ckDispose(idText)
CkJsonObject::ckDispose(validation)
CkMessageSet::ckDispose(target)
CkStringBuilder::ckDispose(joined1)
CkStringBuilder::ckDispose(labelText)
CkStringBuilder::ckDispose(joined2)
ProcedureReturn
EndIf
EndIf
joined3.i = CkStringBuilder::ckCreate()
If joined3.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkStringBuilder::ckAppend(joined3,"UID FETCH ")
CkStringBuilder::ckAppend(joined3,uid)
CkStringBuilder::ckAppend(joined3," (X-GM-LABELS)")
response = CkImap::ckSendRawCommand(imap,CkStringBuilder::ckGetAsString(joined3))
CkStringBuilder::ckSetString(statusText,response)
; A completed raw exchange can still return NO or BAD. Require tagged OK.
completed = CkStringBuilder::ckRegexMatch(statusText,"(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z",statusMatch,1000)
If (CkImap::ckLastMethodSuccess(imap) <> 1) OR (completed <> 1)
CkImap::ckLogout(imap)
CkImap::ckDisconnect(imap)
Debug "Could not read the message labels."
CkStringBuilder::ckDispose(statusText)
CkJsonObject::ckDispose(statusMatch)
CkJsonObject::ckDispose(token)
CkImap::ckDispose(imap)
CkStringBuilder::ckDispose(idText)
CkJsonObject::ckDispose(validation)
CkMessageSet::ckDispose(target)
CkStringBuilder::ckDispose(joined1)
CkStringBuilder::ckDispose(labelText)
CkStringBuilder::ckDispose(joined2)
CkStringBuilder::ckDispose(joined3)
ProcedureReturn
EndIf
; Display the server's label-list syntax, including quoted/encoded names.
; This is a FETCH response, not an authentication/session log.
Debug response
CkImap::ckLogout(imap)
CkImap::ckDisconnect(imap)
CkStringBuilder::ckDispose(statusText)
CkJsonObject::ckDispose(statusMatch)
CkJsonObject::ckDispose(token)
CkImap::ckDispose(imap)
CkStringBuilder::ckDispose(idText)
CkJsonObject::ckDispose(validation)
CkMessageSet::ckDispose(target)
CkStringBuilder::ckDispose(joined1)
CkStringBuilder::ckDispose(labelText)
CkStringBuilder::ckDispose(joined2)
CkStringBuilder::ckDispose(joined3)
ProcedureReturn
EndProcedure