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 PowerBuilder Downloads
integer li_rc
long li_Success
long li_Replacements
oleobject loo_StatusText
oleobject loo_StatusMatch
long li_Completed
oleobject loo_Token
string ls_Mailbox
oleobject loo_Imap
string ls_Capabilities
string ls_GmailMessageId
oleobject loo_IdText
oleobject loo_Validation
long li_Matches
oleobject loo_Target
oleobject loo_Joined1
string ls_Uid
string ls_Action
string ls_Label
oleobject loo_LabelText
string ls_Response
string ls_Command
string ls_Operation
oleobject loo_Joined2
oleobject loo_Joined3
li_Success = 0
// Assumes Chilkat is unlocked. See Global Unlock Sample.
loo_StatusText = create oleobject
li_rc = loo_StatusText.ConnectToNewObject("Chilkat.StringBuilder")
if li_rc < 0 then
destroy loo_StatusText
MessageBox("Error","Connecting to COM object failed")
return
end if
loo_StatusMatch = create oleobject
li_rc = loo_StatusMatch.ConnectToNewObject("Chilkat.JsonObject")
loo_Token = create oleobject
li_rc = loo_Token.ConnectToNewObject("Chilkat.JsonObject")
li_Success = loo_Token.LoadFile("gmail-mail-token.json")
if li_Success <> 1 then
Write-Debug "Could not load the protocol token from the private working directory."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
return
end if
if (loo_Token.JsonTypeOf("access_token") <> 1) OR (loo_Token.StringOfEquals("access_token","",1) = 1) then
Write-Debug "Authorize or refresh the mailbox first."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
return
end if
ls_Mailbox = "user@example.com"
loo_Imap = create oleobject
li_rc = loo_Imap.ConnectToNewObject("Chilkat.Imap")
loo_Imap.Ssl = 1
loo_Imap.Port = 993
loo_Imap.RequireSslCertVerify = 1
loo_Imap.AuthMethod = "XOAUTH2"
li_Success = loo_Imap.Connect("imap.gmail.com")
if li_Success <> 1 then
Write-Debug "Could not establish the Gmail IMAP TLS connection."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
return
end if
li_Success = loo_Imap.Login(ls_Mailbox,loo_Token.StringOf("access_token"))
if li_Success <> 1 then
loo_Imap.Disconnect()
Write-Debug "IMAP authentication failed. Check the mailbox, scope, expiry, and account policy."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
return
end if
ls_Capabilities = loo_Imap.Capability()
if (loo_Imap.LastMethodSuccess <> 1) OR (loo_Imap.HasCapability("X-GM-EXT-1",ls_Capabilities) <> 1) then
loo_Imap.Logout()
loo_Imap.Disconnect()
Write-Debug "Gmail IMAP extensions are unavailable."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
return
end if
li_Success = loo_Imap.SelectMailbox("INBOX")
if li_Success <> 1 then
loo_Imap.Logout()
loo_Imap.Disconnect()
Write-Debug "Could not open INBOX."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
return
end if
// Obtain this decimal string from the Gmail message/thread ID example.
ls_GmailMessageId = "1278455344230334865"
loo_IdText = create oleobject
li_rc = loo_IdText.ConnectToNewObject("Chilkat.StringBuilder")
loo_IdText.Append(ls_GmailMessageId)
loo_Validation = create oleobject
li_rc = loo_Validation.ConnectToNewObject("Chilkat.JsonObject")
li_Matches = loo_IdText.RegexMatch("\A[1-9][0-9]{0,19}\z",loo_Validation,1000)
if li_Matches <> 1 then
loo_Imap.Logout()
loo_Imap.Disconnect()
Write-Debug "Expected a decimal Gmail message ID string."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
destroy loo_IdText
destroy loo_Validation
return
end if
loo_Target = create oleobject
li_rc = loo_Target.ConnectToNewObject("Chilkat.MessageSet")
loo_Joined1 = create oleobject
li_rc = loo_Joined1.ConnectToNewObject("Chilkat.StringBuilder")
loo_Joined1.Append("X-GM-MSGID ")
loo_Joined1.Append(ls_GmailMessageId)
li_Success = loo_Imap.QueryMbx(loo_Joined1.GetAsString(),1,loo_Target)
if li_Success <> 1 then
loo_Imap.Logout()
loo_Imap.Disconnect()
Write-Debug "Could not find the Gmail message in the selected mailbox."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
destroy loo_IdText
destroy loo_Validation
destroy loo_Target
destroy loo_Joined1
return
end if
if loo_Target.Count <> 1 then
loo_Imap.Logout()
loo_Imap.Disconnect()
Write-Debug "Expected one message in the selected mailbox. Matches: " + string(loo_Target.Count)
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
destroy loo_IdText
destroy loo_Validation
destroy loo_Target
destroy loo_Joined1
return
end if
ls_Uid = loo_Target.ToCompactString()
// Choose read, add, or remove. Only add/remove changes the message.
ls_Action = "read"
ls_Label = "Example label"
if (ls_Action <> "read") AND (ls_Action <> "add") AND (ls_Action <> "remove") then
loo_Imap.Logout()
loo_Imap.Disconnect()
Write-Debug "Choose read, add, or remove."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
destroy loo_IdText
destroy loo_Validation
destroy loo_Target
destroy loo_Joined1
return
end if
loo_LabelText = create oleobject
li_rc = loo_LabelText.ConnectToNewObject("Chilkat.StringBuilder")
loo_LabelText.Append(ls_Label)
// This raw-command example accepts printable ASCII custom labels only.
// For non-ASCII labels, encode modified UTF-7 before quoting the command argument.
li_Matches = loo_LabelText.RegexMatch("\A[A-Za-z0-9][\x20-\x7e]*\z",loo_Validation,1000)
if li_Matches <> 1 then
loo_Imap.Logout()
loo_Imap.Disconnect()
Write-Debug "Use a printable ASCII custom label starting with a letter or digit."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
destroy loo_IdText
destroy loo_Validation
destroy loo_Target
destroy loo_Joined1
destroy loo_LabelText
return
end if
li_Replacements = loo_LabelText.Replace("\","\\")
li_Replacements = loo_LabelText.Replace("~"","\~"")
if ls_Action <> "read" then
ls_Operation = "+X-GM-LABELS.SILENT"
if ls_Action = "remove" then
ls_Operation = "-X-GM-LABELS.SILENT"
end if
loo_Joined2 = create oleobject
li_rc = loo_Joined2.ConnectToNewObject("Chilkat.StringBuilder")
loo_Joined2.Append("UID STORE ")
loo_Joined2.Append(ls_Uid)
loo_Joined2.Append(" ")
loo_Joined2.Append(ls_Operation)
loo_Joined2.Append(" (~"")
loo_Joined2.Append(loo_LabelText.GetAsString())
loo_Joined2.Append("~")")
ls_Command = loo_Joined2.GetAsString()
ls_Response = loo_Imap.SendRawCommand(ls_Command)
loo_StatusText.SetString(ls_Response)
// A completed raw exchange can still return NO or BAD. Require tagged OK.
li_Completed = loo_StatusText.RegexMatch("(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z",loo_StatusMatch,1000)
if (loo_Imap.LastMethodSuccess <> 1) OR (li_Completed <> 1) then
loo_Imap.Logout()
loo_Imap.Disconnect()
Write-Debug "Label update failed. Check the custom label and mailbox permissions."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
destroy loo_IdText
destroy loo_Validation
destroy loo_Target
destroy loo_Joined1
destroy loo_LabelText
destroy loo_Joined2
return
end if
end if
loo_Joined3 = create oleobject
li_rc = loo_Joined3.ConnectToNewObject("Chilkat.StringBuilder")
loo_Joined3.Append("UID FETCH ")
loo_Joined3.Append(ls_Uid)
loo_Joined3.Append(" (X-GM-LABELS)")
ls_Response = loo_Imap.SendRawCommand(loo_Joined3.GetAsString())
loo_StatusText.SetString(ls_Response)
// A completed raw exchange can still return NO or BAD. Require tagged OK.
li_Completed = loo_StatusText.RegexMatch("(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z",loo_StatusMatch,1000)
if (loo_Imap.LastMethodSuccess <> 1) OR (li_Completed <> 1) then
loo_Imap.Logout()
loo_Imap.Disconnect()
Write-Debug "Could not read the message labels."
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
destroy loo_IdText
destroy loo_Validation
destroy loo_Target
destroy loo_Joined1
destroy loo_LabelText
destroy loo_Joined2
destroy loo_Joined3
return
end if
// Display the server's label-list syntax, including quoted/encoded names.
// This is a FETCH response, not an authentication/session log.
Write-Debug ls_Response
loo_Imap.Logout()
loo_Imap.Disconnect()
destroy loo_StatusText
destroy loo_StatusMatch
destroy loo_Token
destroy loo_Imap
destroy loo_IdText
destroy loo_Validation
destroy loo_Target
destroy loo_Joined1
destroy loo_LabelText
destroy loo_Joined2
destroy loo_Joined3