Search IMAP messages with UTF-8 characters

See also, How to find messages in the selected mailbox on the IMAP server
var
  search: string;
  searchLen: Integer;
  buf: PclChar;
  str: TStream;
begin
  try
    clImap41.UserName := 'user';
    clImap41.Password := '***';
    clImap41.Server := 'imap.gmail.com';
    clImap41.Port := 993;
    clImap41.UseTLS := ctAutomatic;
 
   clImap41.Open();
    clImap41.SelectMailBox('INBOX');
 
   search := 'Grüße';
 
   searchLen := TclTranslator.GetByteCount(search, 'utf-8');
    GetMem(buf, searchLen);
    str := TMemoryStream.Create();
    try
      TclTranslator.GetBytes(search, buf, searchLen, 'utf-8');
      str.Write(buf^, searchLen);
      str.Write(PclChar(GetTclString(#13#10))^, Length(#13#10));
      str.Position := 0;
 
     Memo1.Lines.Clear();
      clImap41.SendTaggedCommand('SEARCH CHARSET UTF-8 %s {%d}', [IMAP_CONTINUE], ['SUBJECT', searchLen]);
      Memo1.Lines.AddStrings(clImap41.Response);
 
     clImap41.Connection.WriteData(str);
      clImap41.WaitResponse([IMAP_OK]);
      Memo1.Lines.AddStrings(clImap41.Response);
    finally
      str.Free();
      FreeMem(buf);
    end;
  finally
    clImap41.Close();
  end;
end;

Add Feedback