All 22 apps

CandyMail

Email sending — SMTP, Resend and Mailgun HTTP API transports, attachments

inspired by charmbracelet/pop emailmailsmtpattachmentresendmailersend

CandyMail code coverage

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\.

ClassMethodDescription
Emailnew(from, to, ?subject, ?body)Create an email with one sender and one recipient
EmailwithFrom(), withTo(...$to), withCc(...$cc), withBcc(...$bcc), withReplyTo(), withSubject()Immutable header builders
EmailwithBody(), withHtmlBody(), withSignature(), withHeader(name, value)Plain and HTML bodies, the signature, and extra headers
EmailwithAttachment(filename, path), withInlineAttachment(path, cid, ?filename)Attach a file, or embed one for a cid: reference
EmailbodyWithSignature(), allRecipients()The body with the signature applied, and the combined to, cc and bcc list
AttachmentfromPath(path, ?filename), inline(path, cid, ?filename)Build an attachment from a file on disk, plain or inline
AttachmentfromContent(content, filename, mimeType), content(), withCid(cid)Build one from memory, read the bytes, or set the content ID
Transportsend(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.
SmtpTransportwithRequireTls(bool), withImplicitTls(bool), withCaFile(path)TLS policy and a custom CA trust anchor
SmtpTransportbuildMimeMessage(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
MissingTransportConfigextends RuntimeExceptionThe typed refusal for a missing transport configuration. Catch it by type, never by message text.
ComposeModelnew(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.
TextBuffernew(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/.

MethodSummary
static fromPath(string $path, ?string $filename = null): selfCreate from a file path.
static fromContent(string $content, string $filename, string $mimeType = 'application/octet-stream'): selfCreate from raw content bytes.
static inline(string $path, string $cid, ?string $filename = null): selfCreate an inline (embedded) image attachment.
content(): stringGet the raw content bytes.
getContent(): stringBC forwarder for the pre-rename accessor name.
withCid(string $cid): selfCreate a copy with an updated cid (for inline embedding).
__debugInfo(): arrayDebug-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/.

MethodSummary
__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): selfCreate 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): selfAdd an attachment from a file path.
withInlineAttachment(string $path, string $cid, ?string $filename = null): self
withSignature(string $signature): self
withHeader(string $name, string $value): selfEscape 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(): ?stringBody text with signature appended (if set).
allRecipients(): arrayAll 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.

MethodSummary
__construct(Transport $transport)
send(Email $email, ?CancellationToken $token = null): voidSend an email via the configured transport.
transportName(): stringGet the transport name for logging.

MailgunTransport final class

Sends email via the Mailgun REST API (POST /v3/{domain}/messages).

MethodSummary
__construct(#[\SensitiveParameter] string $apiKey = '', string $domain = '', string $region = self::REGION_US, string $baseUrl = '')
endpoint(): stringThe full messages endpoint this transport posts to.
send(Email $email, ?CancellationToken $token = null): void
name(): string
__debugInfo(): arrayMask 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.

MethodSummary
__construct(#[\SensitiveParameter] string $apiKey = '', string $apiUrl = '')
send(Email $email, ?CancellationToken $token = null): void
name(): string
__debugInfo(): arrayMask the API key so var_dump()/print_r() of live object state shows **** (parity with SmtpTransport's password mask).
__serialize(): arrayRefuse 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): staticRefuse var_export() resurrection.

SmtpTransport final class

Sends email via direct SMTP (TCP/TLS).

MethodSummary
static isValidHost(string $host): boolConstruction-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): selfControl whether the send fails when the channel cannot be encrypted.
withImplicitTls(bool $implicit = true): selfReturn a copy that connects with implicit TLS (SMTPS) regardless of port.
withCaFile(string $caFile): selfReturn a copy that verifies the server certificate against a custom CA bundle instead of the system trust store (e.g. a private CA).
__debugInfo(): arrayMask secrets so the SMTP password never leaks through var_dump() or print_r() reflection of live object state.
__serialize(): arrayRefuse 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): staticRefuse var_export() resurrection — see the __debugInfo contract above for what this does and does not seal.
send(Email $email, ?CancellationToken $token = null): voidSend an email with optional cancellation support.
name(): string
buildMimeMessage(Email $email, bool $allow8Bit = true): stringRender the full RFC 2046 MIME message for an email (headers + body).

Transport interface

Pluggable transport for sending Email messages.

MethodSummary
send(Email $email, ?CancellationToken $token = null): voidSend the email.
name(): stringName of this transport for logging/debugging.

SugarCraft\Mail\Tui

ComposeModel final class

Interactive compose form: candy-mail tui.

MethodSummary
static new(\Closure $send, \Closure $render, array $prefill = []): self
init(): ?\Closure
subscriptions(): ?\SugarCraft\Core\Subscriptions
focused(): stringName of the focused field.
email(): EmailCompose the message from the form; the same gate a send goes through.
update(Msg $msg): arrayEvery 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.

MethodSummary
__construct(public readonly ?string $error, public readonly string $transport = '')

TextBuffer final class

Immutable text-editing buffer behind one compose field.

MethodSummary
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(): selfStart of the current line (the whole buffer when single-line).
end(): self
up(): selfMove one line up keeping the column; stays put on the first line.
down(): selfMove one line down keeping the column; stays put on the last line.
onFirstLine(): boolTrue when the cursor sits on the first line.
onLastLine(): boolTrue when the cursor sits on the last line.
clear(): self
layout(): arraySplit 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.

VariableTypeDefaultEffect
RESEND_API_KEYstringunsetEnables the Resend transport. It wins outright when set.
CANDY_MAIL_MAILGUN_API_KEYstringunsetEnables the Mailgun transport when no Resend key is set. The library reads MAILGUN_API_KEY when constructed without a key.
CANDY_MAIL_MAILGUN_DOMAINstringunsetSending domain. Required with the Mailgun key.
CANDY_MAIL_MAILGUN_REGIONus or euusMailgun API region
CANDY_MAIL_SMTP_HOSThost nameunsetSMTP server. Used when no API key is set.
CANDY_MAIL_SMTP_PORTint587SMTP port. Port 465 selects implicit TLS.
CANDY_MAIL_SMTP_USERNAME, CANDY_MAIL_SMTP_PASSWORDstringemptySMTP credentials. Use an app password for Gmail-style accounts.
CANDY_MAIL_SMTP_REQUIRE_TLSboolean word1Requires TLS. 1, true, yes, on and their off counterparts are accepted. Any other value is refused, never guessed.
CANDY_MAIL_SMTP_IMPLICIT_TLSboolean wordautoUnset auto-detects from the port. Set 1 or 0 to force it.
CANDY_MAIL_SMTP_HELOhostnameemptyEHLO identity. Letters, digits, dots and hyphens only.
CANDY_MAIL_SMTP_CA_FILEpathsystem storeCustom CA bundle for TLS verification
CANDY_MAIL_SMTP_TIMEOUTint, 1 to 360030Connect and per-response timeout in seconds
CANDY_MAIL_FROMaddressunsetDefault sender. The CLI requires it unless --from is given, and never invents one.
CANDY_MAIL_SIGNATUREstringunsetAppended 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.

KeyAction
Tab, Shift+TabMove to the next or previous field
EnterIn the body or the HTML field, insert a newline. Elsewhere, move to the next field.
Up, DownIn 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, EndMove the cursor within the field
Backspace, Delete, Ctrl+UDelete before the cursor, after it, or clear the field
Ctrl+PToggle the preview. Esc in the preview returns to editing.
Ctrl+SSend the composed email through the configured transport
Esc on the edit screen, Ctrl+C, Ctrl+QQuit. 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.php builds Email values and prints their fields. It needs no SMTP or Resend access.
  • examples/basic.php sends through the Resend API when RESEND_API_KEY is set. Without a key it prints the composed MIME message.
  • examples/html-email.php adds CC and BCC recipients, an HTML body and an inline CID image, then prints an offline MIME preview. With RESEND_API_KEY set it tries the Resend API instead, which refuses the inline image with the error keyed resend.cid_unsupported, so the run exits 1. Inline CID needs SMTP or Mailgun.
  • examples/attachments.php attaches two files from disk with withAttachment() and prints the offline MIME preview.
  • examples/smtp.php sends over SMTP when CANDY_MAIL_SMTP_HOST is set. Without it, the example prints the offline preview.
  • examples/pipeline.php reads the message body from stdin, takes an optional recipient and subject from the command line, and sends through Resend when RESEND_API_KEY is 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 followsbin/candy-mail, ComposeModel, Mailer
go-mail NewEmail(), the message library pop sends throughEmail::new() and the Email value object
The SMTP client and its MIME encodingSmtpTransport, with its own MIME builder. Not a line-by-line port.
Resend and Mailgun HTTP APIsResendTransport, 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.

  • sugar-core: the Model, Cmd and Program runtime behind the compose screen, plus the sanitizer used on untrusted output.

Try the quickstart →

Source & demos

Demos.

VHS-recorded GIF of the API showcase, regenerated automatically on every push that touches the source.

Showcase

Showcase

Building Email value objects (recipients, multipart bodies) and printing their resolved fields, with the transports described as text and no SMTP access.