Symfony Mailer is a powerful and flexible library for sending emails in PHP applications, designed to work seamlessly within Symfony projects but also usable as a standalone component. It provides an abstraction layer over various email sending mechanisms, known as 'transports', allowing developers to easily switch between them without changing their application logic.
Key features and concepts of symfony/mailer:
1. Transport Abstraction: Mailer supports numerous transports out of the box, including:
* SMTP: For sending emails via an SMTP server.
* Sendmail: For sending via the local `sendmail` command.
* API-based services: Integrations with popular services like Mailgun, Postmark, SendGrid, Amazon SES, and more, typically using their HTTP APIs for better reliability and deliverability.
* DSN (Data Source Name): A powerful way to configure transports using a single string, e.g., `smtp://user:pass@smtp.example.com:587` or `mailgun+api://KEY@REGION`.
2. Email Objects: Emails are represented by `Symfony\Component\Mime\Email` objects. This object allows you to configure all aspects of an email:
* Sender (`from()`, `sender()`)
* Recipients (`to()`, `cc()`, `bcc()`, `replyTo()`)
* Subject (`subject()`)
* Text content (`text()`)
* HTML content (`html()`)
* Attachments (`addPart()` for `DataPart` or `File`)
* Headers (`addHeader()`, `addTextHeader()`, etc.)
3. Templated Emails: For more complex email layouts, `symfony/mailer` integrates with `symfony/twig-bridge` to offer `Symfony\Bridge\Twig\Mime\TemplatedEmail`. This allows you to render email content (both HTML and plain text) using Twig templates, passing data through a context array.
4. Mailer Service: The core `Symfony\Component\Mailer\Mailer` class orchestrates the sending process. You instantiate it with a configured `Transport` and then call its `send()` method with an `Email` object.
5. Asynchronous Sending: In Symfony applications, Mailer can be integrated with `symfony/messenger` to send emails asynchronously. This offloads the email sending process to a message queue, improving application responsiveness and reliability.
6. Testing: Mailer provides mechanisms for testing email sending without actually dispatching emails, such as a `NullTransport` or a `TestingTransport` that can capture sent emails for assertions.
How it works (Simplified):
1. You define a transport DSN (e.g., in your `.env` file or configuration).
2. Mailer's factory method (`Transport::fromDsn()`) creates the appropriate transport instance.
3. You create an `Email` object, setting its content, recipients, and other details.
4. You pass the `Email` object to the `Mailer` service's `send()` method.
5. The `Mailer` uses the configured `Transport` to dispatch the email.
Example Code
```php
<?php
require 'vendor/autoload.php'; // Ensure Composer autoloader is included
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\File;
// --- Configuration ---
// In a real application, this DSN would typically come from an environment variable (e.m., .env file)
// or Symfony configuration. Replace with your actual SMTP server details or API DSN.
// Examples:
// SMTP: 'smtp://user:pass@smtp.example.com:587'
// Mailgun: 'mailgun+api://YOUR_MAILGUN_API_KEY@YOUR_MAILGUN_REGION'
// SendGrid: 'sendgrid+api://YOUR_SENDGRID_API_KEY'
// Sendmail: 'sendmail://default'
// Null (for testing/development): 'null://default'
$dsn = 'smtp://user:pass@smtp.example.com:587'; // Replace with your actual DSN
// --- Create Transport and Mailer ---
try {
$transport = Transport::fromDsn($dsn);
$mailer = new Mailer($transport);
// --- Create the Email Message ---
$email = (new Email())
->from('sender@example.com') // Replace with your sender email
->to('recipient@example.com', 'Another User <another@example.com>') // Can be one or multiple recipients
// ->cc('cc@example.com') // Carbon Copy
// ->bcc('bcc@example.com') // Blind Carbon Copy
->subject('Important Update from Symfony Mailer!')
->text('This is the plain text version of the email. If you see this, your email client does not support HTML.')
->html('<p>This is the <b>HTML version</b> of the email, sent with Symfony Mailer.</p>
<p>It supports <i>rich content</i> and is highly configurable!</p>');
// --- Add an attachment (optional) ---
// For demonstration, let's create a dummy file
$attachmentContent = 'This is the content of the attached file.';
$attachmentPath = __DIR__ . '/dummy_attachment.txt';
file_put_contents($attachmentPath, $attachmentContent);
if (file_exists($attachmentPath)) {
$email->addPart(new DataPart(
new File($attachmentPath),
'my_document.txt', // Display name of the attachment
'text/plain' // MIME type of the attachment
));
echo "Attachment '{$attachmentPath}' created and added.\n";
}
// --- Send the Email ---
$mailer->send($email);
echo "Email successfully sent (or queued for sending)!\n";
// --- Clean up dummy attachment file ---
if (file_exists($attachmentPath)) {
unlink($attachmentPath);
echo "Dummy attachment file '{$attachmentPath}' removed.\n";
}
} catch (\Exception $e) {
echo "Error sending email: " . $e->getMessage() . "\n";
// You might want to log the full exception stack for debugging
// echo $e->getTraceAsString();
}
// To run this code, ensure you have Symfony Mailer installed via Composer:
// composer require symfony/mailer symfony/mime
// For TemplatedEmail (using Twig), you would also need:
// composer require symfony/twig-bridge twig/twig
```








symfony/mailer