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 AutoIt Downloads
Local $bSuccess = False
Local $iReplacements
; Assumes Chilkat is unlocked. See Global Unlock Sample.
$oStatusText = ObjCreate("Chilkat.StringBuilder")
$oStatusMatch = ObjCreate("Chilkat.JsonObject")
Local $iCompleted
$oToken = ObjCreate("Chilkat.JsonObject")
$bSuccess = $oToken.LoadFile("gmail-mail-token.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not load the protocol token from the private working directory." & @CRLF)
Exit
EndIf
If (($oToken.JsonTypeOf("access_token") <> 1) Or ($oToken.StringOfEquals("access_token","",True) = True)) Then
ConsoleWrite("Authorize or refresh the mailbox first." & @CRLF)
Exit
EndIf
Local $sMailbox = "user@example.com"
$oImap = ObjCreate("Chilkat.Imap")
$oImap.Ssl = True
$oImap.Port = 993
$oImap.RequireSslCertVerify = True
$oImap.AuthMethod = "XOAUTH2"
$bSuccess = $oImap.Connect("imap.gmail.com")
If ($bSuccess <> True) Then
ConsoleWrite("Could not establish the Gmail IMAP TLS connection." & @CRLF)
Exit
EndIf
$bSuccess = $oImap.Login($sMailbox,$oToken.StringOf("access_token"))
If ($bSuccess <> True) Then
$oImap.Disconnect()
ConsoleWrite("IMAP authentication failed. Check the mailbox, scope, expiry, and account policy." & @CRLF)
Exit
EndIf
Local $sCapabilities = $oImap.Capability()
If (($oImap.LastMethodSuccess <> True) Or ($oImap.HasCapability("X-GM-EXT-1",$sCapabilities) <> True)) Then
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Gmail IMAP extensions are unavailable." & @CRLF)
Exit
EndIf
$bSuccess = $oImap.SelectMailbox("INBOX")
If ($bSuccess <> True) Then
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Could not open INBOX." & @CRLF)
Exit
EndIf
; Obtain this decimal string from the Gmail message/thread ID example.
Local $sGmailMessageId = "1278455344230334865"
$oIdText = ObjCreate("Chilkat.StringBuilder")
$oIdText.Append($sGmailMessageId)
$oValidation = ObjCreate("Chilkat.JsonObject")
Local $iMatches = $oIdText.RegexMatch("\A[1-9][0-9]{0,19}\z",$oValidation,1000)
If ($iMatches <> 1) Then
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Expected a decimal Gmail message ID string." & @CRLF)
Exit
EndIf
$oTarget = ObjCreate("Chilkat.MessageSet")
$oJoined1 = ObjCreate("Chilkat.StringBuilder")
$oJoined1.Append("X-GM-MSGID ")
$oJoined1.Append($sGmailMessageId)
$bSuccess = $oImap.QueryMbx($oJoined1.GetAsString(),True,$oTarget)
If ($bSuccess <> True) Then
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Could not find the Gmail message in the selected mailbox." & @CRLF)
Exit
EndIf
If ($oTarget.Count <> 1) Then
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Expected one message in the selected mailbox. Matches: " & $oTarget.Count & @CRLF)
Exit
EndIf
Local $sUid = $oTarget.ToCompactString()
; Choose read, add, or remove. Only add/remove changes the message.
Local $sAction = "read"
Local $sLabel = "Example label"
If (($sAction <> "read") And ($sAction <> "add") And ($sAction <> "remove")) Then
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Choose read, add, or remove." & @CRLF)
Exit
EndIf
$oLabelText = ObjCreate("Chilkat.StringBuilder")
$oLabelText.Append($sLabel)
; This raw-command example accepts printable ASCII custom labels only.
; For non-ASCII labels, encode modified UTF-7 before quoting the command argument.
$iMatches = $oLabelText.RegexMatch("\A[A-Za-z0-9][\x20-\x7e]*\z",$oValidation,1000)
If ($iMatches <> 1) Then
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Use a printable ASCII custom label starting with a letter or digit." & @CRLF)
Exit
EndIf
$iReplacements = $oLabelText.Replace("\","\\")
$iReplacements = $oLabelText.Replace("""","\""")
Local $sResponse
Local $sCommand
If ($sAction <> "read") Then
Local $sOperation = "+X-GM-LABELS.SILENT"
If ($sAction = "remove") Then
$sOperation = "-X-GM-LABELS.SILENT"
EndIf
$oJoined2 = ObjCreate("Chilkat.StringBuilder")
$oJoined2.Append("UID STORE ")
$oJoined2.Append($sUid)
$oJoined2.Append(" ")
$oJoined2.Append($sOperation)
$oJoined2.Append(" (""")
$oJoined2.Append($oLabelText.GetAsString())
$oJoined2.Append(""")")
$sCommand = $oJoined2.GetAsString()
$sResponse = $oImap.SendRawCommand($sCommand)
$oStatusText.SetString($sResponse)
; A completed raw exchange can still return NO or BAD. Require tagged OK.
$iCompleted = $oStatusText.RegexMatch("(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z",$oStatusMatch,1000)
If (($oImap.LastMethodSuccess <> True) Or ($iCompleted <> 1)) Then
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Label update failed. Check the custom label and mailbox permissions." & @CRLF)
Exit
EndIf
EndIf
$oJoined3 = ObjCreate("Chilkat.StringBuilder")
$oJoined3.Append("UID FETCH ")
$oJoined3.Append($sUid)
$oJoined3.Append(" (X-GM-LABELS)")
$sResponse = $oImap.SendRawCommand($oJoined3.GetAsString())
$oStatusText.SetString($sResponse)
; A completed raw exchange can still return NO or BAD. Require tagged OK.
$iCompleted = $oStatusText.RegexMatch("(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z",$oStatusMatch,1000)
If (($oImap.LastMethodSuccess <> True) Or ($iCompleted <> 1)) Then
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Could not read the message labels." & @CRLF)
Exit
EndIf
; Display the server's label-list syntax, including quoted/encoded names.
; This is a FETCH response, not an authentication/session log.
ConsoleWrite($sResponse & @CRLF)
$oImap.Logout()
$oImap.Disconnect()