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.
Chilkat Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkImapW.h>
#include <CkMessageSetW.h>
void ChilkatSample(void)
{
bool success = false;
int replacements;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
CkStringBuilderW statusText;
CkJsonObjectW statusMatch;
int completed;
CkJsonObjectW token;
success = token.LoadFile(L"gmail-mail-token.json");
if (success != true) {
wprintf(L"Could not load the protocol token from the private working directory.\n");
return;
}
if ((token.JsonTypeOf(L"access_token") != 1) || (token.StringOfEquals(L"access_token",L"",true) == true)) {
wprintf(L"Authorize or refresh the mailbox first.\n");
return;
}
const wchar_t *mailbox = L"user@example.com";
CkImapW imap;
imap.put_Ssl(true);
imap.put_Port(993);
imap.put_RequireSslCertVerify(true);
imap.put_AuthMethod(L"XOAUTH2");
success = imap.Connect(L"imap.gmail.com");
if (success != true) {
wprintf(L"Could not establish the Gmail IMAP TLS connection.\n");
return;
}
success = imap.Login(mailbox,token.stringOf(L"access_token"));
if (success != true) {
imap.Disconnect();
wprintf(L"IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.\n");
return;
}
const wchar_t *capabilities = imap.capability();
if ((imap.get_LastMethodSuccess() != true) || (imap.HasCapability(L"X-GM-EXT-1",capabilities) != true)) {
imap.Logout();
imap.Disconnect();
wprintf(L"Gmail IMAP extensions are unavailable.\n");
return;
}
success = imap.SelectMailbox(L"INBOX");
if (success != true) {
imap.Logout();
imap.Disconnect();
wprintf(L"Could not open INBOX.\n");
return;
}
// Obtain this decimal string from the Gmail message/thread ID example.
const wchar_t *gmailMessageId = L"1278455344230334865";
CkStringBuilderW idText;
idText.Append(gmailMessageId);
CkJsonObjectW validation;
int matches = idText.RegexMatch(L"\\A[1-9][0-9]{0,19}\\z",validation,1000);
if (matches != 1) {
imap.Logout();
imap.Disconnect();
wprintf(L"Expected a decimal Gmail message ID string.\n");
return;
}
CkMessageSetW target;
CkStringBuilderW joined1;
joined1.Append(L"X-GM-MSGID ");
joined1.Append(gmailMessageId);
success = imap.QueryMbx(joined1.getAsString(),true,target);
if (success != true) {
imap.Logout();
imap.Disconnect();
wprintf(L"Could not find the Gmail message in the selected mailbox.\n");
return;
}
if (target.get_Count() != 1) {
imap.Logout();
imap.Disconnect();
wprintf(L"Expected one message in the selected mailbox. Matches: %d\n",target.get_Count());
return;
}
const wchar_t *uid = target.toCompactString();
// Choose read, add, or remove. Only add/remove changes the message.
const wchar_t *action = L"read";
const wchar_t *label = L"Example label";
if ((action != L"read") && (action != L"add") && (action != L"remove")) {
imap.Logout();
imap.Disconnect();
wprintf(L"Choose read, add, or remove.\n");
return;
}
CkStringBuilderW labelText;
labelText.Append(label);
// This raw-command example accepts printable ASCII custom labels only.
// For non-ASCII labels, encode modified UTF-7 before quoting the command argument.
matches = labelText.RegexMatch(L"\\A[A-Za-z0-9][\\x20-\\x7e]*\\z",validation,1000);
if (matches != 1) {
imap.Logout();
imap.Disconnect();
wprintf(L"Use a printable ASCII custom label starting with a letter or digit.\n");
return;
}
replacements = labelText.Replace(L"\\",L"\\\\");
replacements = labelText.Replace(L"\"",L"\\\"");
const wchar_t *response = 0;
const wchar_t *command = 0;
if (action != L"read") {
const wchar_t *operation = L"+X-GM-LABELS.SILENT";
if (action == L"remove") {
operation = L"-X-GM-LABELS.SILENT";
}
CkStringBuilderW joined2;
joined2.Append(L"UID STORE ");
joined2.Append(uid);
joined2.Append(L" ");
joined2.Append(operation);
joined2.Append(L" (\"");
joined2.Append(labelText.getAsString());
joined2.Append(L"\")");
command = joined2.getAsString();
response = imap.sendRawCommand(command);
statusText.SetString(response);
// A completed raw exchange can still return NO or BAD. Require tagged OK.
completed = statusText.RegexMatch(L"(?i)(?:\\A|\\r\\n)[^*+ \\r\\n]+ OK[^\\r\\n]*\\r?\\n?\\z",statusMatch,1000);
if ((imap.get_LastMethodSuccess() != true) || (completed != 1)) {
imap.Logout();
imap.Disconnect();
wprintf(L"Label update failed. Check the custom label and mailbox permissions.\n");
return;
}
}
CkStringBuilderW joined3;
joined3.Append(L"UID FETCH ");
joined3.Append(uid);
joined3.Append(L" (X-GM-LABELS)");
response = imap.sendRawCommand(joined3.getAsString());
statusText.SetString(response);
// A completed raw exchange can still return NO or BAD. Require tagged OK.
completed = statusText.RegexMatch(L"(?i)(?:\\A|\\r\\n)[^*+ \\r\\n]+ OK[^\\r\\n]*\\r?\\n?\\z",statusMatch,1000);
if ((imap.get_LastMethodSuccess() != true) || (completed != 1)) {
imap.Logout();
imap.Disconnect();
wprintf(L"Could not read the message labels.\n");
return;
}
// Display the server's label-list syntax, including quoted/encoded names.
// This is a FETCH response, not an authentication/session log.
wprintf(L"%s\n",response);
imap.Logout();
imap.Disconnect();
}