Symfony Mailer sends email through a transport you choose with one environment variable, MAILER_DSN. For SMTP, the DSN holds the host, port and credentials. You then inject MailerInterface wherever you need it and send Email objects. The examples below follow the current Symfony 8 documentation; apart from the require_tls option, which older releases do not have, the same configuration works in Symfony 6 and 7.
Option 1: SMTP with MAILER_DSN
Install and configure
composer require symfony/mailer
In .env.local (or your server’s environment), set the DSN:
MAILER_DSN=smtp://mailcandor:mc_live_xxxxxxxxxxxxxxxx@smtp.mailcandor.com:587?require_tls=true
With Mailcandor’s SMTP relay, the username is mailcandor and the password is your API key. The Flex recipe already wires the DSN into config/packages/mailer.yaml:
framework:
mailer:
dsn: '%env(MAILER_DSN)%'
How TLS works in the DSN
- Port 587: Symfony connects in plain text, sees that the server offers STARTTLS, and upgrades before logging in.
require_tls=truemakes it throw an error instead of continuing if the upgrade fails. - Port 465: use
smtp://...@smtp.mailcandor.com:465. Symfony uses TLS from the first byte on this port.
If a username or password contains reserved URL characters such as @, /, + or :, URL-encode them in the DSN, or the parser will split it in the wrong place. The SMTP ports guide explains 465 versus 587.
Send an email from a controller
<?php
// src/Controller/SignupController.php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Attribute\Route;
class SignupController extends AbstractController
{
#[Route('/signup/welcome', methods: ['POST'])]
public function welcome(MailerInterface $mailer): Response
{
$email = (new Email())
->from('Acme <hello@acme.com>')
->to('sam@example.com')
->replyTo('support@acme.com')
->subject('Welcome to Acme')
->text('Thanks for signing up.')
->html('<p>Thanks for signing up.</p>');
$mailer->send($email);
return new Response('Sent', 202);
}
}
$mailer->send() returns nothing. If it fails, it throws a TransportExceptionInterface, which you can catch to log the error.
Attachments
$email->attachFromPath('/path/to/invoice-1042.pdf', 'invoice-1042.pdf', 'application/pdf');
Twig templates
With Twig installed, use TemplatedEmail instead of Email:
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
$email = (new TemplatedEmail())
->from('Acme <hello@acme.com>')
->to($user->getEmail())
->subject('Welcome to Acme')
->htmlTemplate('emails/welcome.html.twig')
->context(['name' => $user->getFirstName()]);
Keep context() values simple (strings and arrays). Queued emails are serialized, and entities such as Doctrine objects do not serialize cleanly.
Sending in the background with Messenger
If symfony/messenger is installed, $mailer->send() dispatches a SendEmailMessage instead of sending straight away. Route it to an async transport so the request returns immediately:
# config/packages/messenger.yaml
framework:
messenger:
transports:
async: '%env(MESSENGER_TRANSPORT_DSN)%'
routing:
'Symfony\Component\Mailer\Messenger\SendEmailMessage': async
Then run a worker with php bin/console messenger:consume async. The most common “Symfony mailer does not send” problem is a routed message with no worker running. To check your transport without Messenger in the way, run php bin/console mailer:test you@example.com.
Option 2: an email API with HttpClient
If you prefer an HTTP API, Symfony’s HttpClient makes the request in a few lines:
<?php
// src/Service/Mailcandor.php
namespace App\Service;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class Mailcandor
{
public function __construct(
private HttpClientInterface $client,
#[Autowire(env: 'MAILCANDOR_KEY')] private string $key,
) {}
public function send(array $email, ?string $idempotencyKey = null): string
{
$headers = $idempotencyKey ? ['Idempotency-Key' => $idempotencyKey] : [];
$response = $this->client->request('POST', 'https://api.mailcandor.com/v1/emails', [
'auth_bearer' => $this->key,
'headers' => $headers,
'json' => $email,
'timeout' => 10,
]);
return $response->toArray()['id']; // throws on 4xx and 5xx
}
}
$id = $mailcandor->send([
'from' => 'Acme <hello@acme.com>',
'to' => 'sam@example.com',
'subject' => 'Your receipt',
'text' => 'Thanks for your order.',
], 'order-1042-receipt');
toArray() throws an exception for error responses, so failures surface without extra checks. The idempotency key means a retry after a timeout returns the first response instead of sending a duplicate. Install the client with composer require symfony/http-client if your project does not have it.
Testing Symfony email
In functional tests, Symfony records every message the mailer handles, so you can assert on it without sending:
$client->request('POST', '/signup/welcome');
$this->assertEmailCount(1);
$email = $this->getMailerMessage();
$this->assertEmailHtmlBodyContains($email, 'Thanks for signing up');
For local development, set MAILER_DSN=null://null to discard mail, or point it at a local catcher such as Mailpit with MAILER_DSN=smtp://localhost:1025. The Symfony web profiler also shows each email a request sent.
Other Symfony transports
MAILER_DSN also accepts failover(...) and roundrobin(...) with several DSNs inside, separated by spaces, and Symfony has bridge packages for several providers’ HTTP APIs. SMTP works with every provider and needs no extra package, which is why this guide uses it.
Common errors
- “Failed to authenticate on SMTP server”: wrong username or password in the DSN. With Mailcandor the username is
mailcandorand the password is your API key. - “Connection could not be established”: the port is blocked by your host. Try the other port, or use the API over port 443.
- Nothing arrives and no error appears: Messenger queued the email and no worker is consuming it.
Which should you choose?
| Symfony Mailer (SMTP) | HttpClient (API) | |
|---|---|---|
| Setup | One DSN | A small service |
| Twig templates, Messenger queueing | Built in | Render and queue yourself |
| Safe retries | Not built in | Idempotency keys |
| Delivery events | Usually none | Webhooks per email id |
For most Symfony apps, Mailer over SMTP is the natural fit because the rest of the framework already uses it. Laravel uses the same mailer underneath; see the Laravel guide for its configuration.
Before you send: verify your domain
The address in from() must be on a domain with SPF, DKIM and DMARC records, or receiving servers will filter your mail. Add the domain with your provider and publish the DNS records it gives you. The SPF, DKIM and DMARC guide explains each one.