## Getting Started
### Minimal Setup
1. **Installation**:
```bash
composer require donkeycode/mail-bundle
Register the bundle in config/bundles.php (Symfony 4+):
DonkeyCode\MailBundle\DonkeyCodeMailBundle::class => ['all' => true],
Configuration:
Add to config/packages/donkey_code_mail.yaml (Symfony 4+):
donkey_code_mail:
mail_from: 'noreply@example.com'
reply_to: 'contact@example.com'
options:
header_bg: '#2d7cff'
header_txt_color: '#ffffff'
First Use Case:
Create a Twig template at templates/Mails/invoice.html.twig:
{% block subject %}Invoice #{{ invoiceId }}{% endblock %}
{% block body %}
{% embed "@DonkeyCodeMail/Mails/layout.html.twig" %}
{% block title %}Your Invoice{% endblock %}
{% block content %}
<p>Invoice details...</p>
{% endblock %}
{% endembed %}
{% endblock %}
Send the email in a controller:
use DonkeyCode\MailBundle\Mailer;
public function sendInvoice(Mailer $mailer, int $invoiceId)
{
$mailer->createMessage()
->setTemplate('Mails/invoice.html.twig', ['invoiceId' => $invoiceId])
->setTo('customer@example.com')
->send();
}
Dynamic Templates: Use Twig variables to customize emails dynamically:
{% block subject %}Welcome, {{ user.name }}{% endblock %}
{% block body %}
{% embed "@DonkeyCodeMail/Mails/layout.html.twig" %}
{% block content %}
<h1>Hello {{ user.name }}!</h1>
<p>Your account: {{ user.email }}</p>
{% endblock %}
{% endembed %}
{% endblock %}
Pass data via setTemplate():
->setTemplate('Mails/welcome.html.twig', ['user' => $user])
Reusable Layouts:
Extend the default layout (@DonkeyCodeMail/Mails/layout.html.twig) by overriding blocks:
{% extends "@DonkeyCodeMail/Mails/layout.html.twig" %}
{% block footer %}
<p>© {{ year }} Your Company</p>
{% endblock %}
Attachments: Attach files to emails (if supported by SwiftMailer):
->addAttachment('/path/to/file.pdf', 'invoice.pdf')
CC/BCC:
->setCc(['cc@example.com'])
->setBcc(['bcc@example.com'])
Async Sending: Use Symfony’s Messenger component to queue emails for background processing:
$message = $mailer->createMessage()
->setTemplate('Mails/newsletter.html.twig', [])
->setTo($recipient);
$this->messageBus->dispatch($message);
Symfony Forms:
Validate email inputs and pass them directly to setTo():
$form = $this->createForm(ContactType::class);
if ($form->isSubmitted() && $form->isValid()) {
$mailer->createMessage()
->setTemplate('Mails/contact.html.twig', ['contact' => $form->getData()])
->setTo($this->getParameter('contact_email'))
->send();
}
Event Listeners:
Trigger emails on entity events (e.g., postPersist):
// src/EventListener/UserListener.php
public function onUserCreated(UserCreatedEvent $event)
{
$mailer->createMessage()
->setTemplate('Mails/registration.html.twig', ['user' => $event->getUser()])
->setTo($event->getUser()->getEmail())
->send();
}
Testing: Mock the mailer service in PHPUnit:
$mailer = $this->createMock(Mailer::class);
$mailer->expects($this->once())
->method('send')
->willReturn(true);
$this->container->set('donkeycode.mailer', $mailer);
Bundle Registration:
config/bundles.php. The AppKernel.php registration method is deprecated.AppKernel.php includes the bundle in the registerBundles() method.Twig Paths:
templates/Mails/ or @DonkeyCodeMail/Mails/. Misconfigured paths will throw TemplateNotFoundException.@YourBundle/Mails/template.html.twig) for clarity.SwiftMailer Dependency:
ClassNotFoundException.composer require symfony/swiftmailer-bundle
Configuration Overrides:
mail_from) may not persist if not set in config/packages/donkey_code_mail.yaml.Deprecated Methods:
getContainer() method is outdated. Use dependency injection (e.g., constructor injection) instead:
public function __construct(private Mailer $mailer) {}
Email Not Sending:
mailer_transport in .env).# config/packages/swiftmailer.yaml
swiftmailer:
logging: true
Twig Errors:
subject, body, title, content) are defined in your template. Missing blocks may cause silent failures.{{ dump(_context) }} in Twig to inspect variables.Styling Issues:
{% block styles %}
{{ parent() }}
<style>
/* Your custom styles */
</style>
{% endblock %}
Custom Layouts: Override the default layout to match your brand:
{# templates/Mails/layout.html.twig #}
{% extends "@DonkeyCodeMail/Mails/layout.html.twig" %}
{% block header %}
<div style="background: {{ config('donkey_code_mail.options.header_bg') }}">
<img src="{{ asset('images/logo.png') }}" alt="Logo">
</div>
{% endblock %}
Environment-Specific Config: Use Symfony’s parameter bag for environment-specific settings:
# config/packages/donkey_code_mail.yaml
donkey_code_mail:
mail_from: '%env(MAIL_FROM)%'
Performance:
twig:
cache: '%kernel.cache_dir%/twig'
Extensions:
Mailer class to add custom methods:
// src/Service/CustomMailer.php
class CustomMailer extends \DonkeyCode\MailBundle\Mailer
{
public function sendNewsletter(array $recipients, array $data)
{
foreach ($recipients as $email) {
$this->createMessage()
->setTemplate('Mails/newsletter.html.twig', $data)
->setTo($email)
->send();
}
}
}
Register it as a service:
services:
App\Service\CustomMailer:
parent: donkeycode.mailer
Local Testing: Use a local SMTP server (e.g., MailHog) for testing:
# .env
MAILER_TRANSPORT=smtp
MAILER_HOST=mailhog
MAILER_PORT=1025
Fallback for Missing Config:
Handle cases where mail_from or reply_to are null:
$mailer->createMessage()
->setFrom($this->getParameter('default_mail_from') ?? 'no-reply@example.com')
->setTemplate(...)
->send();
Security:
How can I help you explore Laravel packages today?