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

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Integer iReplacements
    Handle hoStatusText
    Variant vStatusMatch
    Handle hoStatusMatch
    Integer iCompleted
    Handle hoToken
    String sMailbox
    Handle hoImap
    String sCapabilities
    String sGmailMessageId
    Handle hoIdText
    Variant vValidation
    Handle hoValidation
    Integer iMatches
    Variant vTarget
    Handle hoTarget
    Handle hoJoined1
    String sUid
    String sAction
    String sLabel
    Handle hoLabelText
    String sResponse
    String sCommand
    String sOperation
    Handle hoJoined2
    Handle hoJoined3
    String sTemp1
    Integer iTemp1
    Boolean bTemp1
    Boolean bTemp2

    Move False To iSuccess

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    Get Create (RefClass(cComChilkatStringBuilder)) To hoStatusText
    If (Not(IsComObjectCreated(hoStatusText))) Begin
        Send CreateComObject of hoStatusText
    End
    Get Create (RefClass(cComChilkatJsonObject)) To hoStatusMatch
    If (Not(IsComObjectCreated(hoStatusMatch))) Begin
        Send CreateComObject of hoStatusMatch
    End

    Get Create (RefClass(cComChilkatJsonObject)) To hoToken
    If (Not(IsComObjectCreated(hoToken))) Begin
        Send CreateComObject of hoToken
    End
    Get ComLoadFile Of hoToken "gmail-mail-token.json" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not load the protocol token from the private working directory."
        Procedure_Return
    End

    Get ComJsonTypeOf Of hoToken "access_token" To iTemp1
    Get ComStringOfEquals Of hoToken "access_token" "" True To bTemp1
    If ((iTemp1 <> 1) Or (bTemp1 = True)) Begin
        Showln "Authorize or refresh the mailbox first."
        Procedure_Return
    End

    Move "user@example.com" To sMailbox
    Get Create (RefClass(cComChilkatImap)) To hoImap
    If (Not(IsComObjectCreated(hoImap))) Begin
        Send CreateComObject of hoImap
    End
    Set ComSsl Of hoImap To True
    Set ComPort Of hoImap To 993
    Set ComRequireSslCertVerify Of hoImap To True
    Set ComAuthMethod Of hoImap To "XOAUTH2"
    Get ComConnect Of hoImap "imap.gmail.com" To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not establish the Gmail IMAP TLS connection."
        Procedure_Return
    End

    Get ComStringOf Of hoToken "access_token" To sTemp1
    Get ComLogin Of hoImap sMailbox sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Get ComDisconnect Of hoImap To iSuccess
        Showln "IMAP authentication failed. Check the mailbox, scope, expiry, and account policy."
        Procedure_Return
    End

    Get ComCapability Of hoImap To sCapabilities
    Get ComLastMethodSuccess Of hoImap To bTemp1
    Get ComHasCapability Of hoImap "X-GM-EXT-1" sCapabilities To bTemp2
    If ((bTemp1 <> True) Or (bTemp2 <> True)) Begin
        Get ComLogout Of hoImap To iSuccess
        Get ComDisconnect Of hoImap To iSuccess
        Showln "Gmail IMAP extensions are unavailable."
        Procedure_Return
    End

    Get ComSelectMailbox Of hoImap "INBOX" To iSuccess
    If (iSuccess <> True) Begin
        Get ComLogout Of hoImap To iSuccess
        Get ComDisconnect Of hoImap To iSuccess
        Showln "Could not open INBOX."
        Procedure_Return
    End

    //  Obtain this decimal string from the Gmail message/thread ID example.
    Move "1278455344230334865" To sGmailMessageId
    Get Create (RefClass(cComChilkatStringBuilder)) To hoIdText
    If (Not(IsComObjectCreated(hoIdText))) Begin
        Send CreateComObject of hoIdText
    End
    Get ComAppend Of hoIdText sGmailMessageId To iSuccess
    Get Create (RefClass(cComChilkatJsonObject)) To hoValidation
    If (Not(IsComObjectCreated(hoValidation))) Begin
        Send CreateComObject of hoValidation
    End
    Get pvComObject of hoValidation to vValidation
    Get ComRegexMatch Of hoIdText "\A[1-9][0-9]{0,19}\z" vValidation 1000 To iMatches
    If (iMatches <> 1) Begin
        Get ComLogout Of hoImap To iSuccess
        Get ComDisconnect Of hoImap To iSuccess
        Showln "Expected a decimal Gmail message ID string."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatMessageSet)) To hoTarget
    If (Not(IsComObjectCreated(hoTarget))) Begin
        Send CreateComObject of hoTarget
    End
    Get Create (RefClass(cComChilkatStringBuilder)) To hoJoined1
    If (Not(IsComObjectCreated(hoJoined1))) Begin
        Send CreateComObject of hoJoined1
    End
    Get ComAppend Of hoJoined1 "X-GM-MSGID " To iSuccess
    Get ComAppend Of hoJoined1 sGmailMessageId To iSuccess
    Get ComGetAsString Of hoJoined1 To sTemp1
    Get pvComObject of hoTarget to vTarget
    Get ComQueryMbx Of hoImap sTemp1 True vTarget To iSuccess
    If (iSuccess <> True) Begin
        Get ComLogout Of hoImap To iSuccess
        Get ComDisconnect Of hoImap To iSuccess
        Showln "Could not find the Gmail message in the selected mailbox."
        Procedure_Return
    End

    Get ComCount Of hoTarget To iTemp1
    If (iTemp1 <> 1) Begin
        Get ComLogout Of hoImap To iSuccess
        Get ComDisconnect Of hoImap To iSuccess
        Get ComCount Of hoTarget To iTemp1
        Showln "Expected one message in the selected mailbox. Matches: " iTemp1
        Procedure_Return
    End

    Get ComToCompactString Of hoTarget To sUid
    //  Choose read, add, or remove. Only add/remove changes the message.
    Move "read" To sAction
    Move "Example label" To sLabel
    If ((sAction <> "read") And (sAction <> "add") And (sAction <> "remove")) Begin
        Get ComLogout Of hoImap To iSuccess
        Get ComDisconnect Of hoImap To iSuccess
        Showln "Choose read, add, or remove."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatStringBuilder)) To hoLabelText
    If (Not(IsComObjectCreated(hoLabelText))) Begin
        Send CreateComObject of hoLabelText
    End
    Get ComAppend Of hoLabelText sLabel To iSuccess
    //  This raw-command example accepts printable ASCII custom labels only.
    //  For non-ASCII labels, encode modified UTF-7 before quoting the command argument.
    Get pvComObject of hoValidation to vValidation
    Get ComRegexMatch Of hoLabelText "\A[A-Za-z0-9][\x20-\x7e]*\z" vValidation 1000 To iMatches
    If (iMatches <> 1) Begin
        Get ComLogout Of hoImap To iSuccess
        Get ComDisconnect Of hoImap To iSuccess
        Showln "Use a printable ASCII custom label starting with a letter or digit."
        Procedure_Return
    End

    Get ComReplace Of hoLabelText "\" "\\" To iReplacements
    Get ComReplace Of hoLabelText '"' '\"' To iReplacements

    If (sAction <> "read") Begin
        Move "+X-GM-LABELS.SILENT" To sOperation
        If (sAction = "remove") Begin
            Move "-X-GM-LABELS.SILENT" To sOperation
        End

        Get Create (RefClass(cComChilkatStringBuilder)) To hoJoined2
        If (Not(IsComObjectCreated(hoJoined2))) Begin
            Send CreateComObject of hoJoined2
        End
        Get ComAppend Of hoJoined2 "UID STORE " To iSuccess
        Get ComAppend Of hoJoined2 sUid To iSuccess
        Get ComAppend Of hoJoined2 " " To iSuccess
        Get ComAppend Of hoJoined2 sOperation To iSuccess
        Get ComAppend Of hoJoined2 ' ("' To iSuccess
        Get ComGetAsString Of hoLabelText To sTemp1
        Get ComAppend Of hoJoined2 sTemp1 To iSuccess
        Get ComAppend Of hoJoined2 '")' To iSuccess
        Get ComGetAsString Of hoJoined2 To sCommand
        Get ComSendRawCommand Of hoImap sCommand To sResponse
        Get ComSetString Of hoStatusText sResponse To iSuccess
        //  A completed raw exchange can still return NO or BAD. Require tagged OK.
        Get pvComObject of hoStatusMatch to vStatusMatch
        Get ComRegexMatch Of hoStatusText "(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z" vStatusMatch 1000 To iCompleted

        Get ComLastMethodSuccess Of hoImap To bTemp1
        If ((bTemp1 <> True) Or (iCompleted <> 1)) Begin
            Get ComLogout Of hoImap To iSuccess
            Get ComDisconnect Of hoImap To iSuccess
            Showln "Label update failed. Check the custom label and mailbox permissions."
            Procedure_Return
        End

    End

    Get Create (RefClass(cComChilkatStringBuilder)) To hoJoined3
    If (Not(IsComObjectCreated(hoJoined3))) Begin
        Send CreateComObject of hoJoined3
    End
    Get ComAppend Of hoJoined3 "UID FETCH " To iSuccess
    Get ComAppend Of hoJoined3 sUid To iSuccess
    Get ComAppend Of hoJoined3 " (X-GM-LABELS)" To iSuccess
    Get ComGetAsString Of hoJoined3 To sTemp1
    Get ComSendRawCommand Of hoImap sTemp1 To sResponse
    Get ComSetString Of hoStatusText sResponse To iSuccess
    //  A completed raw exchange can still return NO or BAD. Require tagged OK.
    Get pvComObject of hoStatusMatch to vStatusMatch
    Get ComRegexMatch Of hoStatusText "(?i)(?:\A|\r\n)[^*+ \r\n]+ OK[^\r\n]*\r?\n?\z" vStatusMatch 1000 To iCompleted

    Get ComLastMethodSuccess Of hoImap To bTemp1
    If ((bTemp1 <> True) Or (iCompleted <> 1)) Begin
        Get ComLogout Of hoImap To iSuccess
        Get ComDisconnect Of hoImap To iSuccess
        Showln "Could not read the message labels."
        Procedure_Return
    End

    //  Display the server's label-list syntax, including quoted/encoded names.
    //  This is a FETCH response, not an authentication/session log.
    Showln sResponse
    Get ComLogout Of hoImap To iSuccess
    Get ComDisconnect Of hoImap To iSuccess


End_Procedure