Sample code for 30+ languages & platforms
Ruby Requires Chilkat v11.1.0+

Gmail IMAP: Identify Messages and Threads Across Folders

See more GMail SMTP/IMAP/POP Examples

Sample INBOX and the discovered All Mail folder, fetch Gmail message and thread IDs, and deduplicate messages appearing in both. Each X-GM-MSGID maps to an X-GM-THRID; equal thread IDs group messages in a Gmail conversation.

All identifiers are strings. IMAP UIDs identify messages only within one mailbox and UIDVALIDITY. Gmail IDs identify messages across labels, while the RFC Message-ID header is a separate identifier. Gmail IMAP IDs are unsigned decimal values; Gmail REST uses the corresponding hexadecimal strings. Do not pass these decimal strings directly as REST IDs.

The example reads at most ten messages per folder. Its regular expression extracts only the requested numeric metadata from a single-line FETCH result, tolerating attribute order and unrelated notifications. It is not a general IMAP/MIME parser. A vanished message is skipped. No message body is downloaded or marked read.

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 Ruby Downloads

Ruby
require 'chilkat'

success = false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

statusText = Chilkat::CkStringBuilder.new()
statusMatch = Chilkat::CkJsonObject.new()

token = Chilkat::CkJsonObject.new()
success = token.LoadFile("gmail-mail-token.json")
if (success != true)
    print "Could not load the protocol token from the private working directory." + "\n";
    exit
end

if ((token.JsonTypeOf("access_token") != 1) or (token.StringOfEquals("access_token","",true) == true))
    print "Authorize or refresh the mailbox first." + "\n";
    exit
end

mailbox = "user@example.com"
imap = Chilkat::CkImap.new()
imap.put_Ssl(true)
imap.put_Port(993)
imap.put_RequireSslCertVerify(true)
imap.put_AuthMethod("XOAUTH2")
success = imap.Connect("imap.gmail.com")
if (success != true)
    print "Could not establish the Gmail IMAP TLS connection." + "\n";
    exit
end

success = imap.Login(mailbox,token.stringOf("access_token"))
if (success != true)
    imap.Disconnect()
    print "IMAP authentication failed. Check the mailbox, scope, expiry, and account policy." + "\n";
    exit
end

capabilities = imap.capability()
if ((imap.get_LastMethodSuccess() != true) or (imap.HasCapability("X-GM-EXT-1",capabilities) != true))
    imap.Logout()
    imap.Disconnect()
    print "Gmail IMAP extensions are unavailable." + "\n";
    exit
end

folders = Chilkat::CkMailboxes.new()
success = imap.MbxList(false,"","*",folders)
if (success != true)
    imap.Logout()
    imap.Disconnect()
    print "Could not list Gmail folders." + "\n";
    exit
end

allMail = ""
folderMatches = 0
f = 0
while (f < folders.get_Count())
    if ((folders.HasFlag(f,"\\All") == true) and (folders.IsSelectable(f) == true))
        allMail = folders.getName(f)
        folderMatches = folderMatches + 1
    end

    f = f + 1
end
if (folderMatches != 1)
    imap.Logout()
    imap.Disconnect()
    print "Expected one selectable folder with the \\All special-use attribute. Check label visibility." + "\n";
    exit
end

mailboxNames = Chilkat::CkStringTable.new()
mailboxNames.Append("INBOX")
mailboxNames.Append(allMail)
unique = Chilkat::CkJsonObject.new()
found = Chilkat::CkMessageSet.new()
uidStrings = Chilkat::CkStringTable.new()
raw = Chilkat::CkStringBuilder.new()
captures = Chilkat::CkJsonObject.new()
folderIndex = 0
while (folderIndex < mailboxNames.get_Count())
    selected = mailboxNames.stringAt(folderIndex)
    success = imap.ExamineMailbox(selected)
    if (success != true)
        imap.Logout()
        imap.Disconnect()
        print "Could not open the mailbox read-only." + "\n";
        exit
    end

    success = imap.QueryMbx("ALL",true,found)
    if (success != true)
        imap.Logout()
        imap.Disconnect()
        print "Could not obtain message UIDs." + "\n";
        exit
    end

    uidStrings.Clear()
    if (found.get_Count() > 0)
        uidStrings.SplitAndAppend(found.toCommaSeparatedStr(),",",false,false)
    end

    #  Sample up to 10 messages from each mailbox; this is not a complete synchronization.
    i = 0
    while ((i < uidStrings.get_Count()) and (i < 10))
        uid = uidStrings.stringAt(i)
        joined1 = Chilkat::CkStringBuilder.new()
        joined1.Append("UID FETCH ")
        joined1.Append(uid)
        joined1.Append(" (UID X-GM-MSGID X-GM-THRID)")
        response = imap.sendRawCommand(joined1.getAsString())
        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.get_LastMethodSuccess() != true) or (completed != 1))
            imap.Logout()
            imap.Disconnect()
            print "Could not fetch Gmail IDs." + "\n";
            exit
        end

        raw.SetString(response)
        #  Match only this UID's metadata line. Attribute order need not be fixed.
        #  Unsolicited EXISTS/EXPUNGE/FLAGS lines do not match these three attributes.
        joined2 = Chilkat::CkStringBuilder.new()
        joined2.Append("(?mi)^\\* [0-9]+ FETCH \\((?=[^\\r\\n]*\\bUID ")
        joined2.Append(uid)
        joined2.Append("(?: |\\)))(?=[^\\r\\n]*\\bX-GM-MSGID ([0-9]+)(?: |\\)))(?=[^\\r\\n]*\\bX-GM-THRID ([0-9]+)(?: |\\)))[^\\r\\n]*\\)\\r?$")
        pattern = joined2.getAsString()
        count = raw.RegexMatch(pattern,captures,1000)
        if (count < 0)
            imap.Logout()
            imap.Disconnect()
            print "Could not parse the Gmail metadata response." + "\n";
            exit
        end

        if (count == 1)
            messageId = captures.stringOf("match[0].group[1].cap")
            threadId = captures.stringOf("match[0].group[2].cap")
            if (unique.IndexOf(messageId) < 0)
                #  Direct JSON member names; both IDs remain strings without numeric conversion.
                unique.AppendString(messageId,threadId)
                print "Message ID: " + messageId + "  Thread ID: " + threadId + "\n";
            else
                print "Already encountered under another label: " + messageId + "\n";
            end

        else
            print "No single metadata row for UID " + uid + "; it may have disappeared. Skipping." + "\n";
        end

        i = i + 1
    end
    folderIndex = folderIndex + 1
end
imap.Logout()
imap.Disconnect()
print "Unique sampled messages: " + unique.get_Size().to_s() + "\n";