I'm trying to retrieve all my unread email messages using IMAP, and I seem to connect and locate fine those unread message (I can see, for example, that SearchResult returns 3 items corresponding to my 3 currently unread messages), but the IMAP.Retrieve call always returns false, not retrieving any of them.
Do you see what must be lacking on my code ?.
procedure TForm1.btnUnreadMessagesClick(Sender: TObject);
var i: integer;
SearchInfo: array of TIdIMAP4SearchRec;
MSG: TIdMessage;
begin
Memo1.Lines.Clear;
IMAP.Host := 'outlook.office365.com';
IMAP.Port := 993;
IMAP.Username := 'xxxxx@acme.com';
IMAP.Password := 'xxxxx';
SSL.Host := IMAP.Host;
SSL.Port := IMAP.Port;
SSL.Destination := SSL.Host + ':' + IntToStr(SSL.Port);
SSL.MaxLineLength := MaxInt;
IMAP.IOHandler := SSL;
IMAP.UseTLS := utUseImplicitTLS;
IMAP.Connect;
IMAP.SelectMailBox('INBOX');
SetLength(SearchInfo, 1);
SearchInfo[0].SearchKey := skUnseen;
IMAP.UIDSearchMailBox(SearchInfo);
for i := 0 to High(IMAP.MailBox.SearchResult) do begin
MSG := TIdMessage.Create(nil);
try
if IMAP.Retrieve(IMAP.MailBox.SearchResult[i], MSG) then begin
// Here is the problem, I never enter this section
Memo1.Lines.Add(MSG.From.Text);
end;
finally
MSG.Free;
end;
end;
IMAP.Disconnect;
end;
Thanks for your help.
When using SearchMailBox()
, the SearchResult
array contains sequence numbers.
When using UIDSearchMailBox()
, the SearchResult
array contains UIDs.
Retrieve()
expects a sequence number. Since you have UIDs instead, use UIDRetrieve()
, eg:
IMAP.UIDRetrieve(IntToStr(IMAP.MailBox.SearchResult[i]), MSG)