# Send Email with PHP: A Complete API Tutorial

> Send email with PHP using cURL and an email API instead of mail(): HTML, templates, attachments, batches, safe retries and a contact form, with working code.

Canonical: https://www.cresca.xyz/blog/send-email-php
Author: Lalit Kumar Jangid
Published: 2026-10-27
Last updated: 2026-10-30

If you want to **send email with PHP** from a real app, `mail()` is the wrong tool. It hands the message to the server's local mailer, usually from a shared IP without DKIM for your domain, and on failure it returns `false` and nothing else. An email API replaces all of that with one HTTPS request from the cURL extension. Cresca accepts the message, gives you an id back and delivers it from your own verified domain with SPF and DKIM in place. Below: the bare request, a reusable `cresca()` function with retries, then templates, attachments, batches and a contact form.

**In short**

- One `curl_init()` call POSTs JSON to `https://api.cresca.xyz/api/v1/emails` with an `Authorization: Bearer` header.
- Plain PHP 8 and the cURL extension, no Composer package.
- Send an `Idempotency-Key` and retry only on timeouts, 429 and 5xx.

## Before you start

- **PHP 8.0 or newer with cURL.** `php -m | grep curl` tells you if it is loaded. On Debian and Ubuntu it comes from the `php-curl` package.
- **A verified domain and a sender.** Add the domain under [Sending Domains](https://app.cresca.xyz/sending-domains) and publish the DKIM, MAIL FROM and ownership records it lists (Cresca can add them for you if the DNS is on Cloudflare). Then create a sender such as `hello@acme.com`. Any `from` address you use has to be an active sender on that domain.
- **A sending key.** Create one on the [API keys](https://app.cresca.xyz/api-keys) page with *Sending access*. It can send but cannot read logs or edit templates. It starts with `cr_live_` and you only see it once.

The [email API quickstart](https://www.cresca.xyz/docs/quickstart) covers the account side in more detail.

### Where PHP should find the key

The examples read `getenv('CRESCA_API_KEY')`. PHP-FPM starts workers with `clear_env = yes` by default, so a variable exported in your shell or systemd unit never reaches your script; add `env[CRESCA_API_KEY] = cr_live_...` to the pool config instead. Under Apache, `SetEnv` in the virtual host works. On shared hosting with neither option, keep it in a config file outside the web root and out of Git.

## Send email with PHP: the basic request

```php
<?php
$payload = [
    'from' => 'Acme <hello@acme.com>',
    'to' => 'ana@example.com',
    'subject' => 'Welcome to Acme',
    'html' => '<p>Hi Ana, your account is ready.</p>',
];

$ch = curl_init('https://api.cresca.xyz/api/v1/emails');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 10,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('CRESCA_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode($payload),
]);
$raw = curl_exec($ch);
if ($raw === false) {
    throw new RuntimeException('Network error: ' . curl_error($ch));
}
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$body = json_decode($raw, true);

if ($status !== 200) {
    throw new RuntimeException("{$body['name']}: {$body['message']}");
}
echo $body['id'], PHP_EOL;
```

cURL in PHP reports problems as return values, not exceptions. `curl_exec()` returns `false` when the request never got a response (DNS failure, refused connection, the 10 second `CURLOPT_TIMEOUT`), and `curl_error()` says why. Any HTTP response, even a 422, comes back as a string, so you check the status yourself. When Cresca accepts the email you get `200` and an id:

```json
{ "id": "4ef9a417-02e9-4d39-ad75-9611e0fcc33c" }
```

For `to` you can pass one address or an array. The limit is 50 recipients per email, counted across `to`, `cc` and `bcc`. Leave out `text` and Cresca generates the plain-text version from your `html`.

## A cresca() function you can reuse

A one-off script can live with the code above. A web app needs three more things:

- **Idempotency.** The optional third argument becomes an `Idempotency-Key` header. If the connection drops after Cresca accepted the email, a retry with the same key gets the original response and no second email. Keys last 24 hours. Derive them from the thing that happened, like `welcome/user-123` or `invoice/inv-2026-0042`. A timestamp or `uniqid()` defeats the point. Details are in [idempotency](https://www.cresca.xyz/docs/idempotency).
- **Selective retries.** It retries when `curl_exec()` returns `false`, on `5xx`, on `429 rate_limit_exceeded` and on `409 concurrent_idempotent_requests`. The `CURLOPT_HEADERFUNCTION` callback picks up `retry-after`; without it the function waits 1, 2, then 4 seconds plus jitter. Any other 4xx is thrown straight away, since sending the same body again gets the same answer.
- **Exceptions with something to branch on.** Cresca's error bodies look like `{"statusCode": 422, "name": "validation_error", "message": "..."}`. The function throws a `RuntimeException` whose code is the HTTP status (0 for a network failure) and whose message starts with the `name`. Match on the name, not the wording of the message, which can change.

```php
<?php
// cresca.php: a small client for the Cresca email API.

function cresca(string $path, array $payload, ?string $idempotencyKey = null, int $attempts = 4): array
{
    $headers = [
        'Authorization: Bearer ' . getenv('CRESCA_API_KEY'),
        'Content-Type: application/json',
    ];
    if ($idempotencyKey !== null) {
        $headers[] = 'Idempotency-Key: ' . $idempotencyKey;
    }
    $json = json_encode($payload, JSON_THROW_ON_ERROR);

    for ($attempt = 1; ; $attempt++) {
        $retryAfter = 0;
        $ch = curl_init('https://api.cresca.xyz/api/v1' . $path);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_POSTFIELDS => $json,
            CURLOPT_HEADERFUNCTION => function ($ch, string $line) use (&$retryAfter): int {
                if (stripos($line, 'retry-after:') === 0) {
                    $retryAfter = (int) trim(substr($line, 12));
                }
                return strlen($line);
            },
        ]);
        $raw = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $body = is_string($raw) ? (json_decode($raw, true) ?? []) : [];

        if ($status >= 200 && $status < 300) {
            return $body;
        }

        // $raw === false means a network error or timeout: safe to retry.
        $name = $body['name'] ?? ($raw === false ? 'network_error' : 'unknown_error');
        $retryable = $raw === false
            || $status >= 500
            || ($status === 429 && $name !== 'monthly_quota_exceeded')
            || $name === 'concurrent_idempotent_requests';
        if (!$retryable || $attempt >= $attempts) {
            $message = $body['message'] ?? curl_error($ch);
            throw new RuntimeException("Cresca {$status} {$name}: {$message}", $status);
        }
        // Wait for retry-after, or 1s, 2s, 4s... plus jitter.
        $seconds = $retryAfter > 0 ? $retryAfter : 2 ** ($attempt - 1) + mt_rand(0, 250) / 1000;
        usleep((int) ($seconds * 1000000));
    }
}
```

One PHP-specific catch: `usleep()` blocks the worker. With four attempts and a 10 second timeout, a bad outage can hold a PHP-FPM process for nearly 50 seconds. In a web request, pass a lower `$attempts` or send from a background worker. Calling it:

```php
<?php
require __DIR__ . '/cresca.php';

$name = htmlspecialchars($user['first_name'], ENT_QUOTES, 'UTF-8');

$sent = cresca('/emails', [
    'from' => 'Acme <hello@acme.com>',
    'to' => $user['email'],
    'subject' => 'Welcome to Acme',
    'html' => "<p>Hi {$name}, your account is ready.</p>",
], "welcome/{$user['id']}");
```

`htmlspecialchars()` with `ENT_QUOTES` and `'UTF-8'` stops a first name like `<script>` from becoming markup. Prefer Guzzle? Pass the payload as `json =>`, send the same headers and keep the same retry rules.

## Send a Cresca template instead of PHP-built HTML

HTML in heredocs gets hard to edit. Cresca's template editor lets you design the email once and mark the dynamic parts with triple braces, for example `{{{RESET_LINK}}}`. After you publish it, your PHP sends the template alias and an array of values. Only the *published* version is ever sent, so drafts are safe to edit. Cresca HTML-escapes each value, which means you can pass `$user['first_name']` without `htmlspecialchars()` here. Forget a variable that has no fallback and the call throws with `422 validation_error` naming the missing one. See [templates and variables](https://www.cresca.xyz/docs/templates).

```php
<?php
cresca('/emails', [
    'to' => $user['email'],
    'template' => [
        'id' => 'password-reset', // the template's alias or id
        'variables' => ['NAME' => $user['first_name'], 'RESET_LINK' => $resetUrl],
    ],
], "password-reset/{$resetRequestId}");
```

## Attach a PDF or an image

Attachments travel inside the JSON as base64, so in PHP it is `file_get_contents()` followed by `base64_encode()`. Check the path first: on a missing file `file_get_contents()` returns `false`, and encoding that gives an empty attachment. Each entry needs `filename` and `content`, and `content_type` is optional. Give an image a `content_id` and you can show it inline with `<img src="cid:logo">`. Limits per email: 20 files and 7 MB in total. Executables such as .exe and .js are rejected, and you cannot attach by URL yet.

```php
<?php
cresca('/emails', [
    'from' => 'Acme Billing <billing@acme.com>',
    'to' => $customer['email'],
    'subject' => 'Your invoice INV-2026-0042',
    'html' => '<p>Thanks for your payment. Your invoice is attached.</p>',
    'attachments' => [[
        'filename' => 'inv-2026-0042.pdf',
        'content' => base64_encode(file_get_contents(__DIR__ . '/invoices/inv-2026-0042.pdf')),
        'content_type' => 'application/pdf',
    ]],
], 'invoice/inv-2026-0042');
```

## Send a batch of up to 100 emails

For bulk sends to your own users, such as a weekly summary, `POST /emails/batch` takes an array of up to 100 emails, which maps neatly onto `array_chunk($emails, 100)`. Each item takes the same fields as a single send, minus `attachments` and `scheduled_at`. Validation is all or nothing: one bad item and the whole chunk is rejected, with the error message pointing at the zero-based index of the culprit. On success, `$result['data']` holds the ids in your order. A batch counts as one request toward your rate limit, so this is how you reach thousands of emails a minute.

```php
<?php
$emails = array_map(fn (array $user) => [
    'from' => 'Acme <hello@acme.com>',
    'to' => $user['email'],
    'subject' => 'Your weekly summary',
    'html' => renderSummary($user),
], $users);

foreach (array_chunk($emails, 100) as $index => $chunk) {
    $result = cresca('/emails/batch', $chunk, "weekly-summary/2026-10-27/{$index}");
    echo "Batch {$index}: " . count($result['data']) . " emails accepted\n";
}
```

The chunk index in the idempotency key only stays stable if `$users` comes back in the same order on a re-run, so sort the query by id.

## Handle a contact form in plain PHP

Most PHP sites send email for a contact form. Address the message to your own team from your verified sender, set `reply_to` to the visitor so you can answer with one click, and send `text` rather than `html` so whatever they typed is never rendered:

```php
<?php
require __DIR__ . '/cresca.php';

$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$message = trim((string) filter_input(INPUT_POST, 'message'));

if (!$email || $message === '' || strlen($message) > 5000) {
    http_response_code(422);
    exit('Please enter a valid email address and a message.');
}

cresca('/emails', [
    'from' => 'Acme Website <website@acme.com>',
    'to' => 'team@acme.com',
    'reply_to' => $email,
    'subject' => 'New contact form message',
    'text' => "From: {$email}\n\n{$message}",
]);

echo 'Thanks, we will get back to you soon.';
```

The visitor's address must not go in `from`. Cresca only sends from your verified domain, and a forged from address would fail SPF and DKIM at the receiving end anyway. Add a CAPTCHA or a per-IP rate limit, or bots will spend your allowance.

## mail(), PHPMailer or an HTTP API?

`mail()` relies on the server's sendmail setup, hides errors and rarely lines up with SPF, DKIM and DMARC. PHPMailer and Symfony Mailer are fine SMTP clients when you have an SMTP server to talk to. Shared hosts and container platforms often block outbound SMTP ports, while HTTPS works everywhere, and you get JSON errors and idempotency keys that SMTP has no equivalent for. Cresca has no SMTP relay yet, so the API is the way in. On Laravel, the [send email with Laravel](https://www.cresca.xyz/blog/send-email-laravel) guide uses the framework's Http client and Mailables instead of raw cURL.

## Errors to handle when you send email with PHP

The ones you will actually see, and how `cresca()` treats each. The rest are on the [errors page](https://www.cresca.xyz/docs/errors).

| name | Status | What cresca() does | What you do |
| --- | --- | --- | --- |
| `invalid_from_address` | 403 | Throws right away | Use an active sender on a verified domain |
| `validation_error` | 422 | Throws right away | Fix the field, or pass the template variable it names |
| `missing_required_field` | 422 | Throws right away | Add `to`, `from` or `subject`, or use a template that sets them |
| `rate_limit_exceeded` | 429 | Sleeps for `retry-after`, then retries | If it keeps happening, batch your sends |
| `monthly_quota_exceeded` | 429 | Throws right away | The plan's monthly email allowance is spent |
| `concurrent_idempotent_requests` | 409 | Retries shortly | Nothing; a request with that key is still in progress |
| `application_error` | 5xx | Retries with backoff | Nothing, unless it outlasts the retries |

One case is not an error at all: addresses on your suppression list (past hard bounces, complaints and unsubscribes) are skipped while the call still returns 200. See [suppression](https://www.cresca.xyz/docs/suppression).

## Check that the email was delivered

Save `$body['id']` next to the user or order. A `200` only means Cresca took the email, not that the recipient's server accepted it. The [Transactional](https://app.cresca.xyz/transactional) page shows a timeline per email. From the command line you can fetch it with a full-access key, since a sending key cannot read logs:

```bash
curl https://api.cresca.xyz/api/v1/emails/4ef9a417-02e9-4d39-ad75-9611e0fcc33c \
  -H "Authorization: Bearer $CRESCA_API_KEY"
```

Watch `last_event`: it starts at `queued`, becomes `sent`, and ends as `delivered` or `bounced`. All the states are listed under [email lifecycle](https://www.cresca.xyz/docs/email-lifecycle).

## Frequently asked questions

### Why do emails from PHP mail() land in spam?

The server's local mailer usually sends from a shared IP with no SPF, DKIM or DMARC alignment for your domain. Gmail and Yahoo require that authentication from bulk senders and filter mail that lacks it. Sending through an API from a verified domain fixes the alignment.

### Can I call this from WordPress?

Yes. cresca() is plain PHP, so a plugin or theme can include it. Put the key in wp-config.php or an environment variable, never in the options table or a theme file, and only call it from server-side hooks.

### Is there a Composer package for Cresca?

No, and you don't need one. The API is plain HTTPS and JSON, so cURL or Guzzle is enough. The function above is a few dozen lines you can drop into your project and own.

## The same tutorial in other languages

[Node.js](https://www.cresca.xyz/blog/send-email-nodejs) · [Python](https://www.cresca.xyz/blog/send-email-python) · [Go](https://www.cresca.xyz/blog/send-email-golang) · [Ruby](https://www.cresca.xyz/blog/send-email-ruby) · [Java](https://www.cresca.xyz/blog/send-email-java) · [C# and .NET](https://www.cresca.xyz/blog/send-email-csharp) · [Next.js](https://www.cresca.xyz/blog/send-email-nextjs) · [Laravel](https://www.cresca.xyz/blog/send-email-laravel) · [Django](https://www.cresca.xyz/blog/send-email-django) · [Ruby on Rails](https://www.cresca.xyz/blog/send-email-rails)

Need a field this post skipped? The [send email API guide](https://www.cresca.xyz/blog/send-email-api) documents every one with cURL. The [transactional email API overview](https://www.cresca.xyz/blog/transactional-email-api) explains how the pieces fit, and [SMTP vs API](https://www.cresca.xyz/blog/smtp-vs-api-sending) helps if you are still choosing between PHPMailer and HTTP.

## Start sending

Copy `cresca.php` into your project, set `CRESCA_API_KEY` where PHP can read it, and send. **[Create a Cresca account](https://app.cresca.xyz/signup)**: it's free for 30 days: 250 contacts, 1,000 emails and 20 AI emails, no credit card. Then work through the [quickstart](https://www.cresca.xyz/docs/quickstart) or the [API docs](https://www.cresca.xyz/docs).
