Introducing a new way to review your PRs.

Read the announcement

appwrite / appwrite

The open-source cloud for agents & devs. Including Auth, Databases, Storage, Functions, Messaging, Hosting, Realtime, WAF and more

View on GitHub

59 documents · Updated Nov 20, 2026

docs / smtp-client-library

SMTP client library

The SMTP client library is a reusable package for submitting email to an SMTP server. It manages one SMTP session, turns a message into RFC-compliant wire data, negotiates server features, and reports which recipients received the message. It is part of the reusable platform packages; the compression library and telemetry library describe related packages.

System purpose

The package gives callers one high-level path from a message model to SMTP delivery. It keeps message formatting, connection security, server negotiation, and delivery results separate so callers can choose a transport and retry policy without handling SMTP commands themselves.

The package is designed for submission to a configured server. It does not provide a mail queue, connection pool, or delivery scheduler. A caller or an external pool owns those wider concerns.

References: packages/…/README.md• L6-10 packages/…/Client.php• L17-22 packages/…/composer.json• L1-13

Client lifecycle

The client is lazy and session-based. Creating a Client does not touch the network; the first send or capability query opens the connection and prepares it for mail. One client represents one connection and can handle sequential transactions until it is closed or discarded.

When the client starts a session, it follows this order:

  1. Open the selected transport with the connect timeout.
  2. Read the server greeting.
  3. Send EHLO, or use HELO when the server does not support ESMTP.
  4. Apply the selected TLS mode.
  5. Re-negotiate capabilities after STARTTLS when the connection was upgraded.
  6. Authenticate when authenticators were supplied.
  7. Submit the envelope and message data for each send.

The client drops a session after a connection or protocol failure because the next command could be sent out of sequence. A healthy session can be checked with ping() and ended with close(). Callers that share connections across work units should provide one client per active caller or use an external pool.

sequenceDiagram
    participant Caller
    participant Client
    participant Transport
    participant Server

    Caller->>Client: create client
    Caller->>Client: send message
    Client->>Transport: connect
    Transport->>Server: greeting and session setup
    Client->>Server: EHLO, TLS, and AUTH as needed
    Client->>Server: MAIL FROM and RCPT TO
    Client->>Server: DATA and message bytes
    Server-->>Client: recipient and final replies
    Client-->>Caller: delivery result

References: packages/…/Client.php• L53-73 packages/…/Client.php• L223-261 packages/…/Client.php• L264-351

Message and envelope composition

The message describes what recipients see. The envelope describes where the SMTP transaction sends the bytes. send() derives the envelope from the message, while sendRaw() accepts an explicit envelope and already-built RFC 5322 content for callers that render elsewhere.

The two views can differ by design. Bcc addresses are included in the envelope but never written into message headers. Reply-To is a header only and never becomes an SMTP recipient. The envelope also removes duplicate recipient addresses before the transaction starts.

References: packages/…/Message.php• L10-35 packages/…/Envelope.php• L7-18 packages/…/Envelope.php• L37-59 packages/…/Client.php• L63-71

MIME structure

The message builds its MIME structure from the content supplied by the caller. Plain text and HTML can be sent alone or together. Inline attachments stay with the related content, while normal attachments wrap the complete body in a mixed message.

Message contentMIME shape
Text onlytext/plain
HTML onlytext/html
Text and HTMLmultipart/alternative
Inline attachmentsmultipart/related around the body
Normal attachmentsmultipart/mixed around the body

Text uses quoted-printable encoding. Attachments use base64 encoding. File-backed attachments are read while the message is written, which supports large files without first copying them into the message object. Headers are encoded and folded so non-ASCII values and long address lists remain valid message data.

References: packages/…/Message.php• L133-163 packages/…/Part.php• L32-67 packages/…/Part.php• L87-145 packages/…/Header.php• L34-40 packages/…/Encoding.php• L22-37

SMTP session negotiation

The client learns what the server can do from the multi-line EHLO reply. It uses those capabilities to select security and authentication steps and to add only supported message parameters. If EHLO fails, the client falls back to HELO and treats the server as having no ESMTP extensions.

Capability negotiation

The capability map controls behavior at the point where each feature matters. A message that needs a feature the server does not advertise fails before the client sends an unsupported transaction.

CapabilityClient behavior
STARTTLSAllows a plaintext session to upgrade when the selected encryption mode requires or permits it.
AUTHSelects a compatible configured authenticator.
SIZEAdds a size declaration and rejects an over-limit string message before submission.
8BITMIMEDeclares 8-bit message content when the message is not ASCII.
SMTPUTF8Allows internationalized addresses and headers.
Enhanced status codesAdds structured status information to replies when the server provides it.

The client rebuilds the capability map after STARTTLS. It does not trust the pre-TLS advertisement because the secure session can expose a different feature set.

References: packages/…/Client.php• L264-297 packages/…/Client.php• L353-387 packages/…/Capabilities.php• L7-14 packages/…/Capabilities.php• L29-86

TLS modes

Encryption mode decides when TLS starts and whether the absence of STARTTLS is acceptable. Certificate verification is a separate setting that controls trust in the certificate issuer and the peer name.

ModeSession behavior
NoneKeep the session in plaintext.
OpportunisticUse STARTTLS when the server advertises it; otherwise continue in plaintext.
StartTlsRequire STARTTLS and fail when the server does not advertise it.
ImplicitStart TLS before the SMTP greeting, as used by common submission services on port 465.

The default certificate policy checks both a trusted certificate chain and the peer name. A private authority can use a custom CA or self-signed mode. Disabling verification removes the identity check and should be limited to controlled cases.

References: packages/…/Encryption.php• L7-19 packages/…/Verification.php• L7-22 packages/…/Tls.php• L7-22 packages/…/Client.php• L275-297

Authentication

Authentication runs after the session is secure and uses only mechanisms advertised by the server. The configured authenticators are tried in their given order, so that order is part of the caller's security policy.

The package supplies PLAIN, LOGIN, and XOAUTH2 mechanisms. The Authenticator interface allows another mechanism to participate without changing the client. If no configured mechanism matches the server, or the server rejects the credentials, the client raises an authentication failure and does not begin message delivery.

References: packages/…/Client.php• L299-351 packages/…/Authenticator.php• L7-35 packages/…/Plain.php• L7-31 packages/…/Login.php• L7-35 packages/…/XOAuth2.php• L7-35

Transports and timing

The transport layer moves bytes and performs the socket-level TLS work. The client keeps SMTP line parsing and transaction rules above that layer, so the same session behavior can run over different PHP runtimes.

TransportBest fit
Transport\NativeStandard PHP streams. It also works with Swoole's stream hook.
Transport\SwooleSwoole coroutine code where socket operations must yield without relying on the stream hook.

Both transports use the same TLS options and expose connection, read, write, upgrade, and close operations. The Swoole transport requires ext-swoole and must run inside a coroutine. Certificate name checks can differ for an IP address, so callers using Swoole should provide the DNS name carried by the certificate when they dial an address directly.

Timeouts are separate for connection, read, and write operations. They apply per operation rather than to the whole session, which lets a large message use several bounded writes instead of one session-wide deadline.

References: packages/…/Transport.php• L7-34 packages/…/Native.php• L12-31 packages/…/Swoole.php• L13-19 packages/…/Swoole.php• L181-199 packages/…/Timeouts.php• L7-31

Delivery outcomes

SMTP delivery is not a boolean result because a server can accept some recipients and refuse others. The result records accepted recipients, rejected recipients with their server replies, and a message identifier when the final reply provides one.

OutcomeMeaning for the caller
Complete resultEvery recipient was accepted.
Partial resultSome recipients were accepted and some were refused; the message was sent to the accepted set.
TransactionExceptionEvery recipient was refused, or the server refused the envelope or message data. The attached reply shows whether retry may help.
Other SmtpExceptionConnection, protocol, authentication, capability, timeout, or message production failed outside normal recipient results.

Replies are grouped into four classes: 2yz success, 3yz intermediate, 4yz transient failure, and 5yz permanent failure. A transient transaction failure may be retried by the caller. The library reports that signal but does not queue or retry the message itself.

References: packages/…/Result.php• L7-29 packages/…/Reply.php• L7-37 packages/…/Outcome.php• L9-35 packages/…/TransactionException.php• L7-33 packages/…/SmtpException.php• L7-16

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep Message, Envelope::fromMessage(), and Client::send() aligned so Bcc and Reply-To keep their different roles.
  • Keep MIME tree rules aligned with content-transfer encoding and the SMTP 8BITMIME and SMTPUTF8 checks.
  • When adding an authenticator, keep mechanism selection compatible with the server's AUTH advertisement and with reconnects.
  • When changing TLS setup, keep implicit TLS, STARTTLS renegotiation, capability refresh, and certificate verification aligned across both transports.
  • Keep Result and TransactionException semantics aligned with recipient-level replies so partial delivery is not treated as an all-or-nothing failure.
  • Keep timeout meaning consistent across the client and each transport because the limits are per connection, read, and write operation.

Important failure modes

TriggerConsequenceGuard
The server does not offer required STARTTLS.The session fails before authentication or delivery.Use opportunistic encryption only when plaintext fallback is acceptable.
An internationalized address reaches a server without SMTPUTF8.The message is rejected before MAIL FROM is sent.Use a server that advertises SMTPUTF8 or use ASCII addresses.
No configured authenticator matches the server, or credentials are refused.The session cannot send mail.Check the server's advertised mechanisms and keep authenticator order intentional.
Some recipients receive a refusal while others are accepted.The result is partial and the message already reached the accepted recipients.Process rejected recipients without blindly retrying the whole recipient set.
Every recipient is refused with a 4yz reply.The send raises a retryable transaction exception.Put the message back on the caller's queue according to its retry policy.
Message streaming, reading, or protocol exchange fails mid-send.The connection is not safe for reuse and the send raises an SMTP or message error.Discard the session and let the caller decide whether the message can be safely retried.
Swoole verifies a certificate against an IP literal.TLS setup fails because the transport needs a certificate DNS name.Set Tls::peerName to a name in the certificate or use a transport and policy suited to the endpoint.

Key files

FileWhy to read it
packages/…/Client.phpMain session lifecycle, SMTP transaction flow, capability use, and delivery result creation.
packages/…/Message.phpPublic message model and MIME structure selection.
packages/…/Envelope.phpBoundary between visible headers and SMTP delivery recipients.
packages/…/Part.phpMIME body, multipart nesting, attachment streaming, and transfer encoding.
packages/…/Capabilities.phpInterpretation of the server's EHLO feature list.
packages/…/Encryption.php and packages/…/Tls.phpTLS timing modes and certificate settings.
packages/…/Authenticator.phpExtension point and contract for SMTP authentication mechanisms.
packages/…/Transport.phpRuntime-neutral socket contract used by the client.
packages/…/Result.php and packages/…/TransactionException.phpDelivery reporting and retry-relevant failure signals.