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 Xojo Plugin Downloads
Dim success As Boolean
success = False
Dim replacements As Int32
// Assumes Chilkat is unlocked. See Global Unlock Sample.
Dim statusText As New Chilkat.StringBuilder
Dim statusMatch As New Chilkat.JsonObject
Dim completed As Int32
Dim token As New Chilkat.JsonObject
success = token.LoadFile("gmail-mail-token.json")
If (success <> True) Then
System.DebugLog("Could not load the protocol token from the private working directory.")
Return
End If
If ((token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token","",True) = True)) Then
System.DebugLog("Authorize or refresh the mailbox first.")
Return
End If
Dim mailbox As String
mailbox = "user@example.com"
Dim imap As New Chilkat.Imap
imap.Ssl = True
imap.Port = 993
imap.RequireSslCertVerify = True
imap.AuthMethod = "XOAUTH2"
success = imap.Connect("imap.gmail.com")
If (success <> True) Then
System.DebugLog("Could not establish the Gmail IMAP TLS connection.")
Return
End If
success = imap.Login(mailbox,token.StringOf("access_token"))
If (success <> True) Then
success = imap.Disconnect()
System.DebugLog("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.")
Return
End If
Dim capabilities As String
capabilities = imap.Capability()
If ((imap.LastMethodSuccess <> True) Or (imap.HasCapability("X-GM-EXT-1",capabilities) <> True)) Then
success = imap.Logout()
success = imap.Disconnect()
System.DebugLog("Gmail IMAP extensions are unavailable.")
Return
End If
success = imap.SelectMailbox("INBOX")
If (success <> True) Then
success = imap.Logout()
success = imap.Disconnect()
System.DebugLog("Could not open INBOX.")
Return
End If
// Obtain this decimal string from the Gmail message/thread ID example.
Dim gmailMessageId As String
gmailMessageId = "1278455344230334865"
Dim idText As New Chilkat.StringBuilder
success = idText.Append(gmailMessageId)
Dim validation As New Chilkat.JsonObject
Dim matches As Int32
matches = idText.RegexMatch("\A[1-9][0-9]{0,19}\z",validation,1000)
If (matches <> 1) Then
success = imap.Logout()
success = imap.Disconnect()
System.DebugLog("Expected a decimal Gmail message ID string.")
Return
End If
Dim target As New Chilkat.MessageSet
Dim joined1 As New Chilkat.StringBuilder
success = joined1.Append("X-GM-MSGID ")
success = joined1.Append(gmailMessageId)
success = imap.QueryMbx(joined1.GetAsString(),True,target)
If (success <> True) Then
success = imap.Logout()
success = imap.Disconnect()
System.DebugLog("Could not find the Gmail message in the selected mailbox.")
Return
End If
If (target.Count <> 1) Then
success = imap.Logout()
success = imap.Disconnect()
System.DebugLog("Expected one message in the selected mailbox. Matches: " + Str(target.Count))
Return
End If
Dim uid As String
uid = target.ToCompactString()
// Choose read, add, or remove. Only add/remove changes the message.
Dim action As String
action = "read"
Dim label As String
label = "Example label"
If ((action <> "read") And (action <> "add") And (action <> "remove")) Then
success = imap.Logout()
success = imap.Disconnect()
System.DebugLog("Choose read, add, or remove.")
Return
End If
Dim labelText As New Chilkat.StringBuilder
success = labelText.Append(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 = labelText.RegexMatch("\A[A-Za-z0-9][\x20-\x7e]*\z",validation,1000)
If (matches <> 1) Then
success = imap.Logout()
success = imap.Disconnect()
System.DebugLog("Use a printable ASCII custom label starting with a letter or digit.")
Return
End If
replacements = labelText.Replace("\","\\")
replacements = labelText.Replace("""","\""")
Dim response As String
Dim command As String
If (action <> "read") Then
Dim operation As String
operation = "+X-GM-LABELS.SILENT"
If (action = "remove") Then
operation = "-X-GM-LABELS.SILENT"
End If
Dim joined2 As New Chilkat.StringBuilder
success = joined2.Append("UID STORE ")
success = joined2.Append(uid)
success = joined2.Append(" ")
success = joined2.Append(operation)
success = joined2.Append(" (""")
success = joined2.Append(labelText.GetAsString())
success = joined2.Append(""")")
command = joined2.GetAsString()
response = imap.SendRawCommand(command)
success = statusText.SetString(response)
// A completed raw exchange can still return NO or BAD. Require tagged OK.
completed = statusText.RegexMatch("(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z",statusMatch,1000)
If ((imap.LastMethodSuccess <> True) Or (completed <> 1)) Then
success = imap.Logout()
success = imap.Disconnect()
System.DebugLog("Label update failed. Check the custom label and mailbox permissions.")
Return
End If
End If
Dim joined3 As New Chilkat.StringBuilder
success = joined3.Append("UID FETCH ")
success = joined3.Append(uid)
success = joined3.Append(" (X-GM-LABELS)")
response = imap.SendRawCommand(joined3.GetAsString())
success = statusText.SetString(response)
// A completed raw exchange can still return NO or BAD. Require tagged OK.
completed = statusText.RegexMatch("(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z",statusMatch,1000)
If ((imap.LastMethodSuccess <> True) Or (completed <> 1)) Then
success = imap.Logout()
success = imap.Disconnect()
System.DebugLog("Could not read the message labels.")
Return
End If
// Display the server's label-list syntax, including quoted/encoded names.
// This is a FETCH response, not an authentication/session log.
System.DebugLog(response)
success = imap.Logout()
success = imap.Disconnect()