Sample code for 30+ languages & platforms
Classic ASP 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 Classic ASP Downloads

Classic ASP
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<%
success = 0

'  Assumes Chilkat is unlocked. See Global Unlock Sample.

set statusText = Server.CreateObject("Chilkat.StringBuilder")
set statusMatch = Server.CreateObject("Chilkat.JsonObject")

set token = Server.CreateObject("Chilkat.JsonObject")
success = token.LoadFile("gmail-mail-token.json")
If (success <> 1) Then
    Response.Write "<pre>" & Server.HTMLEncode( "Could not load the protocol token from the private working directory.") & "</pre>"
    Response.End
End If

If ((token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token","",1) = 1)) Then
    Response.Write "<pre>" & Server.HTMLEncode( "Authorize or refresh the mailbox first.") & "</pre>"
    Response.End
End If

mailbox = "user@example.com"
set imap = Server.CreateObject("Chilkat.Imap")
imap.Ssl = 1
imap.Port = 993
imap.RequireSslCertVerify = 1
imap.AuthMethod = "XOAUTH2"
success = imap.Connect("imap.gmail.com")
If (success <> 1) Then
    Response.Write "<pre>" & Server.HTMLEncode( "Could not establish the Gmail IMAP TLS connection.") & "</pre>"
    Response.End
End If

success = imap.Login(mailbox,token.StringOf("access_token"))
If (success <> 1) Then
    success = imap.Disconnect()
    Response.Write "<pre>" & Server.HTMLEncode( "IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.") & "</pre>"
    Response.End
End If

capabilities = imap.Capability()
If ((imap.LastMethodSuccess <> 1) Or (imap.HasCapability("X-GM-EXT-1",capabilities) <> 1)) Then
    success = imap.Logout()
    success = imap.Disconnect()
    Response.Write "<pre>" & Server.HTMLEncode( "Gmail IMAP extensions are unavailable.") & "</pre>"
    Response.End
End If

success = imap.SelectMailbox("INBOX")
If (success <> 1) Then
    success = imap.Logout()
    success = imap.Disconnect()
    Response.Write "<pre>" & Server.HTMLEncode( "Could not open INBOX.") & "</pre>"
    Response.End
End If

'  Obtain this decimal string from the Gmail message/thread ID example.
gmailMessageId = "1278455344230334865"
set idText = Server.CreateObject("Chilkat.StringBuilder")
success = idText.Append(gmailMessageId)
set validation = Server.CreateObject("Chilkat.JsonObject")
matches = idText.RegexMatch("\A[1-9][0-9]{0,19}\z",validation,1000)
If (matches <> 1) Then
    success = imap.Logout()
    success = imap.Disconnect()
    Response.Write "<pre>" & Server.HTMLEncode( "Expected a decimal Gmail message ID string.") & "</pre>"
    Response.End
End If

set target = Server.CreateObject("Chilkat.MessageSet")
set joined1 = Server.CreateObject("Chilkat.StringBuilder")
success = joined1.Append("X-GM-MSGID ")
success = joined1.Append(gmailMessageId)
success = imap.QueryMbx(joined1.GetAsString(),1,target)
If (success <> 1) Then
    success = imap.Logout()
    success = imap.Disconnect()
    Response.Write "<pre>" & Server.HTMLEncode( "Could not find the Gmail message in the selected mailbox.") & "</pre>"
    Response.End
End If

If (target.Count <> 1) Then
    success = imap.Logout()
    success = imap.Disconnect()
    Response.Write "<pre>" & Server.HTMLEncode( "Expected one message in the selected mailbox. Matches: " & target.Count) & "</pre>"
    Response.End
End If

uid = target.ToCompactString()
'  Choose read, add, or remove. Only add/remove changes the message.
action = "read"
label = "Example label"
If ((action <> "read") And (action <> "add") And (action <> "remove")) Then
    success = imap.Logout()
    success = imap.Disconnect()
    Response.Write "<pre>" & Server.HTMLEncode( "Choose read, add, or remove.") & "</pre>"
    Response.End
End If

set labelText = Server.CreateObject("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()
    Response.Write "<pre>" & Server.HTMLEncode( "Use a printable ASCII custom label starting with a letter or digit.") & "</pre>"
    Response.End
End If

replacements = labelText.Replace("\","\\")
replacements = labelText.Replace("""","\""")

If (action <> "read") Then
    operation = "+X-GM-LABELS.SILENT"
    If (action = "remove") Then
        operation = "-X-GM-LABELS.SILENT"
    End If

    set joined2 = Server.CreateObject("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()
ERROR: ASP example cannot use request or response as a variable name.
    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 <> 1) Or (completed <> 1)) Then
        success = imap.Logout()
        success = imap.Disconnect()
        Response.Write "<pre>" & Server.HTMLEncode( "Label update failed. Check the custom label and mailbox permissions.") & "</pre>"
        Response.End
    End If

End If

set joined3 = Server.CreateObject("Chilkat.StringBuilder")
success = joined3.Append("UID FETCH ")
success = joined3.Append(uid)
success = joined3.Append(" (X-GM-LABELS)")
ERROR: ASP example cannot use request or response as a variable name.
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 <> 1) Or (completed <> 1)) Then
    success = imap.Logout()
    success = imap.Disconnect()
    Response.Write "<pre>" & Server.HTMLEncode( "Could not read the message labels.") & "</pre>"
    Response.End
End If

'  Display the server's label-list syntax, including quoted/encoded names.
'  This is a FETCH response, not an authentication/session log.
Response.Write "<pre>" & Server.HTMLEncode( response) & "</pre>"
success = imap.Logout()
success = imap.Disconnect()

%>
</body>
</html>