Get Gmail labels for specified messages
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.
For list of messages
// C# version using (Imap imap = new Imap()) { imap.ConnectSSL("imap.gmail.com"); imap.UseBestLogin("pat@gmail.com", "password"); imap.SelectInbox(); List<long> uids = imap.GetAll(); List<messageInfo> infos = imap.GetMessageInfoByUID(uids); foreach (MessageInfo info in infos) { List<string> labels = info.GmailLabels.Labels; Console.WriteLine("[{0}] {1}", string.Join(" ", labels.ToArray()), info.Envelope.Subject); } imap.Close(); }
' VB.NET version Using imap As New Imap() imap.ConnectSSL("imap.gmail.com") imap.UseBestLogin("pat@gmail.com", "password") imap.SelectInbox() Dim uids As List(Of Long) = imap.GetAll() Dim infos As List(Of MessageInfo) = imap.GetMessageInfoByUID(uids) For Each info As MessageInfo In infos Dim labels As List(Of String) = info.GmailLabels.Labels Console.WriteLine("[{0}] {1}", _ String.Join(" ", labels.ToArray()), _ info.Envelope.Subject) Next imap.Close() End Using
For single message:
// C# version using (Imap imap = new Imap()) { imap.ConnectSSL("imap.gmail.com"); imap.Login("pat@gmail.com", "password"); imap.SelectInbox(); long uid = imap.GetAll().Last(); List<string> labels = imap.GmailGetLabelsByUID(uid); labels.ForEach(Console.WriteLine); imap.Close(); }
' VB.NET version Using imap As New Imap() imap.ConnectSSL("imap.gmail.com") imap.Login("pat@gmail.com", "password") imap.SelectInbox() Dim uid As Long = imap.GetAll().Last() Dim labels As List(Of String) = imap.GmailGetLabelsByUID(uid) labels.ForEach(Console.WriteLine) imap.Close() End Using
You can learn more about this Gmail IMAP extension here:
http://code.google.com/apis/gmail/imap/#x-gm-labels
January 23rd, 2016 at 19:18
[…] Get Gmail labels for specified messages […]