Slim Framework and Swift Mailer

Swift Mailer is a great open source library to accompany the Slim Framework. Here is a quick run down of how I currently integrate Swift Mailer into my apps that use the Slim Framework.

Including the Library

I use composer within my app so for me it was simple as adding a single like to my composer.json file.

    "require": {
        "slim/slim": "*",
        "illuminate/database": "*",
        "swiftmailer/swiftmailer": "@stable"

If you’re not using Composer look to the Swift Mailer Docs for information on how to manually download and set it up.

Initializing Swift Mailer

In my index.php file where I initialize other things such as Slim itself I in do the following to initialize Swift Mailer.

// Create Transport
$transport = Swift_MailTransport::newInstance();

// Create Mailer with our Transport.
$mailer = Swift_Mailer::newInstance($transport);

Depending on how you plan on sending email (SMTP login, PHP Mail, SendMail), you will need to adjust the transport method to fit your needs. Refer to the Sending Messages Doc for more information on other options. In the example above I’m using the default Mail method in PHP as I have it already configured.

Sending Messages

We are now ready to send emails! Below is a simple example of how to send a HTML email within a route method.

// Notice we pass along that $mailer we created in index.php
$app->get('/test-email', function() use ($app, $mailer){
    // Here I'm fetching my email template from my template directory.
    $welcomeEmail = $app->view->fetch('emails/welcome.php');
    // Setting all needed info and passing in my email template.
    $message = Swift_Message::newInstance('Wonderful Subject')
                    ->setFrom(array('' => 'Me'))
                    ->setTo(array('' => 'You'))

    // Send the message
    $results = $mailer->send($message);
    // Print the results, 1 = message sent!