Send with

Send email with Symfony

A small service on Symfony’s HttpClient is all you need. Using Laravel instead? See Send with Laravel.

Setup

composer require symfony/http-client
# .env.local
ROBUSTEMAIL_API_KEY=rb_test_...

The service

<?php
// src/Service/RobustEmail.php
namespace App\Service;

use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Contracts\HttpClient\HttpClientInterface;

final class RobustEmail
{
    public function __construct(
        private HttpClientInterface $client,
        #[Autowire(env: 'ROBUSTEMAIL_API_KEY')] private string $apiKey,
    ) {
    }

    /** Returns the email ID. */
    public function send(array $email, ?string $idempotencyKey = null): string
    {
        $headers = ['Authorization' => 'Bearer '.$this->apiKey];
        if ($idempotencyKey) {
            $headers['Idempotency-Key'] = $idempotencyKey;
        }

        $response = $this->client->request('POST', 'https://robustemail.com/api/v2/emails', [
            'headers' => $headers,
            'json' => $email,
            'timeout' => 15,
        ]);

        // false: read the JSON error body instead of throwing on 4xx/5xx
        $body = $response->toArray(false);
        if ($response->getStatusCode() >= 400) {
            throw new \RuntimeException($body['name'].': '.$body['message']);
        }

        return $body['id'];
    }
}

The #[Autowire(env: ...)] attribute needs Symfony 6.3 or later. On older versions, bind the argument in config/services.yaml.

Send from a controller

use App\Service\RobustEmail;

#[Route('/signup', methods: ['POST'])]
public function signup(Request $request, RobustEmail $email): Response
{
    $user = $this->users->create($request->toArray()); // your own code

    $email->send([
        'from' => 'Acme <hello@acme.com>',
        'to' => $user->getEmail(),
        'subject' => 'Welcome to Acme',
        'html' => $this->renderView('emails/welcome.html.twig', ['user' => $user]),
    ], 'welcome-user-'.$user->getId());

    return $this->json(['ok' => true], 201);
}

Twig escapes variables in .html.twig templates automatically.

Send in the background

Dispatch a Messenger message and call RobustEmail::send() from its handler. Messenger retries failed messages; because the idempotency key stays the same on each retry, the email is still sent only once.

Next