alexbrons/swiftmailer-mailgun-bundle
Install the package:
composer require cspoo/swiftmailer-mailgun-bundle php-http/guzzle5-adapter
Register the bundle (Symfony 4+):
// config/bundles.php
return [
// ...
cspoo\Swiftmailer\MailgunBundle\cspooSwiftmailerMailgunBundle::class => ['all' => true],
];
Configure Mailgun credentials (Symfony 4+):
# config/packages/mailgun.yaml
cspoo_swiftmailer_mailgun:
key: '%env(MAILGUN_API_KEY)%'
domain: '%env(MAILGUN_DOMAIN)%'
Enable Mailgun transport in Swiftmailer:
# config/packages/swiftmailer.yaml
swiftmailer:
transport: 'mailgun'
spool: { type: 'memory' }
Send your first email:
use Swift_Message;
$message = (new Swift_Message('Hello Email'))
->setFrom('noreply@example.com')
->setTo('recipient@example.com')
->setBody('Hello, this is a test email!');
$this->get('mailer')->send($message);
Replace your existing mail transport with Mailgun for transactional emails (e.g., password resets, notifications). Test locally using:
bin/console swiftmailer:email:send --from=test@example.com --to=test@example.com --subject="Test" --body="Hello"
Message Composition: Use Swiftmailer’s fluent API to craft emails with HTML/Plaintext bodies, attachments, and custom headers.
$message = (new Swift_Message('Welcome'))
->setFrom(['noreply@domain.com' => 'Support Team'])
->setTo(['user@example.com' => 'User Name'])
->setBody($this->renderView('emails/welcome.html.twig', ['name' => 'John']))
->addPart($plaintextBody, 'text/plain');
Sending Emails:
Inject the mailer service (autowired in controllers) and call send():
public function sendWelcomeEmail(User $user) {
$message = $this->createWelcomeMessage($user);
$this->mailer->send($message);
}
Batch Processing:
Use Swiftmailer’s BatchSender for bulk emails (e.g., newsletters):
$batch = new Swift_BatchSender($this->mailer, 10); // 10 emails at a time
foreach ($users as $user) {
$batch->send($this->createMessage($user));
}
Environment-Specific Configs:
Override mailgun.yaml in config/packages/mailgun_{env}.yaml for staging/production:
# config/packages/mailgun_prod.yaml
cspoo_swiftmailer_mailgun:
endpoint: 'https://api.mailgun.net'
key: '%env(MAILGUN_PROD_KEY)%'
Event Listeners:
Attach listeners to Swiftmailer events (e.g., SentEvent) for analytics or logging:
// src/EventListener/MailgunLogger.php
public function onSent(SentEvent $event) {
$this->logger->info('Email sent to: ' . $event->getAddress());
}
Testing:
Use Swift_Transport_MemoryTransport in tests to avoid real API calls:
// tests/TestCase.php
protected function getMailer() {
$transport = new Swift_Transport_MemoryTransport();
return new Swift_Mailer($transport);
}
Async Processing: Combine with Symfony Messenger for background email sending:
// src/Message/SendEmailMessage.php
class SendEmailMessage {
public function __construct(private Swift_Message $message) {}
}
// src/MessageHandler/SendEmailHandler.php
public function __invoke(SendEmailMessage $message) {
$this->mailer->send($message->message);
}
API Key Exposure:
.env files to version control. Use env() in PHP or %env() in YAML.messages.create).Spooling Quirks:
spool: { type: memory } sends emails only on kernel.terminate. For immediate sending, use:
spool: null
php artisan cache:clear).HTTP Client Issues:
cspoo_swiftmailer_mailgun:
http_client: 'httplug.client' # Must be a valid service ID
bin/console debug:config cspoo_swiftmailer_mailgun
Rate Limiting:
bin/console swiftmailer:spool:send --dry-run
Domain Verification:
Enable Swiftmailer Debug:
swiftmailer:
debug: '%kernel.debug%'
Logs will appear in var/log/dev.log.
Check Mailgun Webhooks: Configure Mailgun webhooks to debug delivery failures:
# config/packages/mailgun.yaml
cspoo_swiftmailer_mailgun:
webhook_url: 'https://your-app.com/webhook/mailgun'
Validate API Responses:
Use Mailgun\Mailgun::getLastResponse() to inspect raw API responses:
$mailgun = $this->container->get('mailgun.mailgun');
$response = $mailgun->getLastResponse();
Custom Transports: Extend the bundle to support additional Mailgun features (e.g., tracking events):
// src/Mailgun/Transport/CustomTransport.php
class CustomTransport extends \cspoo\Swiftmailer\MailgunBundle\Transport\MailgunTransport {
public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) {
// Add custom logic (e.g., track opens)
parent::send($message, $failedRecipients);
}
}
Override Services:
Replace the default Mailgun\Mailgun service in services.yaml:
services:
mailgun.mailgun:
class: App\Service\CustomMailgun
arguments:
- '%env(MAILGUN_API_KEY)%'
- '%env(MAILGUN_DOMAIN)%'
Add Attachments Dynamically:
Use Swiftmailer’s EmbeddedFile for inline images or Attachment for files:
$message->embed(Swift_Image::fromPath('/path/to/image.png'));
$message->attach(Swift_Attachment::fromPath('/path/to/file.pdf'));
Template Inheritance: Combine with Twig to create reusable email templates:
{# templates/emails/base.html.twig #}
<html>
<body>
{{ block('content') }}
</body>
</html>
{# templates/emails/welcome.html.twig #}
{% extends 'emails/base.html.twig' %}
{% block content %}
<h1>Welcome, {{ name }}!</h1>
{% endblock %}
Batch Emails:
Use Swift_BatchSender to reduce API calls:
$batch = new Swift_BatchSender($this->mailer, 50);
foreach ($recipients as $recipient) {
$batch->send($this->createMessage($recipient));
}
Async Queues: Offload email sending to a queue worker (e.g., Symfony Messenger + Redis):
$this->messageBus->dispatch(new SendEmailMessage($message));
Caching Templates: Pre-render email templates and cache them:
$cachedBody = $this->cache->get('email.welcome', function() use ($user) {
return
How can I help you explore Laravel packages today?