Search Gmail label

Gmail treats labels as folders for the purposes of IMAP.

As such, labels can be modified using the standard IMAP commands, CreateFolder, RenameFolder, and DeleteFolder, that act on folders.

System labels, which are labels created by Gmail, are reserved and prefixed by “[Gmail]” or “[GoogleMail]” in the list of labels.

Use the XLIST command to get the entire list of labels for a mailbox.

The labels for a given message may be retrieved by using the X-GM-LABELS attribute with the FETCH command.

It is also possible to use the X-GM-LABELS attribute to return the UIDs for all messages with a given label, using the SEARCH command.

// C# version

using (Imap imap = new Imap())
{
    imap.ConnectSSL("imap.gmail.com");
    imap.UseBestLogin("pat@gmail.com", "password");

    // Select 'All Mail' folder
    CommonFolders common = new CommonFolders(client.GetFolders());
    client.Select(common.AllMail);

    List<long> uids = imap.Search().Where(
        Expression.GmailLabel("MyLabel"));

    foreach (MessageInfo info in imap.GetMessageInfoByUID(uids))
    {
        Console.WriteLine("{0} - {1}",
            info.Envelope.GmailThreadId,
            info.Envelope.Subject);
    }

    imap.Close();
}

' VB.NET version

Using imap As New Imap()
	imap.ConnectSSL("imap.gmail.com")
	imap.UseBestLogin("pat@gmail.com", "password")

	' Select 'All Mail' folder
	Dim common As New CommonFolders(client.GetFolders())
	client.Select(common.AllMail)

	Dim uids As List(Of Long) = imap.Search().Where(Expression.GmailLabel("MyLabel"))

	For Each info As MessageInfo In imap.GetMessageInfoByUID(uids)
            Console.WriteLine("{0} - {1}",  _
                info.Envelope.GmailThreadId,  _
                info.Envelope.Subject)
	Next

	imap.Close()
End Using

You can learn more about this Gmail IMAP extension here:
http://code.google.com/apis/gmail/imap/#x-gm-labels

Tags:      

Questions?

Consider using our Q&A forum for asking questions.

One Response to “Search Gmail label”

  1. Gmail extensions in Mail.dll Says:

    […] Blog   « Search Gmail label […]