sugarcraft / candy-mail
Email sender for PHP, modeled on the charmbracelet/pop Go tool — send via the Resend HTTP API, the Mailgun HTTP API or direct SMTP. Compose from stdin, attach files, supports CC/BCC, HTML body.
Requires
- php: ^8.3
- sugarcraft/sugar-async: dev-master
- sugarcraft/sugar-core: dev-master
Requires (Dev)
- phpstan/phpstan: ^2.2
- phpstan/phpstan-phpunit: ^2.0
- phpunit/phpunit: ^10.5
Suggests
- ext-curl: Required by the Resend and Mailgun API transports (ResendTransport, MailgunTransport); direct SMTP works without it
- ext-fileinfo: Enables automatic MIME type detection for attachments created from file paths
- ext-openssl: Required for STARTTLS and implicit-TLS SMTP connections
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-20 01:04:00 UTC
README
CandyMail
candy-mail — an email sender for PHP 8.3+, a native PHP port of Charmbracelet's pop mail tool, delivering via the Resend HTTP API, the Mailgun HTTP API, or direct SMTP. Send-only by design: candy-mail composes and dispatches mail; it does not read, store, or manage an inbox.
Formerly published as
sugarcraft/sugar-post(renamed 2026-10). Namespace changed:SugarCraft\Post\→SugarCraft\Mail\.
Features
- Three transports — send via the Resend HTTP API (Resend is a hosted email API:
sign up at resend.com and create an API key), the Mailgun HTTP
API (
MailgunTransport, US and EU regions, multipart with attachments and inline images), or raw SMTP - Compose TUI —
candy-mail tui(or a barecandy-mailon a terminal) opens an interactive compose form: From/To/Cc/Bcc/Reply-To/Subject/Body/HTML body/Attachments, Ctrl+S sends through the same transport ladder as the CLI, Ctrl+P previews the MIME offline - Email value object — from, to, cc, bcc, subject, body, HTML body, reply-to, attachments, signature (the signature joins the plain-text body only — an HTML-only mail silently drops it)
- Custom headers —
withHeader()accumulates arbitrary extension headers (List-Unsubscribe, In-Reply-To,X-…) in insertion order behind the fixed set; the names the message and the transports compose themselves (From, To, Cc, Bcc, Subject, Reply-To, Date, Message-ID, MIME-Version, Content-Type, Content-Transfer-Encoding) are refused, and every value rides the same CRLF/control-byte gate as the subject - HTML accessibility — the authored HTML is embedded verbatim (nothing post-processes it),
so set
<html lang="…">, give images alt text, and keep a meaningful plain-text body: it is the reader-facing text alternative inside themultipart/alternative, what reaches anyone your HTML does not. NoContent-Languageheader is emitted — the language lives in the document, not the envelope. - File attachments — attach from disk paths (
withAttachment()), or pass raw in-memory bytes withAttachment::fromContent()via the constructor'sattachments:parameter - Inline attachments (CID) —
withInlineAttachment()embeds images addressed ascid:…; honoured by the SMTP transport's MIME builder and by the Mailgun multipart POST (theinlinepart carries the Content-ID as its filename). The Resend transport refuses an inline attachment with anInvalidArgumentExceptionkeyedresend.cid_unsupportedbefore any HTTP call, so nothing is sent — use SMTP or Mailgun for CID embedding. The CLI has no inline door:--attachproduces ordinary attachments only —cid:embedding is library-only. - CC/BCC support — full carbon-copy / blind carbon-copy routing (envelope RCPT for all, headers for visible sets)
- Header-injection defense — CR/LF in subjects, addresses, attachment names, and MIME types is refused, not folded.
- Body hygiene is a different posture. Plain-text and HTML bodies have stray C0/DEL
characters silently deleted (tabs and newlines survive); that is tidying, not a
refusal — a body is never rejected for it. And the HTML part ships as authored: no tag
or attribute filtering happens here, so sanitize untrusted HTML caller-side before
handing it to
--html/withHtmlBody(). - TLS by default — STARTTLS is required on SMTP unless explicitly relaxed (see below); credentials are never sent over a plaintext channel
- CLI — one-shot sending with STDIN compose,
--renderfor offline MIME preview, and translated error messages (the CLI translates at startup; library errors route through the same facade — see Internationalisation) - PHP 8.3+ — pure PHP. The composer
suggestentries are honestly scoped:ext-curlis needed only for the Resend and Mailgun transports,ext-fileinfoimproves automatic MIME detection for path attachments, andext-opensslis required for TLS — without it the SMTP transport refuses every encrypted connection (STARTTLS and port-465 alike); only plain, unencrypted SMTP works without it.
Install
composer require sugarcraft/candy-mail
Sibling sugarcraft/* requirements track dev-master, so the plain command above
only resolves when dev stability is allowed: pin the package with composer require sugarcraft/candy-mail:@dev, or set minimum-stability: "dev" together with
prefer-stable: true in your consuming manifest. The transitive pull is the part
that bites a naive consumer: this package's own sugarcraft/sugar-async and
sugarcraft/sugar-core requires are themselves pinned to dev-master, so
allowing dev only for candy-mail still hits the stability wall on those siblings —
the @dev pin (or the manifest-wide pair) covers the whole closure. The global
install takes the same form: composer global require sugarcraft/candy-mail:@dev.
The bin/candy-mail bootstrap walks an autoload candidate ladder (package-local
vendor/autoload.php first, then the consumer project's ../../../autoload.php), so
the CLI runs from a standalone clone, a composer install, or a built phar (which reads
its own bundled vendor). In the monorepo checkout, php candy-mail/bin/candy-mail
works after scripts/refresh-deps.php.
Standalone phar
Run the single-file phar — no Composer, no vendor/: download candy-mail.phar
and its candy-mail.phar.sha256 sidecar from the candy-mail/latest release,
verify, and run:
curl -LO https://github.com/detain/sugarcraft/releases/download/candy-mail/latest/candy-mail.phar curl -LO https://github.com/detain/sugarcraft/releases/download/candy-mail/latest/candy-mail.phar.sha256 sha256sum -c candy-mail.phar.sha256 php candy-mail.phar --version
dev is a rolling prerelease channel: the archive is rebuilt and re-stamped on
every master push that touches this app, so the phar there carries the newest
such commit — the dev-<shortsha> --version prints is the commit it was
packed from.
Or build the phar from a checkout:
php -d phar.readonly=0 tools/build-phar.php [--out=dist/candy-mail.phar]
Three prerequisites: -d phar.readonly=0 is build-only, never a runtime
requirement; the tree must be clean, committed, and non-detached (the integrity
preflight refuses anything else); and the packaged vendor must be the published,
--no-dev one — a linked-mode (symlinked-sibling) vendor would freeze
working-tree bytes into the artifact.
Command-line consumers
After composer require sugarcraft/candy-mail in your project the bin lands at
vendor/bin/candy-mail next to your autoloader; the candidate ladder above
resolves it. For a PATH-visible copy, install it globally:
composer global require sugarcraft/candy-mail
Requirements
| Need | Extension | Without it |
|---|---|---|
| Any TLS — STARTTLS or port-465 implicit | ext-openssl |
named refusal (smtp.openssl_missing) before dialling; only plain SMTP works |
| The Resend transport | ext-curl |
named refusal (resend.curl_missing) at send time; SMTP is unaffected |
| The Mailgun transport | ext-curl |
named refusal (mailgun.curl_missing) at send time; SMTP is unaffected |
| MIME types for path attachments | ext-fileinfo |
sniffing degrades to the extension-suffix table (Attachment::EXT_TO_MIME), unknown suffixes become application/octet-stream — sends still work |
| The forked fake-server test legs | pcntl (dev only) |
dialogue suites skip (or fail loudly under CANDY_MAIL_REQUIRE_DIALOGUE_TESTS=1) |
Check what your interpreter has: php -m | grep -E 'curl|openssl|fileinfo'. On Debian and
Ubuntu the three ship as sudo apt install php8.3-curl php8.3-openssl php8.3-fileinfo
(other distros carry the same extension names through their PHP package manager).
Quick Start
Both construction styles ship. The examples below lead with constructor
arguments (the form that mirrors pop's wiring); the fluent house style —
Email::new() with with*() setters where every setter returns a fresh
instance — appears in the Attachment section.
Resend API
use SugarCraft\Mail\{Email, Mailer, ResendTransport}; $transport = new ResendTransport('re_xxxxxxxxxxxxx'); // or omit the argument to read RESEND_API_KEY from the environment $mailer = new Mailer($transport); $email = new Email( from: ['you@example.com'], to: ['them@example.com'], subject: 'Hello from CandyMail', body: 'Sent via the Resend API.', ); $mailer->send($email);
Mailgun API
use SugarCraft\Mail\{Email, Mailer, MailgunTransport}; // key + sending domain; region 'eu' for accounts on api.eu.mailgun.net $transport = new MailgunTransport('key-xxxxxxxx', 'mg.example.com', MailgunTransport::REGION_US); (new Mailer($transport))->send(Email::new('you@example.com', 'them@example.com', 'Hello', 'Sent via Mailgun.'));
The request is a hand-assembled multipart/form-data POST to
https://api.mailgun.net/v3/<domain>/messages with Basic auth (api:<key>).
Attachments ride attachment, inline (cid) images ride inline with the Content-ID
as the part filename, and extension headers ride h:<Name>. The hardening matches
the Resend transport (TLS peer verification, TLS 1.2 floor, no ambient proxy, key
masked in __debugInfo(), serialisation refused).
Compose TUI
candy-mail tui --from me@example.com --to you@example.com
Tab/Shift+Tab change field. In the body and the HTML field, Enter inserts a newline
and Up/Down move between lines, changing field only from the first or last line; in
the other fields Enter advances and Up/Down change field. Ctrl+S sends, Ctrl+P toggles an offline MIME preview, Ctrl+U clears the field, Ctrl+Q
quits, and Esc quits on the edit screen (pressed twice when there are unsent edits; Esc
in the preview returns to editing). Address fields are
comma-separated; the Attachments field takes comma-separated file paths. Flags and
CANDY_MAIL_* env prefill the form; the transport is resolved at send time, so a
missing credential shows in the status line rather than blocking the form. A bare
candy-mail with piped stdin/stdout keeps the classic usage refusal. --html and
--reply-to are not editable in the form (use the one-shot CLI).
SMTP
use SugarCraft\Mail\{Email, Mailer, SmtpTransport}; // TLS is required by default: the send refuses to proceed (or to send // credentials) unless the channel is encrypted. $transport = new SmtpTransport( host: 'smtp.gmail.com', port: 587, username: 'you@gmail.com', // Gmail rejects raw account passwords: app passwords, see // https://support.google.com/accounts/answer/185833 password: 'your-16-char-app-password', ); // In unattended code feed these four arguments from your environment or // secrets store - the CLI builds the same object from CANDY_MAIL_SMTP_* // rows in bin/candy-mail (buildTransport), a good worked example. $mailer = new Mailer($transport); $mailer->send(new Email( from: ['you@gmail.com'], to: ['them@example.com'], subject: 'Hello via SMTP', body: 'Sent directly via SMTP.', ));
Attachment
use SugarCraft\Mail\{Attachment, Email}; $email = (new Email(from: ['me@example.com'], to: ['you@example.com'])) ->withAttachment('invoice.pdf', '/path/to/invoice.pdf'); // from disk (eagerly read) // Raw in-memory bytes: build the Attachment and pass it in the constructor. $email2 = new Email( from: ['me@example.com'], to: ['you@example.com'], attachments: [Attachment::fromContent($csvBytes, 'report.csv', 'text/csv')], );
Note:
--attach/withAttachment()read arbitrary local paths. The caller is responsible for validating that passed paths are trusted. No path allow-list is enforced by design.
TLS & security (SMTP)
| Port | Mode | What happens |
|---|---|---|
| 465 | Implicit TLS (auto-detected on 465; CANDY_MAIL_SMTP_IMPLICIT_TLS or withImplicitTls() override either way) |
Socket is TLS-wrapped at connect; STARTTLS never sent. |
| 587 | STARTTLS (default) | Plaintext connect, then STARTTLS; required — if the server does not advertise it or the upgrade fails, the send throws instead of downgrading. |
| 25 | STARTTLS upgraded opportunistically, enforced by default | Same default policy applies: a server that refuses STARTTLS fails the send as long as requireTls is on. |
- Fail-closed credentials.
AUTH LOGINnever runs on an unencrypted channel — regardless ofrequireTls. There is noallowInsecureAuthescape hatch by design. - Half-set credentials are refused at construction. Both
usernameandpasswordmeans AUTH; both empty means the legal anonymous posture. Exactly one set throws immediately, so a mail can never depart unauthenticated behind a half-configured credential that would have silently skippedAUTH LOGIN. - AUTH mechanisms. The EHLO AUTH advertisement is parsed as a list
(RFC 4954 — both
AUTH <sp>andAUTH=shapes). SASL PLAIN is preferred and travels as a single command once the channel is encrypted; the LOGIN three-step stays the fallback for LOGIN-only relays. A server advertising only mechanisms this client does not speak (CRAM-MD5, OAUTHBEARER) gets the named refusal — never a blind command guess. - Opt out (trusted networks only).
->withRequireTls(false)restores the historical opportunistic behaviour for the STARTTLS upgrade itself; it does not re-open the credential floor above. - Self-signed / private CAs. Peer verification is always on (never blanket-disable
verify_peer). Point the handshake at your bundle with->withCaFile('/path/ca.pem'); it feeds both the implicit-TLS stream context and the STARTTLS upgrade. - Missing
ext-opensslis a named refusal. Without the extension an encrypted connection used to die as an opaque stream error (or, worse, after the relay had seenSTARTTLS). The transport now refuses by name before dialling SMTPS and before sendingSTARTTLS— the same posture as Resend'sext-curlrefusal. - Message integrity. Attachment filenames and MIME types pass the same CR/LF gate as subjects and addresses; MIME part parameters are RFC 2045-quoted.
- Secret masking.
__debugInfo()masks the SMTP password and the Resend API key. - Credential export is refused at two distinct hooks, and neither is a redaction.
serialize()throws (__serializerefuses), and avar_export()file cannot be re-imported (__set_staterefuses) — butvar_export()does not consult__serialize(), so the generated text still carries the secret as a plain string. The export path is the one to keep shut; never cast a credential-holding transport with(array), and never dump it through reflection. Construct a credential-holding transport where it is used. - Attachment ceilings. 25 MiB (
Attachment::MAX_BYTES) per attachment, regular files only — character devices like/dev/zeroare refused before any read. - Wire format discipline. Header lines fold at 998 octets using ≤75-char RFC 2047
encoded-words; non-ASCII filenames ride RFC 2231
filename*; 8-bit bodies downgrade to quoted-printable when the server lacks 8BITMIME (RFC 6152); documents end with a CRLF-terminated close-delimiter (RFC 2046 §5.1); servers answering EHLO with a 5xx fall back to HELO (RFC 5321 §4.1.4) — 4xx refusals still abort. - Senders are never invented. The CLI refuses to run without
--fromorCANDY_MAIL_FROM; an empty Resend sender list throws instead of fabricatingunknown@localhost.
Egress and network topology
- TLS-inspecting egress. A corporate egress that terminates and re-signs TLS
presents a leaf your OS trust store does not anchor, so verification fails —
by design. Feed the interception CA through
--ca-fileorCANDY_MAIL_SMTP_CA_FILE; there is no blanketverify_peeroff switch, the verification options stay pinned ON at both TLS attach points. - IP-literal relays. Verification pins
peer_nameto the configured host, so dialling a relay by IP requires that address in the server's certificate SAN set (IP SANs are uncommon in commercial certs). Point at the relay's hostname instead, and route name resolution wherever you need to. - No base-URL override for SMTP today.
host/portare the entire dial surface. The Resend transport's endpoint seam is test-only; it shows where a future first-class override would attach, and promises nothing.
CLI
# The examples below invoke the bare `candy-mail` (a `vendor/bin/candy-mail` from # your project install, the composer-global bin, or the phar renamed onto your # PATH); in a monorepo checkout run them as `php candy-mail/bin/candy-mail`. candy-mail --from "me@example.com" --to "you@example.com" --subject "Hello" # Body read from STDIN. Both --flag value and --flag=value work. candy-mail --from "me@example.com" --to you@example.com --render < message.txt # Offline preview: prints the composed MIME message (with a declared-boundary, # RFC 2046-valid structure) and sends nothing — no transport env required.
Four parsing rules, one each:
--versionprints the package version.--help(or-h) prints the usage.--to,--cc,--bccand--attachare repeatable; each occurrence accumulates.- A bare
--ends option parsing; later addresses are positional recipients. Short aliases-f(--from),-t(--to),-s(--subject) and-a(--attach) are accepted as-f value; the inline=form is long-option only (so-f=xis refused, use--from=xor-f x). Positional recipients fill--toonly when--tois absent — if you also pass--to, the positional addresses after--are silently dropped (mixing is not additive). Unknown options are rejected loudly, with a did-you-mean hint when a known flag is a near miss.
Value switches: --from/--subject/--body/--reply-to/--html/--helo/--ca-file/--timeout
(the last three override their CANDY_MAIL_SMTP_* env rows, and the flags win over the
environment; --timeout is range-checked at parse time on every path). Transport
selection is a ladder, not a merge: a non-blank RESEND_API_KEY wins outright, then
CANDY_MAIL_MAILGUN_API_KEY (with CANDY_MAIL_MAILGUN_DOMAIN, optional
CANDY_MAIL_MAILGUN_REGION=us|eu), then SMTP; the
Resend and Mailgun legs read none of --timeout/--helo/--ca-file (each one supplied prints a
stderr note naming it), and the API transport keeps its own fixed 10 s connect /
30 s transfer budget — the CLI's timeout knob is SMTP-only. When both transports are
configured the ladder can silently spend the WRONG domain's identity (SPF/DKIM
alignment rides whichever transport answers), so --transport=smtp|resend|mailgun forces the
choice: smtp ignores a present key outright, resend/mailgun refuse without their credentials. The
zero-flag recipe for a one-off is env -u RESEND_API_KEY candy-mail …. A value that begins with a
dash needs the inline form, shell-quoted so the rest of the value stays one argv token
(--subject="-50% off") — a switch is never stolen as another switch's value. The CLI
requires a --to recipient: cc/bcc alone ends in a loud refusal (the library itself
permits cc/bcc-only sends over SMTP; the Resend API needs at least one to). Address
flags and positionals accept a Name <a@b> display name — the address inside the
angle brackets must pass the grammar (mis-shapes are refused, not repaired); display
names may be non-ASCII (RFC 2047-encoded), the address itself must stay ASCII
(SMTPUTF8 is not supported).
Embedding behind another bin? require the bootstrap and call
exit(\SugarCraft\Mail\main($argv)); to keep exit codes honest.
Environment variables:
export RESEND_API_KEY=re_xxxxx # Resend API key — sign up at resend.com and # create one (enables the Resend transport) export CANDY_MAIL_MAILGUN_API_KEY=key-xxxxx # Mailgun API key (used when no RESEND_API_KEY) export CANDY_MAIL_MAILGUN_DOMAIN=mg.example.com # Mailgun sending domain (required with the key) export CANDY_MAIL_MAILGUN_REGION=us # us (default) or eu export CANDY_MAIL_SMTP_HOST=smtp.gmail.com # SMTP host (Resend key wins if both set — # force SMTP with --transport=smtp) export CANDY_MAIL_SMTP_PORT=587 # SMTP port (default: 587) export CANDY_MAIL_SMTP_USERNAME=user # SMTP username export CANDY_MAIL_SMTP_PASSWORD=pass # SMTP password (app password for Gmail etc.) export CANDY_MAIL_SMTP_REQUIRE_TLS=1 # default ON; ON words 1/true/yes/on, OFF words 0/false/no/off — # anything else is REFUSED, never guessed (a mistyped security # switch must not silently downgrade) export CANDY_MAIL_SMTP_IMPLICIT_TLS=0 # leave unset for port-465 auto-detect; set 1 to force on, 0 to force off (same word vocabulary) export CANDY_MAIL_SMTP_HELO=mail.example.com # EHLO/HELO identity (letters, digits, dots, hyphens only) export CANDY_MAIL_SMTP_CA_FILE=/path/ca.pem # custom CA bundle for TLS verification export CANDY_MAIL_SMTP_TIMEOUT=30 # connect + per-response seconds budget, 1..3600 (default 30); # range-checked at parse time — ignored (with a note) when Resend wins export CANDY_MAIL_FROM=me@example.com # Sender default — REQUIRED unless --from passed (never fabricated) export CANDY_MAIL_SIGNATURE="Sent with CandyMail" # Appended to the plain-text body (HTML-only mail drops it) # Pre-rename POP_* exports are imported onto CANDY_MAIL_* equivalents whole-prefix # (an already-set CANDY_MAIL_* wins); the 11 names this program reads also emit a # one-time deprecation warning — off-roster POP_* vars map to names nothing consumes, # staying inert and silent. The exception is POP_SMTP_TLS: it predates the # REQUIRE/IMPLICIT split, so its value carries to CANDY_MAIL_SMTP_REQUIRE_TLS # (nearest meaning — that knob is what the old switch enforced), and the warning # names that successor; the new name still wins if both are set.
Secret hygiene: these are credential-shaped values. For real secrets, inject from your secrets store or a
chmod 600EnvironmentFile rather than the inlineVAR=value cmdform — it persists in shell history and is readable in the child's process environment (and anexportline pasted into a dotfile persists too).
Running unattended
Cron jobs, systemd units, and containers have no terminal, and STDIN there is
an environment detail, not an intent: a closed non-tty stream (redirected from
/dev/null, or the default of a hardened unit) reads as an empty body. Since
a message with no body, no HTML part, and no attachment composes to zero MIME
parts, the CLI now refuses that shape loudly (exit 1) instead of mailing
or previewing a hollow envelope. Unattended senders therefore always pass
--body (or --html) explicitly, or pipe real content:
# crontab — body on the command line, credentials from an EnvironmentFile- # style export block, never from an interactive terminal assumption: */15 * * * * candy-mail --from reports@example.com --to oncall@example.com \ --subject "Nightly summary" --body "$(tail -n 20 /var/log/nightly.log)" # systemd unit — feed the body through a pipe so the service reads content, # not a tty; source the credential env from a root-owned 600 file. ExecStart=/bin/sh -c '. /etc/candy-mail.env; printf "%%s" "$BODY_TEXT" | \ /usr/local/bin/candy-mail --from bot@example.com --to team@example.com' # container — -i keeps STDIN open so the pipe actually delivers: docker run --rm -i candy-mail --from me@example.com --to you@example.com < body.txt
STDIN accumulation is capped at 4 MiB per run: a runaway producer
(yes | candy-mail) is refused at the cap before any connection is paid, the
same loud-over-truncating posture as Attachment::MAX_BYTES. Credentials come
from the environment in every unattended shape — automation passes no flags, so
the CANDY_MAIL_SMTP_* variables above are read identically under cron, systemd,
and containers and carry every decision.
The stdout contract, per mode
- Send — one line on success, translated:
✓ Email sent via {transport}.Everything that is not that line (refusals, warnings, deprecation notices, the--render8-bit note) goes to stderr; stdout stays machine-greppable. --render— stdout carries the composed MIME document and nothing else.--help/--version— stdout carries the usage text / the version line.- Parsing output in a different locale? The banners translate through the catalog
shelf; pin English with
LC_ALL=C(orLANG=C) in the wrapper's environment and the strings above are stable.
A --quiet flag and a --json envelope would formalise this further; they stay
a separate CONV/CLI proposal (recorded with this section, not promised by it).
Exit codes
| Code | Meaning |
|---|---|
| 0 | Success — includes --help, --version, and --render |
| 1 | Every refusal: bad input, missing/invalid config, TLS or relay failure |
(The build script tools/build-phar.php runs on a different scale — it exits
2 on a failed preflight; it is a build tool, not the shipped CLI.)
Differentiated refusal codes per failure class remain a separate open
CONV/CLI decision; until then, script authors branch on 0 vs 1 only.
What a success actually means
A send that returns 0 (and prints ✓ Email sent via …) means the message was
accepted by the transport for delivery, not that it reached an inbox: on
SMTP the 250 after the DATA terminator is the relay queueing the mail, on
Resend the API reply is an accept, and in both cases bounces and rejections
arrive later, out-of-band, at the envelope sender. quit() deliberately
swallows farewell errors — by then the message is already queued, and a
protocol blip during the goodbye must not latch a false failure over a
successful accept. For CI, --render is the pre-flight wire check: it prints
the exact MIME document without dialling anything. (The success banner's
literal value stays "Email sent" in all 17 catalogs — renaming it churns
every translation for a wording win the README now carries honestly; decision
recorded here per CM-18.)
Error messages follow the standard LC_ALL/LC_MESSAGES/LANG environment (17
locales ship); the usage/help text is English by design. Examples under examples/
are offline-safe: without real credentials they print the composed message instead of
dialling any API.
Internationalisation
All user-visible errors route through the SugarCraft\Mail\Lang facade (sugar-core's
shared T registry, namespace mail, catalog in lang/). English is the default;
a host application opts in process-wide:
\SugarCraft\Core\I18n\T::setLocale(\SugarCraft\Core\I18n\T::detect()); // LC_ALL → LC_MESSAGES → LANG → 'en'
The CLI performs this at startup; library embedders decide. Missing keys in an active locale fall back to English; the en catalog is the last stop before the raw key.
17 catalogs ship (ar through zh-tw, Traditional Chinese included alongside zh-cn).
Architecture
Email— immutable email message value objectAttachment— immutable file attachment (path or inline content)Transport— interface for sending implementations; sends are connection-per-send (dial and quit inside onesend()), with no upstream KeepAlive/Close counterpart — batch senders that want session reuse pool at their own layer, above one connection perTransportResendTransport— sends via Resend REST API (HTTPS)MailgunTransport— sends via the Mailgun REST API (HTTPS, multipart, US/EU regions)Tui\ComposeModel— the interactive compose form behindcandy-mail tuiSmtpTransport— sends via direct SMTP (TCP/TLS)Mailer— high-level API wrapping a TransportMissingTransportConfig— the typedRuntimeExceptionfor "no transport is configured": the CLI's--renderpath catches exactly this type to keep the offline preview reachable for a genuinely unconfigured send, while every other transport-build fault (a typo in a security switch, a broken relay setting) stays a loud error instead of being text-matched into the preview. Library callers catch it by type to separate unconfigured from misconfigured — the class exists precisely so no comparison against a translated message can drift.Lang— per-library translation facade over the shared sugar-core registry
Shared foundations
candy-mail uses sugar-async
for cancellation on every send path (Mailer::send, SmtpTransport::send, and
ResendTransport::send all apply the same check) via CancellationToken: an entry
pre-check only
(isCancelled() before the conversation starts). Blocking I/O never yields to the event
loop mid-send, so onCancel() callbacks cannot fire during a running send — true
mid-flight cancellation would require an async transport (documented in
CALIBER_LEARNINGS.md).
Tests
cd candy-mail && composer install && vendor/bin/phpunit -c phpunit.xml
411 tests, 2,021 assertions (PHP 8.3, PHPUnit 10.5). The suite includes fork-based loopback fake-server tests for the SMTP conversation; no external network is ever dialled.
Deprecated accessors
Per the house bare-accessor convention (AGENTS.md: "Bare accessors (no get)),
Attachment::getContent() was renamed to its bare twin content(). The rename is safe
because the method slot was unclaimed: no withContent setter exists, the public readonly
$content property names the raw backing field and not a callable, and PHP keeps property
and method namespaces distinct. The legacy spelling stays as a byte-identical one-line BC
forwarder marked @deprecated with REMOVED-IN: 2.0.0; it will be removed in
candy-mail v2.0.0.
| Namespace | Class | Deprecated | Use instead |
|---|---|---|---|
Mail |
Attachment |
getContent() |
content() |
Note the distinction the rename preserves: the readonly property $content is the raw
nullable backing field, while content() resolves the bytes (including the
defense-in-depth path re-read). tests/AccessorDeprecationTest.php pins five legs:
- BC identity on live objects from both factories
- the property/method distinction
- the forwarder shape
- a discovery-first
src/census, with an inverse leg that reddens any unmarked publicget*() - README table agreement
Internal call sites in src/ (SmtpTransport, ResendTransport) were switched to the bare form in the same commit.
License
MIT
Credits & inspiration
Originally inspired by the Go Charm ecosystem — specifically
its pop mail tool, which this package ports; SugarCraft
is developed as a native PHP project.
