Dienstag, 18. September 2012

symfony 2.1, Commands and Swiftmailer memory spooling

Working with symfony 2.1 for a while now I can say I really enjoy it. Composer is awesome and the new profiler bar is also very nice. I don't use forms that much so I cannot say anything about the new form component.

One problem which took me some time till I figured it out regards the sending of emails within a command when memory spooling is configured for swiftmailer. It just doesn't sent any mails! The reason is very simple once you look in the right direction: Memory spooling means the emails get sent on the kernel terminate event, which never happens when a command is executed. The issue is discussed on github.


The solution is also simple: Either change the configuration to file spooling or no spooling at all (maybe in a special environment which is then used to execute the commands) or sent all spooled mails within your command. Here is some code how this can be achieved (most of the example is copied from \Symfony\Bundle\SwiftmailerBundle\Command\SendEmailCommand):

<?php

namespace Acme\TestBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class EmailCommand extends ContainerAwareCommand
{
    // ..

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Do your stuff, queuing emails and such

        // And right before you are done, sent the emails

        $container = $this->getContainer();
        $mailer = $container->get('mailer');
        $spool = $mailer->getTransport()->getSpool();

        $transport = $container->get('swiftmailer.transport.real');

        $spool->flushQueue($transport);
    }



I ended up using the file spooling, mostly because I will end up using it anyway for all emails triggered by user actions and because I don't like this kind of code inside my commands.

Keine Kommentare:

Kommentar veröffentlichen