Decode IMAP UTF7 mailbox names in Delphi

Starting from Clever Internet Suite version 9.2, the IMAP UTF7 mailbox encoding is included to both the client and server IMAP components.
 

How to use

for i := 0 to mailboxList.Count - 1 do
begin
  mailboxName := TImapUtf7Encoder.Decode(mailboxList[i]);
end;

Implementation

class function TImapUtf7Encoder.Decode(const AValue: string): string;
var
  n, h, t, k: Integer;
begin
  Result := '';
  n := Length(AValue);
  h := 1;

  while (h <= n) do
  begin
    t := System.Pos('&', AValue, h);

    if (t <= 0) then
    begin
      t := n + 1;
    end;

    Result := Result + System.Copy(AValue, h, t - h);
    h := t + 1;
    if (h > n) then Break;

    t := System.Pos('-', AValue, h);
    if (t <= 0) then
    begin
      t := n + 1;
    end;

    k := t - h;
    if (k = 0) then
    begin
      Result := Result + '&';
    end else
    begin
      Result := Result + DecodeBase64Imap(System.Copy(AValue, h, k));
    end;
    h := t + 1;
  end;
end;
 
class function TImapUtf7Encoder.DecodeBase64Imap(const AValue: string): string;
var
  enc: TclEncoder;
  b: TBytes;
begin
  enc := TclEncoder.Create(nil);
  try
    enc.EncodeMethod := cmBase64;
    enc.CharSet := 'UTF-7';
    b := enc.DecodeToBytes(StringReplace(AValue, ',', '/', [rfReplaceAll]));
    Result := TclTranslator.GetString(b, 'UTF-16BE');
  finally
    enc.Free();
  end;
end;

Add Feedback