Label message with Gmail system label (e.g. Starred)

If you want to use user-defined label please read label message with user defined label.

There are two ways of labeling message with Gmail system label (e.g. Starred)

Imap.GmailLabelMessageByUID method

GmailLabelMessageByUID method uses Gmail’s X-GM-LABELS extension to the IMAP protocol. You need to provide a folder flag name for it to work correctly e.g. @”\Starred”.

You can use FolderFlag class static properties to get common flags:
FolderFlag.XImportant, FolderFlag.XSpam, FolderFlag.XStarred.

// C#

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

    imap.SelectInbox();
    long last = imap.GetAll().Last();

    imap.GmailLabelMessageByUID(last, FolderFlag.XStarred.Name);

    imap.Close();
}
' VB.NET

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

    imap.SelectInbox()
    Dim last As Long = imap.GetAll().Last()

    imap.GmailLabelMessageByUID(last, FolderFlag.XStarred.Name)

    imap.Close()
End Using

Imap.CopyByUID method

The second method basis on the fact that Gmail treats labels as regular IMAP folders.
You just need to know correct folder name and copy the message to this folder.

You can use CommonFolders class to get common folders:

// C#

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

    List<FolderInfo> folders = imap.GetFolders();

    imap.SelectInbox();
    long last = imap.GetAll().Last();

    imap.CopyByUID(last, new CommonFolders(folders).Flagged);

    imap.Close();
}

' VB.NET

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

    Dim folders As List(Of FolderInfo) = imap.GetFolders()

    imap.SelectInbox()
    Dim last As Long = imap.GetAll().Last()

    imap.CopyByUID(last, New CommonFolders(folders).Flagged)

    imap.Close()
End Using

Tags:      

Questions?

Consider using our Q&A forum for asking questions.