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

Gmail IMAP: Discover Special Folders

See more GMail SMTP/IMAP/POP Examples

Find Gmail special folders from the attributes returned by LIST, using MbxList and Mailboxes.HasFlag. The result maps roles such as Sent and Trash to the server-provided mailbox names. Chilkat decodes mailbox names for use with its mailbox methods.

Folder names can be localized and visibility can differ by account. The role attributes are stable; do not hard-code [Gmail]/Sent Mail or use the deprecated XLIST command. INBOX is a protocol-defined name. Missing map keys indicate folders not advertised by the server.

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 Lazarus Pascal Downloads

Lazarus Pascal
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Mailboxes,
  Chilkat.Imap,
  Chilkat.JsonObject;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  token: TJsonObject;
  mailbox: string;
  imap: TImap;
  folders: TMailboxes;
  special: TJsonObject;
  i: Integer;

begin
  success := False;

  //  Assumes Chilkat is unlocked. See Global Unlock Sample.

  token := TJsonObject.Create;
  success := token.LoadFile('gmail-mail-token.json');
  if (success <> True) then
    begin
      WriteLn('Could not load the protocol token from the private working directory.');
      Exit;
    end;
  if ((token.JsonTypeOf('access_token') <> 1) or (token.StringOfEquals('access_token','',True) = True)) then
    begin
      WriteLn('Authorize or refresh the mailbox first.');
      Exit;
    end;
  mailbox := 'user@example.com';
  imap := TImap.Create;
  imap.Ssl := True;
  imap.Port := 993;
  imap.RequireSslCertVerify := True;
  imap.AuthMethod := 'XOAUTH2';
  success := imap.Connect('imap.gmail.com');
  if (success <> True) then
    begin
      WriteLn('Could not establish the Gmail IMAP TLS connection.');
      Exit;
    end;
  success := imap.Login(mailbox,token.StringOf('access_token'));
  if (success <> True) then
    begin
      imap.Disconnect();
      WriteLn('IMAP authentication failed. Check the mailbox, scope, expiry, and account policy.');
      Exit;
    end;
  folders := TMailboxes.Create;
  success := imap.MbxList(False,'','*',folders);
  if (success <> True) then
    begin
      imap.Logout();
      imap.Disconnect();
      WriteLn('Could not list Gmail folders.');
      Exit;
    end;
  //  LIST special-use attributes work with localized folder names. XLIST is obsolete.
  special := TJsonObject.Create;
  i := 0;
  while (i < folders.Count) do
    begin
      if (folders.IsSelectable(i) = True) then
        begin
          WriteLn(folders.GetName(i) + '  ' + folders.GetFlags(i));
          if (folders.HasFlag(i,'\All') = True) then
            begin
              special.UpdateString('allMail',folders.GetName(i));
            end;
          if (folders.HasFlag(i,'\Sent') = True) then
            begin
              special.UpdateString('sent',folders.GetName(i));
            end;
          if (folders.HasFlag(i,'\Drafts') = True) then
            begin
              special.UpdateString('drafts',folders.GetName(i));
            end;
          if (folders.HasFlag(i,'\Junk') = True) then
            begin
              special.UpdateString('spam',folders.GetName(i));
            end;
          if (folders.HasFlag(i,'\Trash') = True) then
            begin
              special.UpdateString('trash',folders.GetName(i));
            end;
          if (folders.HasFlag(i,'\Flagged') = True) then
            begin
              special.UpdateString('starred',folders.GetName(i));
            end;
          if (folders.HasFlag(i,'\Important') = True) then
            begin
              special.UpdateString('important',folders.GetName(i));
            end;
        end;
      i := i + 1;
    end;

  imap.Logout();
  imap.Disconnect();
  special.EmitCompact := False;
  WriteLn(special.Emit());
  //  Missing keys mean the folder was not advertised. Do not substitute an English name.


  token.Free;
  imap.Free;
  folders.Free;
  special.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.