CandyMail
Email sending — SMTP, Resend and Mailgun HTTP API transports, attachments
CandyMail builds and sends email. An immutable Email value carries the addresses, subject, plain and HTML bodies, attachments and headers. A Transport delivers it over SMTP, the Resend HTTP API or the Mailgun HTTP API, and Mailer checks the envelope before the transport dials. The package also ships a command-line sender and a compose TUI. It mirrors the send path of charmbracelet/pop, which sends through go-mail; the message model follows go-mail's NewEmail() shape, and the rest is native PHP.
Install
composer require sugarcraft/candy-mail
Requires PHP 8.3 or newer. The Resend and Mailgun API transports need the curl extension, and STARTTLS or implicit-TLS SMTP needs openssl. Plain SMTP works without either. The composer install puts the candy-mail binary in vendor/bin/. A standalone phar is also published; the README's Install section covers both.
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 to dev with prefer-stable set to true in your consuming manifest. The pin covers the whole sibling closure, so allowing dev for candy-mail alone is not enough. The global install takes the same form: composer global require sugarcraft/candy-mail:@dev.
Quickstart
use SugarCraft\Mail\{Email, ResendTransport, SmtpTransport};
// Immutable: every with*() returns a new Email. The constructor takes named
// arguments too, so a partial build stays readable.
$email = Email::new('noreply@example.com', 'user@example.com', 'Deployment complete', 'Your app was deployed successfully.')
->withHtmlBody('<p>Your app was deployed <strong>successfully</strong>.</p>')
->withCc('ops@example.com')
->withAttachment('build.zip', '/tmp/build.zip'); // display name, then the file on disk
// Credentials come from the environment, never from committed source.
$transport = new SmtpTransport(
host: 'smtp.example.com',
port: 587,
username: (string) getenv('CANDY_MAIL_SMTP_USERNAME'),
password: (string) getenv('CANDY_MAIL_SMTP_PASSWORD'),
);
$transport->send($email);
// Or over the Resend HTTP API, with the key taken from RESEND_API_KEY
(new ResendTransport())->send($email);
The SMTP transport requires TLS by default, so credentials never travel over a plaintext channel. The candy-mail CLI reads the same CANDY_MAIL_SMTP_* names listed under Configuration.
To see the message without sending anything, build the MIME text offline. No transport or network is involved:
$mime = (new SmtpTransport('smtp.example.com'))->buildMimeMessage($email);
echo $mime; // headers, the multipart/alternative body and the base64 attachment part
Concepts
An Email is a value. It holds the sender and recipient lists, the subject, the plain and HTML bodies, the attachments and any extra headers. Each with*() returns a new instance, and Email::new() is the one-pair shortcut. The constructor refuses, rather than cleans, any header value that holds a carriage return, line feed or other control byte, so a header cannot forge a second header.
A Transport is the delivery contract. It has a send(Email, ?CancellationToken) method and a name() for logging. Three implementations ship: SmtpTransport, ResendTransport and MailgunTransport. Writing your own means implementing the interface.
Mailer wraps one transport. Before it dials, it refuses an email with no recipient in to, cc or bcc, and an email with no sender. The candy-mail CLI reports a missing transport configuration as MissingTransportConfig, a RuntimeException, and its offline --render fallback catches exactly that type, so a broken configuration stays a loud error. The library does not raise that type: a ResendTransport built with a blank key throws InvalidArgumentException when it sends.
Attachments are read when they are built, not when the message is sent. Attachment::fromPath() reads the file eagerly, so an unreadable path throws at withAttachment() time. A single attachment is capped at Attachment::MAX_BYTES (25 MiB), and the whole message at Email::MAX_TOTAL_BYTES (64 MiB).
Tasks
Send over SMTP with TLS and an explicit CA bundle
$smtp = (new SmtpTransport(
host: 'smtp.example.com',
port: 587,
username: (string) getenv('CANDY_MAIL_SMTP_USERNAME'),
password: (string) getenv('CANDY_MAIL_SMTP_PASSWORD'),
))->withCaFile('/etc/ssl/certs/corp-ca.pem');
$smtp->send($email);
STARTTLS is the default on port 587, and implicit TLS is selected automatically on port 465. withRequireTls(false) allows a plaintext fallback. Use it only when you accept that the credentials may cross the network unencrypted.
Send through the Resend or Mailgun API
use SugarCraft\Mail\{MailgunTransport, Mailer, ResendTransport};
$resend = new ResendTransport(); // reads RESEND_API_KEY when the argument is empty
$mailgun = new MailgunTransport(domain: 'mg.example.com', region: MailgunTransport::REGION_EU);
(new Mailer($resend))->send($email);
A transport constructed with an empty key falls back to the environment. A key that contains whitespace or a control character is refused at construction, before any request is made. One gap remains: a single trailing line feed passes that check, so trim a key read from a file before you pass it. The API transports never send without a key.
Embed an inline image and reference it by content ID
$html = $email
->withInlineAttachment('/srv/assets/logo.png', 'logo') // the cid is the handle
->withHtmlBody('<img src="cid:logo" alt="logo"> <p>Deployed.</p>');
$smtp->send($html); // $smtp from the first recipe; ResendTransport refuses inline parts
The inline part is sent with its content ID, and the HTML body refers to it as cid:logo. Attachment::inline() builds the same value object if you need it outside an Email.
Inline CID needs the SMTP or the Mailgun transport. ResendTransport refuses an inline attachment with an error keyed resend.cid_unsupported, because the Resend API payload has no Content-ID field, so a Resend key never sends this recipe. Send the message with SmtpTransport or MailgunTransport.
Attach bytes that never touch the disk
use SugarCraft\Mail\{Attachment, Email};
$report = Attachment::fromContent($csv, 'report.csv', 'text/csv');
$email = new Email(
from: ['ops@example.com'],
to: ['you@example.com'],
subject: 'Weekly report',
attachments: [$report],
);
withAttachment() is for files on disk and refuses a missing path. Attachment::fromContent() takes the bytes and a MIME type, and defaults to application/octet-stream when none is given. The constructor's attachments argument accepts the value objects directly.
Send from the command line
printf 'Build 42 is live.\n' | candy-mail --from ops@example.com --to you@example.com --subject "Deploy"
candy-mail --from ops@example.com --to you@example.com --attach build.zip --render < message.txt # offline preview, nothing sent
The body is read from stdin. --to, --cc, --bcc and --attach repeat. --render prints the composed MIME message and sends nothing, so it needs no transport configured.
API reference
The public classes live in SugarCraft\Mail\. The message and transports are plain value and service objects. The compose screen lives in SugarCraft\Mail\Tui\.
| Class | Method | Description |
|---|---|---|
new(from, to, ?subject, ?body) | Create an email with one sender and one recipient | |
withFrom(), withTo(...$to), withCc(...$cc), withBcc(...$bcc), withReplyTo(), withSubject() | Immutable header builders | |
withBody(), withHtmlBody(), withSignature(), withHeader(name, value) | Plain and HTML bodies, the signature, and extra headers | |
withAttachment(filename, path), withInlineAttachment(path, cid, ?filename) | Attach a file, or embed one for a cid: reference | |
bodyWithSignature(), allRecipients() | The body with the signature applied, and the combined to, cc and bcc list | |
| Attachment | fromPath(path, ?filename), inline(path, cid, ?filename) | Build an attachment from a file on disk, plain or inline |
| Attachment | fromContent(content, filename, mimeType), content(), withCid(cid) | Build one from memory, read the bytes, or set the content ID |
| Transport | send(Email, ?CancellationToken), name() | The delivery interface. Implement it to add a transport. |
| Mailer | __construct(Transport), send(Email, ?CancellationToken), transportName() | Transport-agnostic sender that validates the envelope before dialing |
| SmtpTransport | __construct(host, port = 587, username = '', password = '', timeout = 30, heloHost = '', ?assumeOpenssl) | SMTP delivery. The constructor refuses an unsafe host, port, timeout or EHLO name. |
| SmtpTransport | withRequireTls(bool), withImplicitTls(bool), withCaFile(path) | TLS policy and a custom CA trust anchor |
| SmtpTransport | buildMimeMessage(Email, allow8Bit = true) | Render the full MIME message without sending |
| ResendTransport | __construct(apiKey = '', apiUrl = ''), send(), name() | Resend API delivery. Falls back to RESEND_API_KEY; API_URL is the default endpoint. |
| MailgunTransport | __construct(apiKey = '', domain = '', region = REGION_US, baseUrl = ''), endpoint(), send() | Mailgun API delivery, with REGION_US and REGION_EU |
| MissingTransportConfig | extends RuntimeException | The typed refusal for a missing transport configuration. Catch it by type, never by message text. |
| ComposeModel | new(Closure $send, Closure $render, array $prefill = []), init(), update(Msg), view(), email(), focused() | The compose screen as a TEA Model. email() builds the Email from the fields. |
| TextBuffer | new(value = '', multiline = false), insert(), backspace(), left(), right(), home(), end(), layout() | The editable text field used by each compose field, with immutable edits |
| SendResultMsg | __construct(?string $error, string $transport = '') | The message that reports a finished send back to the compose screen, with the error text when the send failed |
Only methods declared in candy-mail/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.
SugarCraft\Mail
Attachment final class
Represents a file attachment on an email.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
static fromPath(string $path, ?string $filename = null): self | Create from a file path. |
static fromContent(string $content, string $filename, string $mimeType = 'application/octet-stream'): self | Create from raw content bytes. |
static inline(string $path, string $cid, ?string $filename = null): self | Create an inline (embedded) image attachment. |
content(): string | Get the raw content bytes. |
getContent(): string | BC forwarder for the pre-rename accessor name. |
withCid(string $cid): self | Create a copy with an updated cid (for inline embedding). |
__debugInfo(): array | Debug-output shape: var_dump()/print_r() of an Attachment used to spill up to MAX_BYTES raw payload bytes onto the terminal. Identity stays inspectable; the bytes do not. |
Email final class
Immutable email message value object.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
__construct(array $from, array $to, ?string $subject = null, ?string $body = null, array $cc = [], array $bcc = [], ?string $htmlBody = null, ?string $replyTo = null, array $attachments = [], ?string $signature = null, array $headers = []) | |
static new(string $from, string $to, ?string $subject = null, ?string $body = null): self | Create from a single from/to pair with optional subject/body. |
withFrom(string $from): self | |
withTo(string ...$to): self | |
withSubject(string $subject): self | |
withBody(string $body): self | |
withHtmlBody(string $htmlBody): self | |
withCc(string ...$cc): self | |
withBcc(string ...$bcc): self | |
withReplyTo(string $replyTo): self | |
withAttachment(string $filename, ?string $path = null): self | Add an attachment from a file path. |
withInlineAttachment(string $path, string $cid, ?string $filename = null): self | |
withSignature(string $signature): self | |
withHeader(string $name, string $value): self | Escape hatch for arbitrary headers (RFC 5322 §3.6 optional-field set): List-Unsubscribe, In-Reply-To, X-… anything the fixed message fields do not already own. Names are validated against the RFC 9110 token grammar, values ride the SAME CRLF + C0 refusal class the subject gate uses, and the pair accumulates in insertion order (a later same-name header overwrites the value but keeps its original position; the comparison is case-insensitive per RFC 5321 §2.3.1 — X- prefixed names are always open, the fixed set below is what this class and the transports compose themselves and cannot be overridden from here): From, To, Cc, Bcc (never travels as a header at all), Subject, Reply-To, Date, Message-ID, MIME-Version, Content-Type, Content-Transfer-Encoding. |
bodyWithSignature(): ?string | Body text with signature appended (if set). |
allRecipients(): array | All recipients combined (to + cc + bcc) for SMTP "RCPT TO" routing. |
Lang final class
Per-library translation facade for candy-mail.
Mailer final class
High-level email sender wrapping a Transport.
| Method | Summary |
|---|---|
__construct(Transport $transport) | |
send(Email $email, ?CancellationToken $token = null): void | Send an email via the configured transport. |
transportName(): string | Get the transport name for logging. |
MailgunTransport final class
Sends email via the Mailgun REST API (POST /v3/{domain}/messages).
| Method | Summary |
|---|---|
__construct(#[\SensitiveParameter] string $apiKey = '', string $domain = '', string $region = self::REGION_US, string $baseUrl = '') | |
endpoint(): string | The full messages endpoint this transport posts to. |
send(Email $email, ?CancellationToken $token = null): void | |
name(): string | |
__debugInfo(): array | Mask the key in var_dump()/print_r(); parity with the other transports. |
__serialize(): array | |
static __set_state(array $properties): static |
MissingTransportConfig final class
Thrown when no transport is configured (no API key, no SMTP host).
ResendTransport final class
Sends email via the Resend REST API.
| Method | Summary |
|---|---|
__construct(#[\SensitiveParameter] string $apiKey = '', string $apiUrl = '') | |
send(Email $email, ?CancellationToken $token = null): void | |
name(): string | |
__debugInfo(): array | Mask the API key so var_dump()/print_r() of live object state shows **** (parity with SmtpTransport's password mask). |
__serialize(): array | Refuse serialisation outright — the API key would ride the wire of any cache/session that stored this transport. Build it where used. |
static __set_state(array $properties): static | Refuse var_export() resurrection. |
SmtpTransport final class
Sends email via direct SMTP (TCP/TLS).
| Method | Summary |
|---|---|
static isValidHost(string $host): bool | Construction-time input floors — one home for the bounds. |
static isValidPort(int $port): bool | |
static isValidTimeout(int $timeout): bool | |
__construct(string $host, int $port = 587, string $username = '', #[\SensitiveParameter] string $password = '', int $timeout = 30, string $heloHost = '', ?bool $assumeOpenssl = null) | |
withRequireTls(bool $require = true): self | Control whether the send fails when the channel cannot be encrypted. |
withImplicitTls(bool $implicit = true): self | Return a copy that connects with implicit TLS (SMTPS) regardless of port. |
withCaFile(string $caFile): self | Return a copy that verifies the server certificate against a custom CA bundle instead of the system trust store (e.g. a private CA). |
__debugInfo(): array | Mask secrets so the SMTP password never leaks through var_dump() or print_r() reflection of live object state. |
__serialize(): array | Refuse serialisation outright: a serialised transport is a plaintext credential on disk or in a cache, and unserialize() of it resurrected a live credentialed sender. Transports are cheap to build where they are used; there is nothing worth persisting in one. |
static __set_state(array $properties): static | Refuse var_export() resurrection — see the __debugInfo contract above for what this does and does not seal. |
send(Email $email, ?CancellationToken $token = null): void | Send an email with optional cancellation support. |
name(): string | |
buildMimeMessage(Email $email, bool $allow8Bit = true): string | Render the full RFC 2046 MIME message for an email (headers + body). |
Transport interface
Pluggable transport for sending Email messages.
| Method | Summary |
|---|---|
send(Email $email, ?CancellationToken $token = null): void | Send the email. |
name(): string | Name of this transport for logging/debugging. |
SugarCraft\Mail\Tui
ComposeModel final class
Interactive compose form: candy-mail tui.
| Method | Summary |
|---|---|
static new(\Closure $send, \Closure $render, array $prefill = []): self | |
init(): ?\Closure | |
subscriptions(): ?\SugarCraft\Core\Subscriptions | |
focused(): string | Name of the focused field. |
email(): Email | Compose the message from the form; the same gate a send goes through. |
update(Msg $msg): array | Every arm returns a ComposeModel (self / with() / edit() / move()), never some other Model — the shape states that, so consumers (the Program host and the tests) keep the concrete type across the boundary. |
view(): string |
SendResultMsg final class
Outcome of the background send the compose form kicked off.
| Method | Summary |
|---|---|
__construct(public readonly ?string $error, public readonly string $transport = '') |
TextBuffer final class
Immutable text-editing buffer behind one compose field.
| Method | Summary |
|---|---|
static new(string $value = '', bool $multiline = false): self | |
value(): string | |
length(): int | |
isEmpty(): bool | |
insert(string $text): self | |
backspace(): self | |
delete(): self | |
left(): self | |
right(): self | |
home(): self | Start of the current line (the whole buffer when single-line). |
end(): self | |
up(): self | Move one line up keeping the column; stays put on the first line. |
down(): self | Move one line down keeping the column; stays put on the last line. |
onFirstLine(): bool | True when the cursor sits on the first line. |
onLastLine(): bool | True when the cursor sits on the last line. |
clear(): self | |
layout(): array | Split into lines with the cursor's (line, column) position. |
Configuration
The library reads no configuration files. Transports take their settings as constructor arguments, and the CLI maps environment variables onto them. Flags beat the environment, and the environment beats the defaults.
| Variable | Type | Default | Effect |
|---|---|---|---|
RESEND_API_KEY | string | unset | Enables the Resend transport. It wins outright when set. |
CANDY_MAIL_MAILGUN_API_KEY | string | unset | Enables the Mailgun transport when no Resend key is set. The library reads MAILGUN_API_KEY when constructed without a key. |
CANDY_MAIL_MAILGUN_DOMAIN | string | unset | Sending domain. Required with the Mailgun key. |
CANDY_MAIL_MAILGUN_REGION | us or eu | us | Mailgun API region |
CANDY_MAIL_SMTP_HOST | host name | unset | SMTP server. Used when no API key is set. |
CANDY_MAIL_SMTP_PORT | int | 587 | SMTP port. Port 465 selects implicit TLS. |
CANDY_MAIL_SMTP_USERNAME, CANDY_MAIL_SMTP_PASSWORD | string | empty | SMTP credentials. Use an app password for Gmail-style accounts. |
CANDY_MAIL_SMTP_REQUIRE_TLS | boolean word | 1 | Requires TLS. 1, true, yes, on and their off counterparts are accepted. Any other value is refused, never guessed. |
CANDY_MAIL_SMTP_IMPLICIT_TLS | boolean word | auto | Unset auto-detects from the port. Set 1 or 0 to force it. |
CANDY_MAIL_SMTP_HELO | hostname | empty | EHLO identity. Letters, digits, dots and hyphens only. |
CANDY_MAIL_SMTP_CA_FILE | path | system store | Custom CA bundle for TLS verification |
CANDY_MAIL_SMTP_TIMEOUT | int, 1 to 3600 | 30 | Connect and per-response timeout in seconds |
CANDY_MAIL_FROM | address | unset | Default sender. The CLI requires it unless --from is given, and never invents one. |
CANDY_MAIL_SIGNATURE | string | unset | Appended to the plain-text body. HTML-only mail drops it. |
The transport is chosen by a ladder, not a merge. A non-blank Resend key wins outright, then the Mailgun key, then SMTP. When more than one transport is configured, --transport=smtp, --transport=resend or --transport=mailgun forces the choice, because the sending domain sets SPF and DKIM alignment.
Keys in the compose TUI
candy-mail tui opens the compose screen, a ComposeModel that runs on the sugar-core Model loop. A bare invocation on a terminal opens it too. Fields are from, to, cc, bcc, replyto, subject, body, html and attach.
| Key | Action |
|---|---|
| Tab, Shift+Tab | Move to the next or previous field |
| Enter | In the body or the HTML field, insert a newline. Elsewhere, move to the next field. |
| Up, Down | In the body or the HTML field, move between lines. Elsewhere, and on the first or last line of those fields, move to the previous or next field. |
| Left, Right, Home, End | Move the cursor within the field |
| Backspace, Delete, Ctrl+U | Delete before the cursor, after it, or clear the field |
| Ctrl+P | Toggle the preview. Esc in the preview returns to editing. |
| Ctrl+S | Send the composed email through the configured transport |
| Esc on the edit screen, Ctrl+C, Ctrl+Q | Quit. With unsaved edits the first press asks for confirmation. |
Examples
The examples/ directory holds six runnable programs. Five of them print an offline MIME preview unless they find the credentials they need, so none of them sends mail by accident. showcase.php prints a field summary instead of a MIME message.
examples/showcase.phpbuildsEmailvalues and prints their fields. It needs no SMTP or Resend access.examples/basic.phpsends through the Resend API whenRESEND_API_KEYis set. Without a key it prints the composed MIME message.examples/html-email.phpadds CC and BCC recipients, an HTML body and an inline CID image, then prints an offline MIME preview. WithRESEND_API_KEYset it tries the Resend API instead, which refuses the inline image with the error keyedresend.cid_unsupported, so the run exits 1. Inline CID needs SMTP or Mailgun.examples/attachments.phpattaches two files from disk withwithAttachment()and prints the offline MIME preview.examples/smtp.phpsends over SMTP whenCANDY_MAIL_SMTP_HOSTis set. Without it, the example prints the offline preview.examples/pipeline.phpreads the message body from stdin, takes an optional recipient and subject from the command line, and sends through Resend whenRESEND_API_KEYis set. Otherwise it prints the preview. It needs a piped body: with stdin empty or closed it prints a usage line and exits 1.
php examples/showcase.php
php examples/html-email.php # offline MIME preview; RESEND_API_KEY routes it to Resend, which refuses the inline image
Testing
The suite lives in tests/ and runs under PHPUnit 10. Run it from the package root, with stdin redirected so a stray read cannot hang the run:
vendor/bin/phpunit < /dev/null
The SMTP tests cover the MIME structure, and TlsChannelTest forks a minimal TLS-terminating fake SMTP server to exercise the TLS channel. The Resend and Mailgun tests check the request payload. The compose TUI has its own tests under tests/Tui/.
Troubleshooting
Building an attachment throws a RuntimeException
The path does not exist or is not readable, and withAttachment() reads the file when it is called. Check the path before building the email, or pass the bytes with Attachment::fromContent() instead.
Mailer throws InvalidArgumentException before sending
The email has no recipient in to, cc or bcc, or it has no sender. Add a recipient with withTo() and a sender with withFrom(). The transports never see an envelope that Mailer refuses.
An API key is refused at construction
The key contains a carriage return, whitespace inside the value, or another control character. A trailing carriage return, as left by a Windows-style line ending in RESEND_API_KEY, is a common cause. The check exists because the key is written verbatim into an Authorization header, so a carriage return would forge a second header. A single trailing line feed is the one exception: it passes the check, so trim the value in the environment or after reading it from a file.
Resend refuses a message with only cc or bcc recipients
The Resend API needs at least one to recipient. SMTP accepts a cc or bcc-only send, so the same email can succeed over SMTP and fail over Resend.
The CLI sent through a different provider than expected
A configured Resend key wins over SMTP, and a Mailgun key wins over SMTP when no Resend key is set. Pass --transport=smtp to force SMTP, or --transport=resend and --transport=mailgun to refuse without their credentials.
Upstream mapping
| Upstream (Go) | candy-mail (PHP) |
|---|---|
charmbracelet/pop, the email client whose send path this package follows | bin/candy-mail, ComposeModel, Mailer |
go-mail NewEmail(), the message library pop sends through | Email::new() and the Email value object |
| The SMTP client and its MIME encoding | SmtpTransport, with its own MIME builder. Not a line-by-line port. |
| Resend and Mailgun HTTP APIs | ResendTransport, MailgunTransport. Native additions, not in pop. |
Architecture
Values in, transports out
The message is built as values, validated, and then handed to a transport. Sending is the only network step. A message can be built, inspected and rendered without one, and buildMimeMessage() exposes the exact bytes a send would produce. Attachments are the one I/O at build time, because they read their files when attached.
Validate before dialing
Mailer refuses an envelope with no recipient or no sender, and a canceled token stops a send before it starts. The SMTP transport validates its own host, port, timeout and EHLO name in the constructor, so a bad value fails where the caller still owns it.
The compose screen is a Model
ComposeModel keeps one TextBuffer per field. Each key returns a new model, and the send is a Cmd that reports back through SendResultMsg, so the view never performs I/O.
Changelog and versioning
candy-mail --version prints the package version. Releases follow the sugarcraft tags, and the README's Install section explains the standalone phar.
Related
- sugar-core: the Model, Cmd and Program runtime behind the compose screen, plus the sanitizer used on untrusted output.
Source & demos
Demos.
VHS-recorded GIF of the API showcase, regenerated automatically on every push that touches the source.