Installation:
composer require appventus/swiftmailerdbbundle:dev-master
Add to AppKernel.php:
new AppVentus\SwiftMailerDBBundle\AppVentusSwiftMailerDBBundle(),
Configure config.yml:
white_october_swift_mailer_db:
entity_class: App\Entity\MailMessage
swiftmailer:
spool:
type: db
Create a Doctrine Entity:
Extend EmailInterface and define a status field (e.g., sent, queued):
use AppVentus\SwiftMailerDBBundle\Model\EmailInterface;
#[ORM\Entity]
class MailMessage implements EmailInterface
{
#[ORM\Column(type: 'string', length: 255)]
private $status;
}
First Use Case: Send an email via SwiftMailer (e.g., in a controller):
$message = (new \Swift_Message('Hello'))
->setFrom('from@example.com')
->setTo('to@example.com')
->setBody('Test email');
$this->get('mailer')->send($message);
The email will now be stored in your database (check MailMessage table).
Database Spooling:
MailMessage) before sending.SMS Support (Limited):
recipientPhone, smsBody) and manually handle sending via a gateway (e.g., Twilio).Queue Processing:
php bin/console swiftmailer:spool:send --env=prod
Entity Customization:
EmailInterface to add custom fields:
#[ORM\Column(type: 'datetime', nullable: true)]
private $sentAt;
#[ORM\Column(type: 'string', length: 255, nullable: true)]
private $trackingId;
SwiftMailer Integration:
SwiftMailer service directly:
$mailer = $this->get('mailer');
$mailer->send($message); // Spooled to DB.
Bulk Sending:
$em = $this->getDoctrine()->getManager();
$emails = $em->getRepository(MailMessage::class)
->findBy(['status' => 'queued'], ['createdAt' => 'ASC'], 50);
foreach ($emails as $email) {
$swiftMessage = $this->convertEntityToSwiftMessage($email);
$this->get('mailer')->send($swiftMessage);
$email->setStatus('sent');
$em->flush();
}
Event Listeners:
swiftmailer.send events to log or modify emails:
// src/EventListener/SwiftMailerListener.php
public function onSend(SendEvent $event)
{
$message = $event->getMessage();
// Custom logic (e.g., add headers, validate recipients).
}
Register in services.yml:
services:
App\EventListener\SwiftMailerListener:
tags:
- { name: kernel.event_listener, event: swiftmailer.send, method: onSend }
Testing:
$this->container->set('swiftmailer.transport.real', $this->createMock(SpoolTransport::class));
$this->assertCount(1, $this->getDoctrine()->getRepository(MailMessage::class)->findAll());
Deprecated Bundle:
SMS Support Ambiguity:
SmsGateway) and store SMS records in a parallel entity.Entity Requirements:
status field is mandatory but not enforced by the bundle.#[Assert\NotBlank]
#[ORM\Column(type: 'string', length: 255)]
private $status;
Spool Processing:
swiftmailer:spool:send command may fail silently if the spool is misconfigured.type: db setting in config.yml.Performance:
Check the Spool:
MailMessage table to verify emails are stored:
SELECT * FROM mail_message WHERE status = 'queued';
Enable SwiftMailer Debug:
config.yml:
swiftmailer:
debug: true
Doctrine Events:
prePersist/preUpdate to debug entity changes:
$em->getEventManager()->addEventListener(
[ORM\Events::prePersist, ORM\Events::preUpdate],
function ($event) {
error_log('MailMessage change:', $event->getEntity());
}
);
Custom Spooler:
DBTransport class to add features (e.g., soft deletes):
class CustomDBTransport extends DBTransport
{
public function send(Swift_Message $message, &$failedRecipients = null)
{
// Add custom logic (e.g., rate limiting).
parent::send($message, $failedRecipients);
}
}
services.yml:
services:
swiftmailer.transport.db:
class: App\SwiftMailer\CustomDBTransport
arguments: ['@doctrine.orm.entity_manager']
tags:
- { name: swiftmailer.transport }
Add Retry Logic:
#[ORM\Column(type: 'integer', nullable: true)]
private $failedAttempts;
#[ORM\Column(type: 'datetime', nullable: true)]
private $lastFailure;
Laravel Adaptation:
SwiftMailerBundle with Laravel’s swiftmailer package.// app/Providers/AppServiceProvider.php
public function register()
{
$this->app->bind(
Swift_Transport::class,
function () {
return new CustomDBTransport(
app('db')->connection()->getDoctrineSchemaManager()
);
}
);
}
How can I help you explore Laravel packages today?