How to Send Email from PHP with an API (Laravel and Plain PHP)
Send email from PHP with an API instead of SMTP: one Composer install, HTML, attachments and Laravel queue jobs, with replies landing back in the same inbox.

You want to send email from PHP: a sign-in link, a receipt with a PDF, a “we got your message” note from a contact form. The first thing most tutorials reach for is mail(), and the second is PHPMailer pointed at an SMTP server. Both work, and both leave you configuring hosts, ports, TLS and passwords, then guessing what happened to a message once it left your code.
This tutorial takes the other route: a send email API for PHP. You install one Composer package, give it an API key from the environment, and call send(). The call goes over HTTPS and comes back with a result or an error code you can act on. Because Mailcycle also receives mail, the replies come back to the same address, and the same client can read them.
By the end you’ll have a plain-PHP script and a Laravel controller and queued job that send transactional email with HTML and attachments, reply in the thread, wait for an answer, and handle errors by code. It takes about twenty minutes.
To read mail as well as send it, see How to receive email in PHP: create an address, wait for a message, save attachments and handle a webhook.
Quick answer: how to send email from PHP with an API
Install the mailcycle/mailcycle package with Composer from Mailcycle’s repository, create an API key on the Scale plan, and put it in MAILCYCLE_API_KEY. Then build a client with Mailcycle::withApiKey() and pass an Outgoing message to $mc->messages()->send(). The from must be an address on your account. No SMTP server is involved.
composer config repositories.mailcycle composer https://mailcycle.email/php
composer require mailcycle/mailcycle
use Mailcycle\Mailcycle;
use Mailcycle\Outgoing;
$mc = Mailcycle::withApiKey(getenv('MAILCYCLE_API_KEY') ?: throw new RuntimeException('Set MAILCYCLE_API_KEY'));
$mc->messages()->send(new Outgoing(
'notifications-x7k2@example-pool.email', // from: an address on your account
'someone@example.com', // to: one recipient
'Hello from PHP',
'Sent with the Mailcycle PHP SDK.',
));
That’s the whole integration. The rest of this post makes it production-shaped: environment checks, HTML, attachments, Laravel, retries and replies.
What you’ll build
- A plain-PHP script that sends a transactional email and prints its Message-ID.
- An HTML email with a plain-text part, and an invoice email with a PDF and an inline logo.
- A Laravel setup: the client bound in the service container, a controller that sends an acknowledgement, and a queued job that retries on rate limits.
- A reply flow: send a question, wait for the customer’s answer, and reply in the same thread.
- A Laravel webhook that hears about new mail and reads it in a queue worker.
If you’re comparing languages, the same steps are in the hub post, send email from any language, with sibling posts for Python, TypeScript and Ruby.
Prerequisites
- PHP 8.1 or later with the
sodium,openssl,curl,jsonandmbstringextensions. Most builds include them; check withphp -m. We recommend a supported PHP release kept on its latest patch. - Composer 2.
- A Mailcycle account on the Scale plan, or the free 7-day Scale trial. Sending with an API key starts at Scale. The trial needs no card. See pricing.
- An address on the account to send from. Sending is always from an address you own, never an arbitrary
From. - Laravel 11 or 12 for the Laravel section. The plain-PHP parts need nothing else.
Step 1: Install the PHP email library with Composer
The package is not on Packagist. It’s served from Mailcycle’s own Composer repository, so tell Composer about it first:
composer config repositories.mailcycle composer https://mailcycle.email/php
composer require mailcycle/mailcycle
The first command writes this into your composer.json, which means CI servers, Docker builds and teammates resolve the package without any extra step:
{
"repositories": {
"mailcycle": {
"type": "composer",
"url": "https://mailcycle.email/php"
}
},
"require": {
"mailcycle/mailcycle": "^0.3.0"
}
}
The SDK has no Composer dependencies of its own. It uses PHP’s curl extension for HTTP and libsodium for the encryption, so it adds one package to your vendor/ and nothing else. It’s licensed under Apache 2.0.
Step 2: Create an API key and set the environment
- Sign up at app.mailcycle.email/operator/signup. An account is a twelve-word recovery phrase, not an email and password. Save the phrase somewhere safe.
- Open Plans & Billing and start the free Scale trial, or choose Scale.
- Open API, then the Keys tab. Name the key (for example
production web) and choose Create key. Copy the token now: it starts withmak_and is shown once. - Note the address you’ll send from. Any address on the account works; on Scale you can also bring your own domain and send as
receipts@yourcompany.com.
Put the values in the environment, never in code:
export MAILCYCLE_API_KEY="mak_..."
export MAILCYCLE_FROM="notifications-x7k2@example-pool.email"
In Laravel these go in .env. A key works until you revoke it, and keys are listed in the app with their last four characters, so give each environment its own key and revoke one without touching the others. The authentication guide lists what a key can and cannot do, and API keys covers the endpoints.
Find or create your sending address
To list the addresses on the account from PHP:
<?php
require __DIR__ . '/vendor/autoload.php';
use Mailcycle\Mailcycle;
$mc = Mailcycle::withApiKey(getenv('MAILCYCLE_API_KEY') ?: throw new RuntimeException('Set MAILCYCLE_API_KEY'));
foreach ($mc->addresses()->list() as $address) {
echo $address->emailAddress, ' ', $address->receives ? 'receives' : 'send only', "\n";
}
To create a new one from code, pass the phrase as the second argument. The address’s public key is derived from it, so mail sent to the address can be sealed on arrival:
<?php
require __DIR__ . '/vendor/autoload.php';
use Mailcycle\Mailcycle;
use Mailcycle\NewAddress;
$mc = Mailcycle::withApiKey(
getenv('MAILCYCLE_API_KEY') ?: throw new RuntimeException('Set MAILCYCLE_API_KEY'),
getenv('MAILCYCLE_PHRASE') ?: throw new RuntimeException('Set MAILCYCLE_PHRASE'),
);
$address = $mc->addresses()->create(new NewAddress(prefix: 'notifications', label: 'App notifications'));
echo $address->emailAddress, "\n"; // notifications-x7k2@...
The label is sealed on your machine before it’s stored. On your own domain, pass domain: 'yourcompany.com', localPart: 'receipts' instead of prefix. The email addresses guide has every option.
Step 3: Send your first email from a PHP script
Here’s the minimal script, with the environment checked up front. The ?: throw form (PHP 8.0 and later) fails loudly on a missing variable instead of passing false into a typed parameter:
<?php
require __DIR__ . '/vendor/autoload.php';
use Mailcycle\Mailcycle;
use Mailcycle\Outgoing;
$mc = Mailcycle::withApiKey(getenv('MAILCYCLE_API_KEY') ?: throw new RuntimeException('Set MAILCYCLE_API_KEY'));
$from = getenv('MAILCYCLE_FROM') ?: throw new RuntimeException('Set MAILCYCLE_FROM');
$result = $mc->messages()->send(new Outgoing(
from: $from, // an address on your account
to: 'someone@example.com',
subject: 'Your sign-in link',
text: "Hi,\n\nUse this link to sign in: https://example.com/login/abc123\n",
));
echo $result->messageId, "\n";
Run it with php send.php. send() returns a SendResult:
messageIdis theMessage-IDheader the email went out with. Log it: it’s how you find the message in the recipient’s headers or match a bounce later.sentCopyIdis the id of the copy filed in the address’s Sent folder, ornullwhen the address keeps none.
Outgoing takes named arguments, so the call reads like the email it builds. Its fields are from, to, subject, text, and the optional html, fromName, replyTo and attachments. Each call sends to one recipient: to email several people, call send() once for each, which also gives each of them their own Message-ID and thread.
Step 4: Send HTML email in PHP
Most mail apps render HTML, but a plain-text part still matters: it’s what text-only clients and some inbox previews use. Outgoing requires text and takes html alongside it, and the email goes out with both parts.
<?php
require __DIR__ . '/vendor/autoload.php';
use Mailcycle\Mailcycle;
use Mailcycle\Outgoing;
$mc = Mailcycle::withApiKey(getenv('MAILCYCLE_API_KEY') ?: throw new RuntimeException('Set MAILCYCLE_API_KEY'));
$from = getenv('MAILCYCLE_FROM') ?: throw new RuntimeException('Set MAILCYCLE_FROM');
$name = 'Sam';
$link = 'https://example.com/verify?token=abc123';
$h = fn (string $value): string => htmlspecialchars($value, ENT_QUOTES | ENT_HTML5);
$html = <<<HTML
<!doctype html>
<html>
<body style="font-family: system-ui, sans-serif; line-height: 1.5">
<p>Hi {$h($name)},</p>
<p>Confirm your email address to finish signing up:</p>
<p><a href="{$h($link)}" style="background:#111;color:#fff;padding:10px 16px;border-radius:6px;text-decoration:none">Confirm email</a></p>
<p style="color:#666">If you didn't sign up, ignore this email.</p>
</body>
</html>
HTML;
$text = "Hi {$name},\n\nConfirm your email address to finish signing up:\n{$link}\n\nIf you didn't sign up, ignore this email.\n";
$mc->messages()->send(new Outgoing(
from: $from,
to: 'sam@example.com',
subject: 'Confirm your email address',
text: $text,
html: $html,
fromName: 'Acme Accounts',
));
Three PHP details worth keeping:
- Escape what you interpolate. The
$hclosure wrapshtmlspecialchars(), and heredoc’s{$h($name)}syntax calls it inline. Anything that came from a user, even a first name, goes through it. - Inline your CSS. Some mail clients strip
<style>blocks and ignore external stylesheets, so styles live on the elements. fromNamesets the display name on the From line, like Acme Accounts <notifications-x7k2@…>. It’s one line of up to 78 characters, without quotes, angle brackets or backslashes.
Step 5: Send email with an attachment in PHP
Attachments take raw bytes, so file_get_contents() is all you need; the client does the base64 encoding. Give a file a contentId and it becomes an inline image, shown wherever the HTML says cid: and that id.
<?php
require __DIR__ . '/vendor/autoload.php';
use Mailcycle\Mailcycle;
use Mailcycle\Outgoing;
use Mailcycle\OutgoingAttachment;
$mc = Mailcycle::withApiKey(getenv('MAILCYCLE_API_KEY') ?: throw new RuntimeException('Set MAILCYCLE_API_KEY'));
$from = getenv('MAILCYCLE_FROM') ?: throw new RuntimeException('Set MAILCYCLE_FROM');
$pdf = file_get_contents(__DIR__ . '/invoices/INV-1042.pdf');
$logo = file_get_contents(__DIR__ . '/assets/logo.png');
if ($pdf === false || $logo === false) {
throw new RuntimeException('Could not read the files to attach.');
}
$mc->messages()->send(new Outgoing(
from: $from,
to: 'billing@customer.example',
subject: 'Invoice INV-1042',
text: "Your invoice INV-1042 is attached.\n",
html: '<img src="cid:logo" alt="Acme" width="120"><p>Your invoice <strong>INV-1042</strong> is attached.</p>',
attachments: [
new OutgoingAttachment('INV-1042.pdf', $pdf, mimeType: 'application/pdf'),
new OutgoingAttachment('logo.png', $logo, mimeType: 'image/png', contentId: 'logo'),
],
));
A message can carry up to ten files, 3.5 MB between them. The client checks both before it sends anything, so an oversized batch fails fast with too_many_attachments or attachments_too_large rather than after an upload. Program and script files such as .exe or .js are refused with attachment_blocked. mimeType defaults to application/octet-stream, so set it for anything the recipient should open in place. If you generate PDFs in memory (with Dompdf, for example), pass the string it returns straight in; there’s no need to write a temp file.
The sending mail guide lists every field and the exact size rules.
Step 6: Send email from Laravel with an API
In Laravel, the client belongs in the service container. Bind it once and type-hint it wherever you send: controllers, jobs, listeners, Artisan commands.
1. Add the settings to config/services.php. Reading env() only inside config files keeps the app working after php artisan config:cache:
<?php
return [
// ...your other services
'mailcycle' => [
'key' => env('MAILCYCLE_API_KEY'),
'phrase' => env('MAILCYCLE_PHRASE'), // optional: only to read replies
'from' => env('MAILCYCLE_FROM'),
'webhook_secret' => env('MAILCYCLE_WEBHOOK_SECRET'),
],
];
2. Bind the client as a singleton in app/Providers/AppServiceProvider.php:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Mailcycle\Mailcycle;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(Mailcycle::class, function (): Mailcycle {
$key = config('services.mailcycle.key');
if (!is_string($key) || $key === '') {
throw new \RuntimeException('Set MAILCYCLE_API_KEY in .env');
}
$phrase = config('services.mailcycle.phrase');
return Mailcycle::withApiKey($key, is_string($phrase) && $phrase !== '' ? $phrase : null);
});
}
}
The closure runs the first time something asks for the client, so requests that never send don’t pay for it. With a key alone, building the client is instant and makes no network call. With the phrase as well, it derives the keys (120,000 PBKDF2 iterations) and checks the phrase against the key’s account once. That’s a good reason to leave MAILCYCLE_PHRASE unset on web servers that only send, and set it only on the queue workers that read mail: the phrase then lives on fewer machines, and web requests stay fast.
3. Send from a controller. Here’s an acknowledgement for a contact form, in app/Http/Controllers/ContactController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Mailcycle\Exception\ApiException;
use Mailcycle\Mailcycle;
use Mailcycle\Outgoing;
class ContactController extends Controller
{
public function __construct(private readonly Mailcycle $mailcycle)
{
}
public function store(Request $request): JsonResponse
{
$data = $request->validate([
'email' => ['required', 'email:rfc'],
'name' => ['required', 'string', 'max:100'],
]);
try {
$result = $this->mailcycle->messages()->send(new Outgoing(
from: (string) config('services.mailcycle.from'),
to: $data['email'],
subject: 'We got your message',
text: "Hi {$data['name']},\n\nThanks for getting in touch. Reply to this email if there's anything to add.\n",
fromName: 'Acme Support',
));
} catch (ApiException $e) {
report($e);
return response()->json(['error' => $e->apiCode()], $e->apiCode() === 'rate_limited' ? 429 : 502);
}
return response()->json(['messageId' => $result->messageId], 201);
}
}
4. Add the route in routes/api.php (on Laravel 11 and 12, run php artisan install:api first if the file doesn’t exist). API routes skip the CSRF check that routes/web.php applies to POSTs:
<?php
use App\Http\Controllers\ContactController;
use Illuminate\Support\Facades\Route;
Route::post('/contact', [ContactController::class, 'store']);
The customer’s reply to that acknowledgement goes to the same address, which is where Mailcycle differs from a send-only email API: step 8 picks it up.
Send from a queued job instead
Sending inside the request is fine for a one-off note, but receipts, password resets and anything else that shouldn’t slow the page down belong on the queue. A job also gives you retries for free. This one renders Blade views for both parts and decides what to do from the error code:
<?php
namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Mailcycle\Exception\ApiException;
use Mailcycle\Mailcycle;
use Mailcycle\Outgoing;
use Mailcycle\OutgoingAttachment;
class SendReceipt implements ShouldQueue
{
use Queueable;
/** Uncaught exceptions allowed before the job fails. */
public int $maxExceptions = 3;
public function __construct(
public string $to,
public string $orderNumber,
public string $pdfPath,
) {
}
/** Keep retrying releases for a day, long enough to outlast a daily limit. */
public function retryUntil(): \DateTimeInterface
{
return now()->addHours(26);
}
public function handle(Mailcycle $mailcycle): void
{
$pdf = file_get_contents($this->pdfPath);
if ($pdf === false) {
$this->fail(new \RuntimeException("Missing receipt PDF {$this->pdfPath}"));
return;
}
try {
$mailcycle->messages()->send(new Outgoing(
from: (string) config('services.mailcycle.from'),
to: $this->to,
subject: "Receipt for order {$this->orderNumber}",
text: view('emails.receipt-text', ['order' => $this->orderNumber])->render(),
html: view('emails.receipt', ['order' => $this->orderNumber])->render(),
attachments: [
new OutgoingAttachment("receipt-{$this->orderNumber}.pdf", $pdf, mimeType: 'application/pdf'),
],
));
} catch (ApiException $e) {
match (true) {
$e->apiCode() === 'rate_limited' => $this->release(60),
$e->apiCode() === 'daily_send_limit' => $this->release(now('UTC')->addDay()->startOfDay()->addMinute()),
$e->status() === 0, $e->status() >= 500 => $this->release(30 * $this->attempts()),
default => $this->fail($e), // plan_required, not_your_address, ...: retrying won't help
};
}
}
}
Dispatch it from anywhere with SendReceipt::dispatch($order->email, $order->number, $pdfPath);. Blade’s {{ $order }} escapes for you, so the HTML view needs no htmlspecialchars() calls. Because retryUntil() is defined, Laravel uses it instead of a fixed $tries count, and release() puts the job back without counting as a failure.
Step 7: Reply in the thread and wait for an answer
Transactional email often asks a question: confirm a delivery slot, approve a quote, pick a time. With a send-only API the answer lands somewhere else entirely. With Mailcycle it comes back to the address that sent the question, and the same client can wait for it and answer in the same thread.
Reading mail needs the recovery phrase, so this script passes it as the second argument. Run it from the CLI or a queue worker, not a web request, because waitFor() blocks until a message arrives or the timeout passes:
<?php
require __DIR__ . '/vendor/autoload.php';
use Mailcycle\Exception\ApiException;
use Mailcycle\Mailcycle;
use Mailcycle\Outgoing;
use Mailcycle\WaitFor;
// The phrase lets this process open the reply when it arrives.
$mc = Mailcycle::withApiKey(
getenv('MAILCYCLE_API_KEY') ?: throw new RuntimeException('Set MAILCYCLE_API_KEY'),
getenv('MAILCYCLE_PHRASE') ?: throw new RuntimeException('Set MAILCYCLE_PHRASE'),
);
$from = getenv('MAILCYCLE_FROM') ?: throw new RuntimeException('Set MAILCYCLE_FROM');
$address = null;
foreach ($mc->addresses()->list() as $candidate) {
if ($candidate->emailAddress === $from) {
$address = $candidate;
}
}
if ($address === null) {
throw new RuntimeException("{$from} is not an address on this account.");
}
// Take the time before sending, so a fast reply still counts.
$before = new DateTimeImmutable();
$mc->messages()->send(new Outgoing(
from: $address->emailAddress,
to: 'customer@example.com',
subject: 'Can we confirm your delivery slot?',
text: "Hi,\n\nReply YES to confirm Tuesday 10:00-12:00, or suggest another time.\n",
));
try {
$reply = $mc->messages()->waitFor(new WaitFor(
addressId: $address->id,
from: 'customer@example.com',
timeout: 300,
since: $before,
));
} catch (ApiException $e) {
if ($e->apiCode() === 'timeout') {
exit("No reply within five minutes.\n");
}
throw $e;
}
echo "From: {$reply->fromAddress}\nSubject: {$reply->subject}\n\n{$reply->text}\n";
// Answer in the same thread.
$mc->messages()->send(new Outgoing(
from: $address->emailAddress,
to: $reply->replyTo,
subject: str_starts_with($reply->subject, 'Re:') ? $reply->subject : "Re: {$reply->subject}",
text: "Thanks, you're booked in.\n",
replyTo: $reply,
));
What’s going on:
WaitForfilters by address id, sender and subject (both case-insensitive substrings), with a timeout in seconds. It listens on the event stream and falls back to checking the address every five seconds where the stream can’t be reached. If nothing matches in time it throws anApiExceptionwith the codetimeout.since: $beforeis the detail that matters. The wait counts mail received from that moment on, even mail that landed before the stream was up, so a customer who answers in two seconds isn’t missed.replyTo: $replyfills in the threading for you. The SDK sends the message’s id asinReplyToand itsMessage-IDasinReplyToHeader, so the answer appears under the original in Gmail, Outlook or Apple Mail.$reply->replyTois the address to answer: the sender’sReply-Toif they set one, otherwiseFrom.
The reply comes back as a parsed Message: fromAddress, fromName, subject, text, html and safeHtml, plus attachments. Render safeHtml, never html, if you show a message in your app: it has remote images, stylesheets and embeds removed, the way the Mailcycle apps show mail.
Step 8: Receive email in PHP with a Laravel webhook
waitFor() suits scripts and one-off flows. For an app that should react to every incoming email, such as replies to support acknowledgements, use a webhook. Add one in the app under API, on the Webhooks tab, subscribed to message.received, and copy its signing secret into MAILCYCLE_WEBHOOK_SECRET.
The route verifies the signature against the raw body and hands the work to a queue, because Mailcycle expects a 2xx within ten seconds:
<?php
use App\Jobs\HandleIncomingMail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Mailcycle\WebhookSignature;
Route::post('/hooks/mailcycle', function (Request $request) {
$raw = $request->getContent(); // the body exactly as it arrived
if (!WebhookSignature::verifyNow(
(string) config('services.mailcycle.webhook_secret'),
$raw,
$request->headers->get('Mailcycle-Signature'),
)) {
abort(401);
}
$event = json_decode($raw, true, flags: JSON_THROW_ON_ERROR);
if (is_array($event) && ($event['type'] ?? null) === 'message.received') {
HandleIncomingMail::dispatch((string) $event['payload']['messageId'], (string) $request->headers->get('Mailcycle-Event-Id'));
}
return response()->noContent();
});
Events carry ids, never content, so the job fetches the message and opens it on the worker, which is the machine that holds the phrase:
<?php
namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Mailcycle\Mailcycle;
class HandleIncomingMail implements ShouldQueue
{
use Queueable;
public function __construct(public string $messageId, public string $eventId)
{
}
public function handle(Mailcycle $mailcycle): void
{
// Webhooks can arrive more than once: handle each event once.
if (!Cache::add("mailcycle-event:{$this->eventId}", true, now()->addDays(2))) {
return;
}
$message = $mailcycle->messages()->get($this->messageId); // opened here, with the phrase
if (!$message->opened) {
Log::warning('Mailcycle message could not be opened; is MAILCYCLE_PHRASE set?');
return;
}
$mailcycle->messages()->markRead($message->id);
// Hand it to your own code: attach it to a ticket, an order, a conversation.
Log::info('Mail received', [
'from' => $message->fromAddress,
'subject' => $message->subject,
'text' => mb_substr($message->text, 0, 500),
]);
}
}
Cache::add() only writes when the key is new, which makes it a one-line deduplication on Mailcycle-Event-Id. A message the client can’t open comes back with opened false and empty fields rather than an exception, so a worker without the phrase logs a warning instead of crashing. Failed deliveries are retried for about a day and a half; the webhooks guide has the schedule.
To read a whole folder rather than one message, list() returns a page and all() walks every page. Attachments are fetched and opened one at a time:
<?php
require __DIR__ . '/vendor/autoload.php';
use Mailcycle\Mailcycle;
$mc = Mailcycle::withApiKey(
getenv('MAILCYCLE_API_KEY') ?: throw new RuntimeException('Set MAILCYCLE_API_KEY'),
getenv('MAILCYCLE_PHRASE') ?: throw new RuntimeException('Set MAILCYCLE_PHRASE'),
);
$addressId = 'ibx_k3v9x2mq7a';
$page = $mc->messages()->list($addressId, limit: 20);
foreach ($page->messages as $message) {
if (!$message->opened) {
continue; // no phrase, or the wrong one
}
echo "{$message->receivedAt} {$message->fromAddress} {$message->subject}\n";
foreach ($message->attachments as $attachment) {
$bytes = $mc->messages()->attachment($message, $attachment->index);
file_put_contents(__DIR__ . '/inbox/' . basename($attachment->filename), $bytes);
}
}
basename() matters: an attachment’s file name comes from whoever sent the email, so never use it as a path as it stands. The reading mail guide covers folders, stars and paging.
Handle email API errors in PHP by error code
Everything the SDK throws extends Mailcycle\Exception\MailcycleException, so one catch covers it all. A failed API call is an ApiException with two methods to branch on:
status()is the HTTP status, or0when the request never got an answer (DNS, a timeout, a dropped connection).apiCode()is the API’s stable code, likeplan_requiredorrate_limited. Match on this, never on the message text.
A small retry helper and a match on the code covers what a sender meets in practice:
<?php
require __DIR__ . '/vendor/autoload.php';
use Mailcycle\Exception\ApiException;
use Mailcycle\Exception\MailcycleException;
use Mailcycle\Mailcycle;
use Mailcycle\Models\SendResult;
use Mailcycle\Outgoing;
function sendWithRetry(Mailcycle $mc, Outgoing $outgoing, int $attempts = 4): SendResult
{
for ($attempt = 1; ; $attempt++) {
try {
return $mc->messages()->send($outgoing);
} catch (ApiException $e) {
$retryable = $e->apiCode() === 'rate_limited'
|| $e->status() === 0 // never reached the API
|| $e->status() >= 500; // our side or a provider
if (!$retryable || $attempt >= $attempts) {
throw $e;
}
sleep(min(60, 2 ** $attempt)); // 2, 4, 8 seconds...
}
}
}
$mc = Mailcycle::withApiKey(getenv('MAILCYCLE_API_KEY') ?: throw new RuntimeException('Set MAILCYCLE_API_KEY'));
$from = getenv('MAILCYCLE_FROM') ?: throw new RuntimeException('Set MAILCYCLE_FROM');
$outgoing = new Outgoing($from, 'someone@example.com', 'Hello', 'Hi');
try {
sendWithRetry($mc, $outgoing);
} catch (ApiException $e) {
match ($e->apiCode()) {
'plan_required' => error_log('Sending with an API key needs the Scale plan or above.'),
'not_your_address' => error_log('The from address is not on this account.'),
'invalid_address' => error_log('The recipient address is not valid.'),
'daily_send_limit' => error_log('Today\'s sends are used up; they resume at 00:00 UTC.'),
'attachments_too_large', 'message_too_large', 'too_many_attachments', 'attachment_blocked'
=> error_log('Attachments refused: ' . $e->getMessage()),
default => error_log("Send failed ({$e->status()} {$e->apiCode()}): {$e->getMessage()}"),
};
} catch (MailcycleException $e) {
error_log('Mailcycle client error: ' . $e->getMessage());
}
The split is between errors that time fixes and errors that need a change:
| Code | Status | What to do |
|---|---|---|
rate_limited |
429 | Back off and retry. The message says how long to wait. |
daily_send_limit |
429 | The plan’s sends for today are used. Retry after 00:00 UTC. |
plan_required |
403 | Sending with an API key needs Scale or above. Upgrade or start the trial. |
not_your_address |
403 | from isn’t an address on this account. Check MAILCYCLE_FROM. |
address_paused |
403 | The address is paused after a missed payment. |
domain_not_sending |
409 | Sending isn’t on yet for your own domain; it usually follows receiving within minutes. |
invalid_address |
400 | The recipient address is malformed. Fix the input; don’t retry. |
attachments_too_large, message_too_large |
413 | Shrink or drop files. |
internal, send_failed, provider_error |
5xx | Retry with backoff. |
The per-minute and hourly numbers are on the rate limits page, and every code is in the errors reference. If you raise the client’s timeout for slow networks, pass new Options(timeoutSeconds: 60) as the last argument to withApiKey().
The raw HTTP call: cURL equivalent
Under the hood, send() is one JSON POST to https://api.mailcycle.email/messages/send with the key as a bearer token. Here’s the threaded reply from step 7 as a cURL command, which is handy for testing a key or debugging from a shell:
curl https://api.mailcycle.email/messages/send \
-H "Authorization: Bearer $MAILCYCLE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"from": "notifications-x7k2@example-pool.email",
"to": "customer@example.com",
"subject": "Re: Can we confirm your delivery slot?",
"text": "Thanks, you are booked in.",
"fromName": "Acme Deliveries",
"inReplyTo": "msg_91be02c4a7d1",
"inReplyToHeader": "<CAF8x2k@mail.example.com>"
}'
{ "sent": true, "messageId": "<…>", "sentCopyId": "msg_…" }
Attachments go in an attachments array of objects with filename, mimeType, base64 content and an optional contentId. You can make this call with PHP’s curl_* functions or Guzzle and skip the SDK for sending. What the SDK adds is the other half: creating addresses that receive mail, and opening it, both of which need keys derived from your recovery phrase on your machine. The quickstart walks through the raw API from the first request.
PHP mail() vs PHPMailer vs an email API
PHP gives you three broad ways to send email, and each has its place.
mail() is built in. On Linux and macOS it pipes the message to the program in sendmail_path (sendmail, Postfix or a relay such as msmtp); on Windows it talks SMTP to the host in php.ini. Its true means the local agent accepted the message, which, as the PHP manual notes, does not mean it reached the recipient. Headers, MIME parts and attachments are yours to build.
PHPMailer and Symfony Mailer are mature libraries that build MIME properly and send over SMTP. You supply an SMTP host, a port (587 with STARTTLS or 465 with implicit TLS), a username and a password or app password, and you keep them working as providers change their rules. Laravel’s mailer is built on Symfony Mailer, so the same applies to Mail::to() with the smtp driver.
An email API replaces the SMTP session with an HTTPS request. Mailcycle’s SDK is one of these, with a difference that matters for apps that expect answers: the address you send from is a real inbox, and the same client reads it.
| SMTP library (PHPMailer, Symfony Mailer) | Mailcycle PHP SDK | |
|---|---|---|
| What you configure | SMTP host, port, TLS mode, username, password | One API key in an environment variable |
| Network | Outbound SMTP on 587 or 465, which some hosts restrict | HTTPS on 443 |
| Building the message | The library builds MIME for you | You pass text, html and attachments; the API builds MIME |
| Result of a send | The SMTP server’s acceptance | A SendResult with the Message-ID and Sent copy id, or an ApiException with a stable code |
| Replies | Arrive in whatever mailbox the From belongs to; reading them means IMAP |
Arrive at the same address; waitFor(), all() or a webhook returns them parsed |
| Reading mail in PHP | The IMAP extension (on PECL since PHP 8.4) or a parser library | Built in, no extension |
| Threading | Set In-Reply-To and References yourself |
replyTo: $message fills them in |
| Mail at rest | Depends on the mailbox provider | Stored encrypted; keys derived from your recovery phrase on your machine |
| Dependencies | The library and its requirements | One package, no Composer dependencies |
If you already run a mail server you’re happy with, an SMTP library is a perfectly good choice. If you’d rather not manage SMTP credentials, or your app needs to read the answers to what it sends, the API route is shorter.
Use cases that fit
Mailcycle sends from addresses you own, one recipient per call, and it fits mail where each message matters on its own:
- Transactional and notification mail: receipts, invoices, shipping updates, account alerts.
- Sign-in and verification flows: magic links and one-time codes from your own app, and receiving the codes your own staging services send when you test them.
- Support and operations: acknowledgements that customers can reply to, with the replies handled by the same code.
- AI agents that need an inbox: an agent can have its own address and reply in threads. In PHP you can wire that up with the client above; for MCP clients such as Claude Code, Cursor or any other MCP client, see how to give Claude Code its own email address and the AI agents guide.
Every message you receive is sealed when it reaches Mailcycle, and the copy of every message you send is sealed before it’s stored in Sent. The keys that open them are derived from your recovery phrase on the machine running your PHP code, so mail is encrypted on arrival with your own keys. The encryption overview explains what’s sealed and what stays in the clear.
Security checklist for PHP email code
- Keep the API key in the environment (
.envin Laravel, your host’s secret store in production), never in the repository. Never ship a key inside software you distribute. - One key per environment. Revoke a leaked one in the app under API; anything using it gets
401from then on. - Put the phrase only where mail is read. Sending needs the key alone. Give the phrase to the queue worker that opens replies, not to every web server.
- Escape user data in HTML with
htmlspecialchars()or Blade’s{{ }}. - Verify webhooks against the raw body with
WebhookSignature::verifyNow()before you parse it. - Treat incoming mail as untrusted: render
safeHtml, andbasename()attachment file names before saving them.
Next steps
You now have PHP code that sends transactional email over an API, with HTML, attachments and retries, and reads the replies that come back to the same address. From here:
- PHP email API in Laravel: a receipts inbox per customer, for a full Laravel app with queued jobs, a signed webhook and replies.
- Read the full PHP SDK guide for addresses, sessions, webhooks and the event stream.
- See the PHP SDK page for a one-screen overview, and the developers page for the API and every SDK.
- Bring your own domain with the own domains guide and send as
receipts@yourcompany.com. - Writing a service in another language too? See send email from Go, Java or C#, or start from the series hub.
FAQ
How do I send an email from PHP using an API?
Add Mailcycle's Composer repository, run composer require mailcycle/mailcycle, build a client with Mailcycle::withApiKey(getenv('MAILCYCLE_API_KEY')), and call $mc->messages()->send(new Outgoing($from, $to, $subject, $text)). The request goes over HTTPS to the API, so there is no SMTP server, port or TLS setting to configure. Sending with an API key needs the Scale plan or the free 7-day Scale trial.
Why use an email API instead of PHP's mail() function?
mail() hands the message to whatever mail transfer agent the server has configured, and its true only means that agent accepted it, not that it was delivered. An API call returns a result you can act on: a Message-ID on success, or an error code such as rate_limited or invalid_address when something is wrong. With Mailcycle you also get a copy in Sent and the replies in the same inbox.
How do I send email in Laravel without SMTP?
Bind the Mailcycle client as a singleton in AppServiceProvider, reading the key from config/services.php, then type-hint Mailcycle\Mailcycle in a controller or queued job and call messages()->send(). Laravel's own Mail facade can stay in place for anything else; nothing in the app has to change to use both.
How do I send an email with an attachment in PHP?
Read the file with file_get_contents() and pass it as new OutgoingAttachment('invoice.pdf', $bytes, mimeType: 'application/pdf') in the attachments array of Outgoing. The client base64-encodes it for you. A message can carry up to ten files, 3.5 MB between them, and a contentId turns a file into an inline image for cid: references.
How do I send HTML email from PHP?
Pass both text and html to Outgoing. The plain-text part is required and is what text-only clients and previews show; the HTML part is what most mail apps render. Escape any user data you put into the HTML with htmlspecialchars() or Laravel's Blade {{ }}.
Can I receive email in PHP without the IMAP extension?
Yes. Create an address with $mc->addresses()->create(), then read it with $mc->messages()->all() or wait for the next message with $mc->messages()->waitFor(). Messages come back parsed: sender, subject, text, a safeHtml version with remote content removed, and attachments. The IMAP extension was moved out of PHP's core to PECL in PHP 8.4, and none of this needs it.
Is Mailcycle a PHPMailer alternative?
For mail sent from addresses you own, yes. PHPMailer and Symfony Mailer are good libraries that speak SMTP, so they need an SMTP server and its credentials. The Mailcycle SDK talks to an HTTPS API instead and also reads the replies, so a PHP app can send a message and handle the answer with one client.
Which Mailcycle plan do I need to send email with an API key?
The Scale plan or above. A new account can start a free 7-day Scale trial from Plans & Billing in the web app, with no card. See pricing for what each plan includes.
Can I send from my own domain?
Yes. Scale includes your own domains: add one under My domains in the app or through the API, then create an address like receipts@yourdomain.com and use it as from. The steps are in the own domains guide.
Is the Mailcycle PHP package on Packagist?
No. It is served from Mailcycle's own Composer repository. Run composer config repositories.mailcycle composer https://mailcycle.email/php once in your project, then composer require mailcycle/mailcycle as usual. Composer records the repository in composer.json, so CI and teammates pick it up.
Related
Send email from any language
- Send Email with an API: Code Examples in TypeScript, Python, C#, Go, Rust, PHP, Java, Ruby and Swift (Overview: every language)
- How to Send Email from C# and an ASP.NET Core Web API (C# / .NET)
- How to Send Email from Go (Golang): HTML Templates, a Mailer Package and an API (Go)
- How to Send Email from Java: A Plain Java Program, Spring Boot, HTML, Attachments and Replies (Java / Spring Boot)
- How to Send Email from Python with an API: Scripts, FastAPI and Django (Python)
- How to Send Email from Ruby and Rails with an Email API (Ruby / Rails)
- How to Send Email from Rust with an API: HTML, Attachments, Axum and Replies (Rust)
- How to Send Email From Swift: Vapor, iOS and Server-Side Swift (Swift / Vapor)
- How to Send Email from Node.js and TypeScript (Express and Next.js) (TypeScript / Node.js)