# Send Email with Laravel Using an Email API

> Send email with Laravel through an email API with the Http client: a service class with retries, Mailables rendered to HTML, queued jobs, templates and batches.

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

You can **send email with Laravel** through an HTTP API using only what the framework already ships. The `Http` facade handles the bearer token, JSON, timeouts and retries, your Mailables already render HTML, and the queue already runs work in the background. No mail driver package is involved. With Cresca the send is one POST to `https://api.cresca.xyz/api/v1/emails`; you get an email id back and the message goes out from your own verified domain. This guide wires those Laravel pieces together: a service class, Mailables rendered to HTML, a queued job, then templates, attachments and batches.

**What you will end up with**

- The key in `.env`, read through `config/services.php`.
- An `App\Services\Cresca` class built on `Http::withToken()->retry()`.
- Existing Mailables sent through Cresca with `->render()`.
- A queued job whose retries can never send the same email twice.

## Before you start

- **Laravel 10 or later.** The `Http` client is built in (it wraps Guzzle), so there is nothing extra to `composer require`.
- **A queue worker** if you want the queued example: any driver works, `database` included, with `php artisan queue:work` running.
- **A verified domain and sender in Cresca.** Add the domain in [Sending Domains](https://app.cresca.xyz/sending-domains), publish the DKIM, MAIL FROM and ownership records it gives you (or let Cresca publish them if you use Cloudflare DNS), then add a sender like `hello@acme.com`. Every `from` must be an active sender on that domain.
- **A key with *Sending access*** from the [API keys](https://app.cresca.xyz/api-keys) page. It sends but cannot read logs or touch templates, begins with `cr_live_` and is displayed once.

The [email API quickstart](https://www.cresca.xyz/docs/quickstart) covers the Cresca side step by step.

## Put the key in .env and config/services.php

```bash
# .env
CRESCA_API_KEY=cr_live_xxxxxxxxx
```

```php
// config/services.php
'cresca' => [
    'key' => env('CRESCA_API_KEY'),
],
```

Application code should call `config('services.cresca.key')`, not `env()`. Once you run `php artisan config:cache` in production, Laravel stops loading `.env` and every `env()` call outside a config file returns null. That is the usual reason a send works locally and fails after deploy. Keep the real key out of Git and set it in your server's environment or your host's secret settings.

## Send email with Laravel: the service class

A single `Http::post()` would work. The class below adds the three things that matter once real users are involved:

- **An idempotency key per event.** The third argument becomes an `Idempotency-Key` header. When a timeout hides the fact that Cresca already accepted the email, the retry with the same key returns the first response instead of sending again. Keys are kept for 24 hours. Build them from the model and the event, such as `welcome/user-123` or `invoice/inv-2026-0042`; `now()` or `Str::uuid()` would make every retry look new. More in [idempotency](https://www.cresca.xyz/docs/idempotency).
- **A `retry()` that knows which failures are temporary.** Laravel calls `shouldRetry()` with the exception from each failed attempt. It says yes to a `ConnectionException` (timeout or network error), any `5xx`, `429 rate_limit_exceeded` and `409 concurrent_idempotent_requests`. Other 4xx responses fail at once, because resending the same payload gets the same rejection. `delay()` returns milliseconds: Cresca's `Retry-After` when present, otherwise 1, 2 and 4 seconds plus jitter.
- **Error names you can match.** Cresca returns errors as `{"statusCode": 422, "name": "validation_error", "message": "..."}`. The `name` is stable; the message text may change.

```php
<?php

namespace App\Services;

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Throwable;

class Cresca
{
    public static function post(string $path, array $payload, ?string $idempotencyKey = null): array
    {
        return Http::baseUrl('https://api.cresca.xyz/api/v1')
            ->withToken(config('services.cresca.key'))
            ->withHeaders(array_filter(['Idempotency-Key' => $idempotencyKey]))
            ->acceptJson()
            ->timeout(10)
            ->retry(4, fn (int $attempt, Throwable $e) => self::delay($attempt, $e), fn (Throwable $e) => self::shouldRetry($e))
            ->post($path, $payload)
            ->json();
    }

    private static function shouldRetry(Throwable $e): bool
    {
        if ($e instanceof ConnectionException) {
            return true; // network error or timeout: the idempotency key makes a retry safe
        }
        if (! $e instanceof RequestException) {
            return false;
        }
        $status = $e->response->status();
        $name = $e->response->json('name');

        return $status >= 500
            || ($status === 429 && $name !== 'monthly_quota_exceeded')
            || $name === 'concurrent_idempotent_requests';
    }

    private static function delay(int $attempt, Throwable $e): int
    {
        $retryAfter = $e instanceof RequestException ? (int) $e->response->header('Retry-After') : 0;

        // Milliseconds: retry-after if Cresca sent it, else 1s, 2s, 4s... plus jitter.
        return $retryAfter > 0 ? $retryAfter * 1000 : 2 ** ($attempt - 1) * 1000 + random_int(0, 250);
    }
}
```

Because `retry()` throws by default, a request that is still failing after the last attempt, or one `shouldRetry()` refused, ends in a `RequestException`. Catch it and read `$e->response->json('name')` to decide what to do. A network failure on the last attempt surfaces as `ConnectionException` instead.

## Send your existing Mailables through Cresca

You don't have to give up Mailables. Calling `render()` on one returns the finished HTML, with its Blade or Markdown layout applied, so you build emails the way you always have and only change the last step:

```php
use App\Mail\WelcomeMail;
use App\Services\Cresca;

Cresca::post('/emails', [
    'from' => 'Acme <hello@acme.com>',
    'to' => $user->email,
    'subject' => 'Welcome to Acme',
    'html' => (new WelcomeMail($user))->render(),
], "welcome/{$user->id}");
```

Blade escapes everything inside `{{ }}`, so user data in the view can't break your markup. On success `Cresca::post()` returns an array like `["id" => "4ef9a417-..."]`.

## Queue the send

An HTTP call inside a controller makes the user wait for it, and a slow response ties up the PHP worker. Push the send onto the queue instead:

```php
<?php

namespace App\Jobs;

use App\Mail\WelcomeMail;
use App\Models\User;
use App\Services\Cresca;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class SendWelcomeEmail implements ShouldQueue
{
    use Queueable;

    public int $tries = 5;

    public function __construct(public User $user) {}

    public function handle(): void
    {
        Cresca::post('/emails', [
            'from' => 'Acme <hello@acme.com>',
            'to' => $this->user->email,
            'subject' => 'Welcome to Acme',
            'html' => (new WelcomeMail($this->user))->render(),
        ], "welcome/{$this->user->id}");
    }
}

// In your controller, after creating the user:
SendWelcomeEmail::dispatch($user);
```

There are now two layers of retries. `Http::retry()` covers short blips inside one job run, and `$tries = 5` lets the worker run the job again after a longer outage. You can space those runs out with a `$backoff` property on the job. Both layers send the same `welcome/{id}` key, so however many times the job runs within 24 hours, the user gets one welcome email. The single `Queueable` trait is what Laravel 11 generates. On Laravel 10, keep the four traits your generated job has: `Dispatchable`, `InteractsWithQueue`, `Queueable` and `SerializesModels`.

## Send a Cresca template with variables

Blade views are fine for emails developers own. For emails other people edit, Cresca's template editor is the better home. Mark the dynamic parts with triple braces such as `{{{RESET_LINK}}}`, publish, and from Laravel send only the alias and a `variables` array. Cresca always sends the *published* version, so editing a draft can't affect live mail. Variable values are HTML-escaped, just like Blade's `{{ }}`. If a variable without a fallback is missing, you get `422 validation_error` naming it. See [templates and variables](https://www.cresca.xyz/docs/templates).

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

## Attach files from Laravel Storage

Attachments go in the JSON body as base64. With Laravel's filesystem that is `base64_encode(Storage::get($path))`, and it works the same whether the default disk is local or S3. Each attachment has a `filename`, the `content` and an optional `content_type`; set `content_id` to reference an image inline as `<img src="cid:logo">`. One email can carry up to 20 files and 7 MB in total. Executable types such as .exe and .js are refused, and URL attachments are not supported yet. The example also renders a plain Blade view with `view(...)->render()`, which works when you don't need a full Mailable.

```php
use Illuminate\Support\Facades\Storage;

Cresca::post('/emails', [
    'from' => 'Acme Billing <billing@acme.com>',
    'to' => $invoice->customer->email,
    'subject' => "Your invoice {$invoice->number}",
    'html' => view('emails.invoice', ['invoice' => $invoice])->render(),
    'attachments' => [[
        'filename' => "{$invoice->number}.pdf",
        'content' => base64_encode(Storage::get($invoice->pdf_path)),
        'content_type' => 'application/pdf',
    ]],
], "invoice/{$invoice->number}");
```

## Send a batch of up to 100 emails with chunkById

`POST /emails/batch` accepts up to 100 emails in one array, which lines up with Eloquent's `chunkById(100, ...)`. Every item takes the same fields as a single send except `attachments` and `scheduled_at`. If any item is invalid, the whole batch is rejected and the message names the bad one by zero-based index. A good response is `{"data": [{"id": "..."}, ...]}` in input order. The batch costs one request against your rate limit, so this is the way to send thousands a minute.

```php
User::query()->where('wants_summary', true)->chunkById(100, function ($users, $page) {
    $emails = $users->map(fn (User $user) => [
        'from' => 'Acme <hello@acme.com>',
        'to' => $user->email,
        'subject' => 'Your weekly summary',
        'html' => (new WeeklySummary($user))->render(),
    ])->values()->all();

    Cresca::post('/emails/batch', $emails, "weekly-summary/2026-10-27/{$page}");
});
```

The closure's second argument is the page number. It is stable between runs, which makes it a good part of the idempotency key: if the command dies halfway and you rerun it over the same rows within 24 hours, the chunks that already went out are not sent again. `chunkById` also avoids the skipped rows you can get from `chunk()` when the query filters on a column you update.

## Why not a custom mail transport?

You could write a Symfony Mailer transport so `Mail::to()->send()` goes through Cresca. That is more code, and the mail layer hides the two things that make an API worth using: the idempotency key and the error `name`. A service class keeps both in your hands. Laravel's `smtp` mailer is not an option either, since Cresca has no SMTP relay yet. Not on a framework? The [PHP tutorial](https://www.cresca.xyz/blog/send-email-php) does the same with plain cURL.

## Errors to handle when you send email with Laravel

How each common error shows up in Laravel. The complete list is on the [errors page](https://www.cresca.xyz/docs/errors).

| name | Status | In Laravel | Fix |
| --- | --- | --- | --- |
| `invalid_from_address` | 403 | `RequestException`, no retry | Send from an active sender on a verified domain |
| `validation_error` | 422 | `RequestException`, no retry | Correct the field or supply the named template variable |
| `missing_required_field` | 422 | `RequestException`, no retry | Set `to`, `from` and `subject`, or use a template that does |
| `rate_limit_exceeded` | 429 | `retry()` waits for `Retry-After` | Use batches if you hit it often |
| `monthly_quota_exceeded` | 429 | `RequestException`, no retry | The plan's email allowance is used up for the month |
| `concurrent_idempotent_requests` | 409 | `retry()` tries again shortly | None; the same key is still being processed |
| `application_error` | 5xx | `retry()` backs off, then the job retries | None; the fault is on Cresca's side |

Suppressed recipients (earlier hard bounces, complaints and unsubscribes) are skipped without an error; the request still succeeds. See [suppression](https://www.cresca.xyz/docs/suppression).

## Check that the email was delivered

A `200` tells you Cresca accepted the email, not that it landed. Storing the returned id on the related model, say a `cresca_email_id` column on invoices, makes support questions easy to answer later. The [Transactional](https://app.cresca.xyz/transactional) page in the app shows each email's timeline, or you can query it with a full-access key:

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

`last_event` goes from `queued` to `sent`, then to `delivered` or `bounced`. Every state is described in [email lifecycle](https://www.cresca.xyz/docs/email-lifecycle).

## Frequently asked questions

### Can I keep my Mailables and Blade views?

Yes. render() returns a Mailable's final HTML, so you keep writing emails in Blade or Markdown and only change how they leave the app. For emails non-developers edit, you can also use a Cresca template and send just the alias and variables.

### Why does the key work locally but not in production?

Almost always config caching. After php artisan config:cache, env() returns null outside config files. Read the key through config('services.cresca.key') and run config:cache again after changing .env.

### Will a retried queue job send the email twice?

Not if you pass an idempotency key built from the event, such as welcome/123. A retry within 24 hours with the same key and body gets the original result back from Cresca, and nothing new is sent.

## 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) · [PHP](https://www.cresca.xyz/blog/send-email-php) · [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) · [Django](https://www.cresca.xyz/blog/send-email-django) · [Ruby on Rails](https://www.cresca.xyz/blog/send-email-rails)

The [send email API guide](https://www.cresca.xyz/blog/send-email-api) lists every request field with cURL examples. For how transactional sending fits together, see the [transactional email API overview](https://www.cresca.xyz/blog/transactional-email-api), and if you are weighing Laravel's SMTP mailer against HTTP, read [SMTP vs API](https://www.cresca.xyz/blog/smtp-vs-api-sending).

## Start sending

Add the config entry, drop in the service class and dispatch your first job. **[Sign up for Cresca](https://app.cresca.xyz/signup)**, which is free for 30 days: 250 contacts, 1,000 emails and 20 AI emails, no credit card. The [quickstart](https://www.cresca.xyz/docs/quickstart) and the [API docs](https://www.cresca.xyz/docs) cover the rest.
