从symfony2中的命令行发送电子邮件

nas*_*asy 28 php console symfony twig

我需要从symfony2中的命令类渲染一个twig模板.

namespace IT\bBundle\Command;

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

class CronCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('send:emails')
            ->setDescription('Envio programado de emails');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $message = \Swift_Message::newInstance()
            ->setSubject('bla bla')
            ->setFrom('x@x.com')
            ->setTo('x@gmail.com')
            ->setCharset('UTF-8')
            ->setContentType('text/html')       
            ->setBody($this->renderView('mainBundle:Email:default.html.twig'));

        $this->getContainer()->get('mailer')->send($message);
        $output->writeln('Enviado!');
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我执行命令时,php app/console send:emails我收到以下错误:

致命错误:调用未定义的方法 IT\bBundle\Command\CronCommand::renderView()

我该如何渲染视图?

Cyp*_*ian 75

这是因为renderView是类Controller的方法.而不是尝试:

$this->getContainer()->get('templating')->render(...);
Run Code Online (Sandbox Code Playgroud)


Eln*_*mov 18

更改

$this->renderView()
Run Code Online (Sandbox Code Playgroud)

$this->getContainer()->get('templating')->render()
Run Code Online (Sandbox Code Playgroud)


dey*_*yvw 9

也许,不完全是你问的问题,但肯定 - 重要.

请记住,如果您想通过Command调用发送电子邮件,则需要flushQueue.

$mailer = $container->get('mailer');
$spool = $mailer->getTransport()->getSpool();
$transport = $container->get('swiftmailer.transport.real');
$spool->flushQueue($transport);
Run Code Online (Sandbox Code Playgroud)