如何在不使用命令的情况下从SwiftMailer发送spool。

8

如何在不使用命令的情况下从swiftmailer发送spool?

php app/console swiftmailer:spool:send --env=prod

我需要将这个命令放到一个php文件中,以便服务器管理员可以将其添加到计划任务中。

2个回答

22

这也可以通过如何在控制器中运行Symfony 2运行命令来实现,这样你就不会重复编写代码。对我有用。

services.yml:

services:
    swiftmailer.command.spool_send:
        class: Symfony\Bundle\SwiftmailerBundle\Command\SendEmailCommand
        calls:
            - [ setContainer, ["@service_container"] ]

控制器代码(简化):

$this->get('swiftmailer.command.spool_send')->run(new ArgvInput(array()), new ConsoleOutput());

这绝对是更好的答案。 - Pier-Luc Gendreau
1
是的,这是一种官方的方法 - http://symfony.com/doc/3.2/console/command_in_controller.html - Oleg Abrazhaev

14

只需执行与命令相同的操作即可。从命令Execute()函数中执行:

    $mailer     = $this->getContainer()->get('mailer');
    $transport  = $mailer->getTransport();

    if ($transport instanceof \Swift_Transport_SpoolTransport) {
        $spool = $transport->getSpool();
        if ($spool instanceof \Swift_ConfigurableSpool) {
            $spool->setMessageLimit($input->getOption('message-limit'));
            $spool->setTimeLimit($input->getOption('time-limit'));
        }
        if ($spool instanceof \Swift_FileSpool) {
            if (null !== $input->getOption('recover-timeout')) {
                $spool->recover($input->getOption('recover-timeout'));
            } else {
                $spool->recover();
            }
        }
        $sent = $spool->flushQueue($this->getContainer()->get('swiftmailer.transport.real'));

        $output->writeln(sprintf('sent %s emails', $sent));
    }

您需要删除 $output->... 这一行(也许您可以对 $sent 变量进行一些有用的操作)。此外,这段代码查找两种类型的 spool,如果您的 spool 不是这两种类型之一,则可能不需要所有代码。


运行得非常好 :) 谢谢Carlos - Tom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接