Installation
composer require apacz/mail-bundle
Add to AppKernel.php (Symfony 3.3):
new Apacz\MailBundle\ApaczMailBundle(),
Configuration
Define mail settings in config/packages/apacz_mail.yaml:
apacz_mail:
from_email: 'noreply@example.com'
from_name: 'Your App'
transport: '%env(MAILER_DSN)%' # e.g., 'smtp://user:pass@smtp.example.com:587'
First Use Case Send a basic email via a Service:
use Apacz\MailBundle\Mailer\MailerService;
class UserMailer {
private $mailer;
public function __construct(MailerService $mailer) {
$this->mailer = $mailer;
}
public function sendWelcomeEmail($to, $name) {
$this->mailer->send(
'emails/welcome.twig', // Twig template
['name' => $name], // Data
$to,
'Welcome to Our App' // Subject
);
}
}
Twig Templates
templates/emails/ (e.g., welcome.twig).$mailer->send('emails/welcome.twig', $data).{{ app.name }} for dynamic app context.Attachments
$this->mailer->send(
'emails/invoice.twig',
['total' => 99.99],
'client@example.com',
'Your Invoice',
['attachments' => ['/path/to/invoice.pdf']]
);
Async Sending (Queue)
MailSentEvent) and listen for it:// Event subscriber
public function onMailSent(MailSentEvent $event) {
$this->dispatcher->dispatch(new SendMailJob($event->getMessage()));
}
Dynamic Recipients
$recipients = ['user1@example.com', 'user2@example.com'];
$this->mailer->sendToMultiple(
'emails/newsletter.twig',
['content' => 'Hello!'],
$recipients,
'Monthly Newsletter'
);
Apacz\MailBundle\Form\Type\EmailType.Apacz\MailBundle\Validator\Constraints\ValidEmail for custom rules.MailerService in PHPUnit:
$mailer = $this->createMock(MailerService::class);
$mailer->expects($this->once())->method('send');
Template Paths
TemplateNotFoundException if emails/ is missing or misconfigured.twig.paths in config/packages/twig.yaml includes templates/.Transport Configuration
transport is invalid.MailerService exceptions:
try {
$this->mailer->send(...);
} catch (\Swift_TransportException $e) {
\Log::error('Mail transport error: ' . $e->getMessage());
}
Character Encoding
config/packages/apacz_mail.yaml:
apacz_mail:
charset: 'UTF-8'
Enable SwiftMailer Debug:
# config/packages/swiftmailer.yaml
swiftmailer:
debug: '%kernel.debug%'
Check logs for raw email content in var/log/dev.log.
Inspect Sent Emails:
Use Symfony’s SwiftMailer\Transport\NullTransport for testing:
apacz_mail:
transport: 'null://localhost' # Discards emails
Custom Mailers
Extend Apacz\MailBundle\Mailer\AbstractMailer for domain-specific logic:
class CustomMailer extends AbstractMailer {
protected function getDefaultFrom() {
return 'custom@domain.com';
}
}
Events
Listen for mail.sent or mail.failed events to log/analyze:
// src/EventListener/MailListener.php
public static function getSubscribedEvents() {
return [
'mail.sent' => 'onMailSent',
'mail.failed' => 'onMailFailed',
];
}
Override Templates
Use Symfony’s template inheritance to modify default templates (e.g., base_email.html.twig).
How can I help you explore Laravel packages today?