Contents · Forum Home · StreamSec Tools 4.1.5.363 documentation

StreamSec.Mail.Message

Parses and composes Internet messages - .eml files and streams - as defined
  by RFC 5322 (message format), RFC 2045-2047 and RFC 2049 (MIME). The unit
  carries the tMailHeaders / tMimeEntity engine plus the TsmEmail component
  that applications drop on a form or create in code.

  THE ONE DESIGN RULE EVERYTHING ELSE FOLLOWS FROM: every entity RETAINS THE
  EXACT OCTETS it was parsed from, and re-emits them verbatim for as long as
  the entity has not been modified. S/MIME multipart/signed verification needs
  the byte-exact canonical source of the signed body part - headers included,
  transfer encoding preserved, CRLF intact - and a mail model that re-encodes
  parts on output (the reason the old Indy-based S/MIME demo could never
  verify a detached signature) destroys precisely those bytes. Mutating a
  header or a body invalidates the retained source of that entity and of
  every ancestor whose body contains it; untouched siblings still re-emit
  their original octets, so wrapping a parsed entity as a part of a new
  multipart/signed keeps the signed bytes stable.

  WHAT THIS UNIT IS NOT: it is no transport and no crypto. SMTP lives in
  StreamSec.Mail.SMTPClient; S/MIME wrapping lives in
  StreamSec.Mail.SMIMEBroker; both consume this engine.

  Data is tBytes throughout, for the same reason StreamSec.Http.Client is:
  OctetString is conditionally an AnsiString variant, a dynamic array or a
  record, and only the AnsiString form supports the Pos/Copy idioms a parser
  needs, whereas tBytes is a plain byte array on every supported compiler.
  Header values live in native strings, narrowed and widened BYTE-WISE
  (Latin-1); anything outside that range must travel through the RFC 2047
  encoder, which is what real mail requires anyway.

  TOLERANT IN, STRICT OUT. The parser accepts bare-LF line ends, missing
  colons, unknown transfer encodings and folded headers of every provenance,
  because .eml files in the wild carry all of those. The composer emits CRLF
  line ends, folded headers below 78 columns and RFC 2047 encoded words -
  and SetField REJECTS names or values carrying CR or LF outright, because a
  header value assembled from attacker-influenced text is the header-injection
  family. Bounds (header block size, field count, nesting depth, part count)
  are enforced on parse so a hostile message cannot balloon memory.

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

Classes, interfaces and records

classeMailMessageError

inherits from Exception

(no public members)

recordtMailAddress

One parsed mailbox: DisplayName is the human-readable phrase (RFC 2047 decoded), Address the bare addr-spec (local@domain).

DisplayName: string; Address: string;

classtMailHeaders

An ordered collection of header fields. Order is preserved and duplicate names are legal (Received, for one). Values are stored UNFOLDED and otherwise raw - RFC 2047 encoded words are decoded on demand by DecodedField, never in place, so a round-trip does not rewrite what it merely read. The original header block octets are retained and re-emitted verbatim until the first mutation (Pristine).

destructor Destroy; override; procedure Clear;
Removes every field and the pristine block.
property Pristine: Boolean read fPristine;
True while the header block has not been modified since it was parsed; ComposeTo then re-emits the original octets byte for byte.
property Count: Integer read fCount; property Names[aIndex: Integer]: string read GetName; property Values[aIndex: Integer]: string read GetValue write SetValue;
The raw, unfolded value at aIndex. Writing marks the block modified.
function HasField(const aName: string): Boolean;
Returns True if IndexOf(aName) is greater than or equal to 0; otherwise False.
function Field(const aName: string): string;
The raw, unfolded value of the FIRST field named aName, or ''. Header names compare case-insensitively throughout.
function DecodedField(const aName: string): string;
Field with RFC 2047 encoded words decoded - the human-readable form of Subject, display names and the like.
procedure SetField(const aName, aValue: string);
Replaces the first field named aName, or appends one. The value is stored as given, so it must already be ASCII or Latin-1; use SetTextField for arbitrary text. Raises on CR or LF in either argument - a value assembled from untrusted text is the header injection family - and on characters outside Latin-1.
procedure SetTextField(const aName, aText: string);
As SetField, but non-ASCII text is converted to RFC 2047 encoded words (UTF-8, B encoding) first, so any string is legal.
procedure AddField(const aName, aValue: string);
Appends without replacing - for fields that legally repeat.
procedure RemoveField(const aName: string);
Removes every field named aName. Removing a name that is not present is not an error and does not mark the block modified.
function ParamValue(const aName, aParam: string): string;
The value of parameter aParam of the FIRST field named aName, with RFC 2045 quoting removed - ParamValue('Content-Type','boundary') is the canonical use. '' when the field or the parameter is absent. RFC 2231 continuations and charset-tagged parameters are NOT decoded; the raw parameter value is returned for a name*= match.
procedure ParseFrom(const aData: tBytes; aOffset, aCount: Integer);
Parses one header block (everything before the blank separator line). Folded lines are unfolded; a line without a colon is skipped. Does not fire the change notification: parsing is construction, not mutation.
procedure ComposeTo(aDst: TStream);
Writes the block: the pristine octets when unmodified, otherwise each field folded at cMailFoldColumn. Does NOT write the blank separator line - that belongs to the entity.
procedure CopyFrom(aSource: tMailHeaders);
Deep copy, including pristine state.

classtMimeEntity

One MIME entity: a header block plus either a leaf body or child parts. The root entity of a message is the message itself. RawSource re-emits the exact parsed octets for as long as the entity is unmodified - see the unit comment for why that is the load-bearing feature.

constructor Create(aParent: tMimeEntity = nil); destructor Destroy; override; procedure Clear;
Releases headers, body, retained source and child parts. Body buffers are wiped before release - a decrypted S/MIME payload may have passed through them.
property Parent: tMimeEntity read fParent; property Headers: tMailHeaders read fHeaders; function MediaType: string;
The lowercased type/subtype token of Content-Type, defaulting to text/plain when the field is absent (RFC 2045 s5.2).
function IsMultipart: Boolean;
Returns True if Copy(MediaType, 1, 10) equals 'multipart/'; otherwise False.
function Boundary: string;
The boundary parameter, or ''.
function CharSet: string;
The charset parameter, lowercased, or ''.
function TransferEncoding: tMailEncoding; function FileName: string;
The attachment file name: Content-Disposition filename, falling back to the legacy Content-Type name, RFC 2047 decoded when so encoded.
function IsAttachment: Boolean;
True when Content-Disposition marks this part an attachment.
function RawBody: tBytes;
The body exactly as it stands on the wire, transfer encoding intact. Treat the returned array as read-only.
function DecodedBody: tBytes;
The body with its Content-Transfer-Encoding removed. An meUnknown encoding returns the raw body unchanged rather than guessing.
function BodyText: string;
DecodedBody interpreted through the charset parameter. us-ascii, utf-8, iso-8859-1 and windows-1252 are decoded exactly; anything else falls back to Latin-1 so no byte is ever lost, merely displayed wrong.
procedure SetBody(const aData: tBytes; aEncoding: tMailEncoding; const aMediaType: string = '');
Replaces the body: aData is transfer-encoded as requested and the Content-Transfer-Encoding header is set to match. A non-empty aMediaType replaces Content-Type. Child parts, if any, are dropped.
procedure SetRawBody(const aData: tBytes);
Replaces the on-the-wire body octets VERBATIM - no transfer encoding is applied and no header is touched, so the caller keeps Content-Type and Content-Transfer-Encoding truthful. Child parts are dropped. This is the S/MIME broker's tool for moving an already-encoded entity body without disturbing a single byte of it.
procedure SetBodyText(const aText: string; const aCharSet: string = 'utf-8');
Replaces the body with quoted-printable encoded text. aCharSet must be one of utf-8 (the default), us-ascii or iso-8859-1.
function PartCount: Integer;
Returns the current value of the fPartCount field.
property Parts[aIndex: Integer]: tMimeEntity read GetPart; function AddPart: tMimeEntity;
Appends an empty child part. The entity must already be multipart - call MakeMultipart first when converting a leaf.
function AddPartFromBytes(const aData: tBytes): tMimeEntity;
Appends a child parsed from a complete serialized entity (headers, blank line, body). The child retains aData as its pristine source, so composing the parent re-emits those octets byte for byte - this is how the S/MIME broker builds multipart/signed without disturbing the signed bytes.
procedure DeletePart(aIndex: Integer); procedure MakeMultipart(const aSubType: string);
Converts this entity to multipart/<aSubType> with a fresh random boundary. Existing content (Content-* headers and body) moves into a new first child part; an entity with no content becomes an empty multipart. Calling it on an entity that is already multipart is a no-op.
procedure Parse(const aData: tBytes);
Parses a complete entity from aData.
procedure ParseWithBudget(const aData: tBytes; aDepth: Integer; var aPartTotal: Integer);
Continues a consuming MIME walk through message/rfc822. The budget includes parts already parsed at earlier levels and sibling messages.
property NestingDepth: Integer read fNestingDepth; procedure DiscardBodyStorage;
Consumes retained source/body octets while keeping headers and child entities. A description walk may discard ancestors before descending; RawSource and RawBody no longer describe the original entity.
function RawSource: tBytes;
The complete entity - byte-exact while unmodified.
procedure ComposeTo(aDst: TStream);

classTsmEmail — component reference

inherits from TComponent

An Internet mail message: parse and compose .eml files or streams, read and write the envelope headers, walk or build the MIME part tree via Root. The published address and subject properties present the DECODED, human-readable view (setting them applies RFC 2047 encoding as needed); the raw header values remain reachable through Headers.

A parsed message that is saved unmodified round-trips byte for byte.

constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Clear; procedure LoadFromStream(aStream: TStream); procedure LoadFromFile(const aFileName: string); procedure LoadFromBytes(const aData: tBytes); procedure SaveToStream(aStream: TStream); procedure SaveToFile(const aFileName: string); function SaveToBytes: tBytes;
Returns the RawSource value, obtained via fRoot. » member page
property Root: tMimeEntity read fRoot;
The message entity itself: headers plus body or part tree. » member page
function Headers: tMailHeaders;
The message header block - Root.Headers, published here because every caller needs it. » member page
procedure NewMessage;
Resets to an empty message carrying MIME-Version: 1.0 and a Date of now. Address fields, subject, body and attachments are then set by the caller. » member page
procedure GenerateMessageId(const aDomain: string = '');
Sets a Message-ID of the form <unique@domain>; aDomain defaults to the From address's domain, then to 'localhost'. » member page
procedure SetTextBody(const aText: string; const aCharSet: string = 'utf-8');
Sets the text body: on a non-multipart message it replaces the body; on a multipart message it replaces the existing text part. » member page
function AddAttachment(const aData: tBytes; const aFileName: string; const aMediaType: string = ''): tMimeEntity;
Appends an attachment, converting the message to multipart/mixed when needed. aMediaType defaults to application/octet-stream. » member page
function FindTextEntity: tMimeEntity;
The entity carrying the message text: the root itself for a plain message, the preferred text part of a multipart (text/plain before text/*, attachments skipped). nil when there is none. » member page
function BodyText: string;
FindTextEntity's decoded text, or ''. » member page
function FromAddress: string;
The bare addr-spec of the first From mailbox, or ''. » member page
function SenderAddress: string;
Sender when present, else FromAddress - the SMTP reverse path. » member page
function GetEnvelopeAddresses(aList: TStrings; aIncludeBcc: Boolean): Integer;
Collects the bare addr-specs of Recipients (To), Cc and - when aIncludeBcc - Bcc into aList, deduplicated case-insensitively. Returns the number of addresses added. This is the SMTP forward-path list and the S/MIME encryption recipient list. » member page
function Date: TDateTime;
The Date header as UTC, or 0 when absent or unparsable. » member page
procedure SetDate(aUTC: TDateTime);
Writes the Date header from a UTC time, rendered in local time with the local zone offset. » member page
property Subject: string read GetSubject write SetSubject;
Subject, decoded. Setting a non-ASCII subject emits RFC 2047 encoded words. » member page
property From: string read GetFrom write SetFrom; property Sender: string read GetSender write SetSender; property ReplyTo: string read GetReplyTo write SetReplyTo; property Recipients: string read GetRecipients write SetRecipients;
The To header. Named Recipients because to is a reserved word in Delphi; the Cc and Bcc lists are separate properties, and GetEnvelopeAddresses collects all three. » member page
property Cc: string read GetCc write SetCc; property Bcc: string read GetBcc write SetBcc; property MessageId: string read GetMessageId write SetMessageId;

Types (enumerations, sets, aliases)

enumtMailEncoding

The Content-Transfer-Encoding of an entity body. meUnknown preserves a foreign encoding verbatim: DecodedBody then returns the raw body rather than guessing.

  tMailEncoding = (me7Bit, me8Bit, meBinary, meQuotedPrintable, meBase64,
                   meUnknown);

arraytMailAddressArray

  tMailAddressArray = array of tMailAddress;

Routines