Use TsmIMAPClient to open a mailbox read-only and fetch each message into a TsmEmail. The messages keep their unread status.
ServerName to the name in the certificate - see Download a page over HTTPS.uses
System.SysUtils, StreamSec.Mail.IMAPClient, StreamSec.Mail.Message;
function NewImapReader(const aHost: string; aPort: Word; aImplicitTLS: Boolean; const aCAFile, aUser, aPassword: string): TsmIMAPClient; begin Result := TsmIMAPClient.Create(nil); try Result.Host := aHost; Result.Port := aPort; Result.ImplicitTLS := aImplicitTLS; Result.RequireTLS := True; if Result.TLSServer.LoadRootCertsFromFile(aCAFile) = 0 then raise eIMAPClientError.CreateFmt('No certificate in %s', [aCAFile]); Result.UserName := aUser; Result.SetPassword(aPassword); except Result.Free; raise; end; end;
Give NewImapReader the provider's DNS name, the port, the TLS mode, a trusted issuer file and the account credentials. Use port 993 and aImplicitTLS = True for TLS from the first byte. For an account configured for STARTTLS, use port 143 and False. With RequireTLS set, the client must complete the upgrade before it signs in. For more trust options, see Choose which servers a client trusts.
procedure ReadImapMailbox(aClient: TsmIMAPClient; const aMailbox: string; const aReadMessage: TProc<Cardinal, TsmEmail>); var lUid: Cardinal; lMessage: TsmEmail; begin aClient.Open; try aClient.SelectMailbox(aMailbox, True); // EXAMINE the mailbox read-only lMessage := TsmEmail.Create(nil); try for lUid in aClient.Search('ALL') do begin aClient.FetchMessage(lUid, lMessage); aReadMessage(lUid, lMessage); end; finally lMessage.Free; end; finally aClient.Close; end; end;
Pass the client, the mailbox name (for example, INBOX), and a procedure that takes a Cardinal UID and a TsmEmail. Inside the procedure, read Subject and BodyText, or copy the values you want to keep. The sample reuses the message object for the next UID and frees it before returning. Free the client when you have finished with it.
Search('ALL') returns the message UIDs. An empty mailbox produces no calls to the procedure. Use Search('UNSEEN') to select unread mail.FetchMessage uses BODY.PEEK[], which leaves the Seen flag alone. The client accepts messages up to MaxResponse octets (64 MiB by default). Use FetchHeaders when you only need the header fields.Selected.UidValidity with it. Discard the saved UIDs when that value changes. Another client can remove a message between search and fetch. FetchMessage raises eIMAPClientError if the UID has gone.The mail notes cover mailbox selection, search and other IMAP commands.
TsmIMAPClient · TsmEmail · StreamSec.Mail.IMAPClient · StreamSec.Mail.Message