Simple wrapper around Swiftmailer.

v2.1.1 2014-09-05 12:58 UTC


A simple wrapper around Swiftmailer.


All of my components require PHP >= 5.4.


Use Composer to install: composer require ts/mailer:~2.1

Basic usage

use TS\Mailer\Mailer;

// Instantiate the mailer
$mailer = new Mailer;

// Create a message
$message = $mailer->createMessage();

// Set the important headers
$message->setSubject('Hello there');
$message->setBody(/* body contents */);

// Send the message
$sentCount = $mailer->send($message);

if ($sentCount > 0) {
    echo "Mail successfully sent to $sentCount recipients.\n";

// Handle failed recipients for the last message
$failedRecipients = $mailer->getFailedRecipients();

if ( ! empty($failedRecipients)) {
    foreach ($failedRecipients as $recipient) {
        echo "Recipient $recipient did not get the mail.\n";

Advanced usage

There is a more complicated way of instantiating the mailer, allowing you to fully leverage the power of runtime extension through events and Swiftmailer's different transport mechanisms:

use Swift_MailTransport;
use TS\Common\Event\EventDispatcher;
use TS\Mailer\Mailer;

// Instantiate the mailer
$mailer = new Mailer(
    new EventDispatcher, // This might be your global instance, retrieved from your service/DI container
    Swift_MailTransport::newInstance() // Or any other transport instance you want to use

// Proceed like you normally would ...

Addresses can also be defined in various ways:

use TS\Mailer\Address;
use TS\Mailer\AddressCollection;

// Create message object like described above

// Singular addresses
$message->setTo(new Address('recipient@tld.com'));

// Multiple addresses
$addresses = ['recipient1@tld.com', 'recipient2@tld.com'];

$coll = AddressCollection::fromArray($addresses);

// Do something with the collection before adding it

String and array addresses are converted to address / address collection objects internally to allow filtering and removal through the event system, if necessary.

Using the event system

You can intercept or influence most parts of the mailer's lifecycle by utilizing your favorite event dispatcher. By default Symfony's EventDispatcher Component is used.

The events (and their names) triggered by the mailer are described inside the TS\Mailer\MailerEvents class:

  • AFTER_SEND: Dispatched after a message has been sent.
  • BEFORE_SEND: Dispatched before a message is sent.
  • INIT: Dispatched right in the mailer's constructor.
  • MESSAGE_CREATE: Dispatched when a new message is created.
  • TRANSPORT_SEND: Dispatched when a message is passed to a custom Swift_Transport's send() method.