Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

StreamSec.Mail.SMTPSpool

WHAT A 250 MEANS. When an SMTP server answers 250 to the end of DATA it has
  told the client the message is its problem no longer - the client is entitled
  to delete its copy, and every other MTA does. So the accept has to be durable
  BEFORE the reply, and delivery has to keep being attempted afterwards, across
  restarts, until it succeeds or is abandoned with a bounce. That is what this
  unit is: the queue behind StreamSec.Mail.SMTPServer.

  THE COMMIT IS ONE RENAME. Store writes the message body into queue\<id>.msg,
  then writes the envelope into tmp\<id>.env and RENAMES it into queue\. The
  presence of the .env is what makes a message queued, so a crash can leave an
  orphan .msg (collected on the next scan) but never a half-written message that
  looks deliverable. With FlushToDisk set - the default - both files are flushed
  to the platter before the rename, so the guarantee survives power loss and not
  merely process death.

  DELIVERY IS SOMEBODY ELSE'S JOB. The queue decides WHEN to try and what to do
  with the answer; iSmtpDeliveryAgent does the trying. tSmtpSmarthostAgent is
  the shipped implementation and drives TsmCustomSMTPClient at a configured
  smarthost, which is what a submission relay wants; anything else - MX lookup,
  a local mailbox store, a test double - is an interface away.

  WHAT IT IS NOT. It is not a full MTA queue. There is NO per-recipient
  resolution: a message is delivered, deferred or bounced AS A WHOLE, because
  the client API underneath reports one outcome per submission. A message to ten
  recipients of which one is permanently rejected therefore bounces in full
  rather than being split, which is the one place a real MTA would do better -
  it is the honest limit of the layer below, not an oversight, and the shape of
  iSmtpDeliveryAgent is what a per-recipient version would widen.

Feature notes: Mail subsystem notes (SMTP / POP3 / IMAP)

Classes, interfaces and records

classeSmtpSpoolError

inherits from Exception

(no public members)

interfaceiSmtpDeliveryAgent

DOING THE ACTUAL SENDING. The queue owns the schedule; this owns the wire. Deliver runs on a spool worker thread, one message at a time per thread, and may block for as long as the transfer takes - that is the whole reason delivery is off the reactor. aError is what goes into the bounce and the log, so put the far end's own reply text in it.

function Deliver(const aEnvelope: iSmtpEnvelope; const aData: tBytes; var aError: string): tSmtpDeliveryOutcome;

classtSmtpSpool

(no public members)

classtSmtpSpoolItem

One queued message. The BODY IS NOT HERE - it stays on disk until an attempt is made, so a queue of ten thousand messages costs ten thousand envelopes of memory rather than the mail itself.

property Id: string read fId; property Envelope: iSmtpEnvelope read fEnvelope; property Attempts: Integer read fAttempts;
How many delivery attempts have been made and failed.
property FirstAttempt: TDateTime read fFirstAttempt;
UTC. Zero until the first attempt fails.
property NextAttempt: TDateTime read fNextAttempt; property LastError: string read fLastError;
The far end's own words about the last failure.

classtSmtpSpool

THE QUEUE. Create it, point it at a directory, give it an agent, Start it. Store is then safe to call from any thread - and specifically from the reactor thread that is holding an SMTP client waiting for its 250.

constructor Create; destructor Destroy; override; procedure Store(const aEnvelope: iSmtpEnvelope; const aData: tBytes);
DURABLY ACCEPTS aData for the recipients in aEnvelope, and RAISES if it could not. That is the contract the caller needs: an exception here means answer the client 4xx so it keeps its copy and retries, and a normal return means the message will be delivered or bounced by this queue and the client may forget it. Never answer 250 on a Store that raised.
procedure Start;
Reads the directory back in - every message left by a previous run, whatever killed it - and starts the delivery threads. Orphaned files (a body whose envelope never committed, a state file with neither) are collected here.
procedure RequestStop(aFreezeWrites: Boolean = False);
Stops dispatch without joining a worker reporting a fatal error. aFreezeWrites permanently refuses new Store calls as well.
procedure Stop;
Stops accepting new work and winds the threads down. The queue on disk is untouched: whatever has not been delivered is picked up by the next Start. Full description »
procedure Poke;
Wakes the workers now rather than at the next timeout - Store does this itself, so it is only needed after changing the schedule.
procedure Snapshot(aDest: TList);
A snapshot of the queue for an operator display. The items are the live objects, so read them and let go.
function OldestReceivedAt: TDateTime;
THE ARRIVAL TIME (UTC) OF THE OLDEST QUEUED MESSAGE THAT HAS ONE, read under the queue's own lock; 0 when no queued message carries an arrival time - which, for a queue this spool filled itself, means an empty queue and nothing else. Full description »
property Count: Integer read GetCount; property Active: Boolean read fActive; property Stored: Int64 read fStored;
Totals since Start, for a status page.
property Delivered: Int64 read fDelivered; property Bounced: Int64 read fBounced; property Directory: string read fDirectory write SetDirectory;
Where the queue lives. Two subdirectories are created under it, tmp and queue, and nothing else in it is touched. IT MUST NOT BE SHARED between two running spools: the commit protocol is safe against a crash, not against a second process scanning the same directory.
property StoreGate: tMaildir read fStoreGate write SetStoreGate;
Retains the store and serializes queue writes with its fatal latch. Assign before starting workers. Nil is an independent queue.
property Agent: iSmtpDeliveryAgent read fAgent write fAgent; property RetryIntervals: string read fRetryIntervals write SetRetryIntervals;
Comma-separated seconds; the last one repeats. See cSmtpDefaultRetryIntervals.
property MaxAge: Integer read fMaxAge write fMaxAge;
Seconds a message may stay in the queue before it is bounced. 0 = never expire, which means a permanently unreachable destination accumulates messages for ever - deliberate, and rarely what you want.
property DeliveryThreads: Integer read fDeliveryThreads write SetDeliveryThreads; property DrainTimeout: Cardinal read fDrainTimeout write fDrainTimeout; property FlushToDisk: Boolean read fFlushToDisk write fFlushToDisk;
Flush each spool file to the platter before committing it. Off makes Store faster and makes "accepted" mean "the OS has it" rather than "the disk has it" - which is a promise to the client this library would rather not break, so it defaults on.
property Postmaster: string read fPostmaster write fPostmaster;
The address a bounce comes from, e.g. 'postmaster@example.com'. A bounce is sent with an EMPTY reverse path whatever this says - that is what stops bounce loops - so this is the From: header only. Leave it '' and bounces are not generated at all.
property ServerName: string read fServerName write fServerName;
This host's name, for the bounce's own Received-style identification.
property OnDelivered: tSmtpSpoolEvent read fOnDelivered write fOnDelivered; property OnDeferred: tSmtpSpoolEvent read fOnDeferred write fOnDeferred; property OnUndeliverable: tSmtpSpoolFailureEvent read fOnUndeliverable write fOnUndeliverable;
A message is being abandoned. aBounce arrives True when a bounce is possible - i.e. Postmaster is set and the reverse path is not empty - and setting it False suppresses it.
property OnLog: tSmtpSpoolLogEvent read fOnLog write fOnLog;

recordtSmtpDeliveryReport

WHERE AN ATTEMPT ENDED AND WHAT ENDED IT, for a consumer whose policy turns on more than the outcome. The agent frees its client inside Deliver, so without this the stage and the reply code die there and the only thing left to reason from is aError's text - which this record exists to abolish as a programming interface.

Stage: tSmtpDeliveryStage;
Where the attempt had got to when it ended - the client's own Stage, never inferred from the exception's text.
ReplyCode: Integer;
The reply code behind the failure, 0 when the failure was not an SMTP reply (a timeout, a malformed reply, a refused local precondition); on success the final reply's code. NOTE that 0 does not mean no server bytes were involved: a malformed reply quotes 32 raw characters of it.
SmtpError: Boolean;
Whether the SMTP LAYER ITSELF failed - a reply the far end sent, a malformed reply line, or one of the client's refused local preconditions - as opposed to anything under it. Full description »

recordtSmtpProbeResult

WHAT A COMMISSIONING PROBE FOUND. Nothing is ever submitted.

Opened: Boolean;
Open completed: TCP, TLS validated, the greeting, EHLO (STARTTLS and a second EHLO on that path), and AUTH when UserName is set.
Authenticated: Boolean;
The client's Authenticated after Open - False when UserName is empty.
SenderTried: Boolean;
MAIL FROM was sent.
SenderAccepted: Boolean;
And its reply was 2xx.
Report: tSmtpDeliveryReport;
Where it stopped; MAIL's code when SenderTried.
Extensions: TArray<string>;
The EHLO keyword lines learned after Open, in the server's order.

classtSmtpSmarthostAgent

inherits from TInterfacedObject

implements iSmtpDeliveryAgent

THE SHIPPED AGENT: everything goes to one smarthost. That is the submission relay shape - an application hands its mail to a provider that owns the MX lookups, the reputation and the retry policy of the wider internet, and this queue owns only the hop to it. A CLIENT PER DELIVERY, deliberately: TsmCustomSMTPClient is a stateful component with a live connection, holding one open across idle periods invites the far end to close it under us, and reconnecting is a few milliseconds against a transfer measured in hundreds.

constructor Create; function Deliver(const aEnvelope: iSmtpEnvelope; const aData: tBytes; var aError: string): tSmtpDeliveryOutcome; overload; function Deliver(const aEnvelope: iSmtpEnvelope; const aData: tBytes; var aError: string; out aReport: tSmtpDeliveryReport): tSmtpDeliveryOutcome; overload;
THE SAME DELIVERY, WITH WHERE IT GOT TO. Identical in every outcome and every aError text to the three-argument form, which calls it; the report is the only addition. A queue that must tell an account fault from a recipient's, or a breaker that must not be driven by whoever gets to choose a recipient, needs the stage - and the stage is unrecoverable afterwards, because the client is freed in here.
function Probe(const aMailFrom: string; var aError: string): tSmtpProbeResult;
OPENS A SESSION WITH EXACTLY THE CONFIGURATION Deliver USES, then - when aMailFrom is not '' - asks whether that reverse path is acceptable and resets, then closes. Full description »
procedure SetPassword(const aValue: string);
Wraps aValue in wiped storage, as TsmCustomSMTPClient.SetPassword does.
property Host: string read fHost write fHost; property Port: Word read fPort write fPort;
465 for sdtImplicit, 587 for sdtRequired, 25 for sdtOpportunistic. It is not derived from TLSMode: a provider may put any of them anywhere.
property TLSServer: TsmSimpleTLSInternalServer read fTLSServer write fTLSServer;
THE TRUST CONFIGURATION FOR THE OUTBOUND LEG, SHARED ACROSS DELIVERIES. Outbound is its own trust domain and it is not the listener's: what the onward leg has to trust is whoever answers at the far end. Full description »
property TLSMode: tSmtpDeliveryTlsMode read fTLSMode write fTLSMode;
See tSmtpDeliveryTlsMode - and read what sdtOpportunistic does NOT protect against before choosing it.
property UserName: string read fUserName write fUserName; property Password: iSecretKey read fPassword write fPassword; property HeloName: string read fHeloName write fHeloName; property SourceIP: string read fSourceIP write fSourceIP;
Local source literal for delivery AND Probe. Empty keeps OS selection.
property ConnectTimeout: Cardinal read fConnectTimeout write fConnectTimeout; property OnConfigure: tSmtpAgentConfigureEvent read fOnConfigure write fOnConfigure;
PER-DELIVERY adjustment of the client, called with the shared TLSServer already assigned and everything else set. Full description »

Types (enumerations, sets, aliases)

enumtSmtpDeliveryOutcome

What an attempt at delivery came to.
sdoDelivered gone; the spool files are removed.
sdoTransient 4xx, a connection failure, a timeout - try again later.
sdoPermanent 5xx - the destination has refused it and will refuse it again, so retrying is only noise. Bounces.

  tSmtpDeliveryOutcome = (sdoDelivered, sdoTransient, sdoPermanent);

enumtSmtpDeliveryTlsMode

HOW MUCH TLS THE ONWARD LEG INSISTS ON. One property rather than an implicit-TLS flag beside a require-TLS flag: the two together can express states nobody wants and can disagree with each other, and which of them wins is exactly the kind of thing that gets discovered in production. THERE IS NO 'never' MEMBER, deliberately. The client upgrades whenever the far end advertises STARTTLS and there is no way to tell it not to, so a cleartext-only mode would be a name that lies.

  tSmtpDeliveryTlsMode = (
    { TLS from the first octet, port 465 (RFC 8314). THE DEFAULT, and the right
      answer for a smarthost you control: there is no cleartext phase for an
      active attacker to interfere with. }
    sdtImplicit,
    { STARTTLS on a cleartext port (conventionally 587), and REFUSE TO DELIVER
      if the far end does not offer it. }
    sdtRequired,
    { STARTTLS when the far end offers it, cleartext when it does not - the
      posture RFC 3207 describes for mail between servers, where refusing to
      deliver is worse than delivering unencrypted.

      IT PROTECTS AGAINST A PASSIVE OBSERVER AND NOTHING ELSE. An active
      attacker strips STARTTLS from the EHLO response and this mode then sends
      in the clear, by design, without complaint. Do not choose it for a
      smarthost you have a trust relationship with - choose sdtRequired or
      sdtImplicit there, and keep this for a destination you cannot dictate to.

      IT STILL VERIFIES WHOEVER ANSWERS. If STARTTLS IS offered, the handshake
      must succeed and the certificate must validate; an untrusted certificate
      fails the delivery rather than falling back. That is deliberately stricter
      than a typical internet MTA, which would accept anything - loosening it is
      a trust decision, and it belongs in OnConfigure where it is visible. }
    sdtOpportunistic);

enumtSmtpFailureReason

Why a message left the queue without being delivered - what OnUndeliverable is told, and what the bounce says.

  tSmtpFailureReason = (sfrRejected,     // a permanent refusal from the far end
                        sfrExpired,      // MaxAge passed with no delivery
                        sfrUnbounceable);// failed, and there was nobody to tell

proctSmtpSpoolEvent

  tSmtpSpoolEvent = procedure (Sender: TObject;
                               aItem: tSmtpSpoolItem) of object;

proctSmtpSpoolFailureEvent

  tSmtpSpoolFailureEvent = procedure (Sender: TObject; aItem: tSmtpSpoolItem;
                                      aReason: tSmtpFailureReason;
                                      var aBounce: Boolean) of object;

proctSmtpSpoolLogEvent

Anything worth telling an operator. aFatal marks the ones that mean the queue is not working - an unwritable directory, a corrupt spool file - as opposed to the ordinary business of a deferred message.

  tSmtpSpoolLogEvent = procedure (Sender: TObject; const aText: string;
                                  aFatal: Boolean) of object;

proctSmtpAgentConfigureEvent

Configures the SMTP client for one delivery: trust anchors, a client certificate for mutual TLS, timeouts. Called on the worker thread with a freshly created client each time.

  tSmtpAgentConfigureEvent = procedure (Sender: TObject;
                                        aClient: TsmCustomSMTPClient) of object;

typetSmtpDeliveryStage

NOT REDECLARED HERE, RE-EXPORTED. tSmtpDeliveryStage is declared in StreamSec.Mail.SMTPClient - the unit whose own code moves it - so that a consumer sees ONE type and cannot end up holding two enumerations that drift apart. The member names belong to the declaring unit: name it in the uses clause to write sdsMail rather than to merely pass the value on.

  tSmtpDeliveryStage = StreamSec.Mail.SMTPClient.tSmtpDeliveryStage;

Routines