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

时间:2022-06-01 21:24:07

I need to render a twig template from a command class in symfony2.

我需要从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!');
    }
}

But when I execute the command php app/console send:emails I get the following error:

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

Fatal error: Call to undefined method IT\bBundle\Command\CronCommand::renderView()

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

How can I render the view?

我该如何渲染视图?

3 个解决方案

#1


75  

It's because renderView is method of class Controller. Instead of that try:

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

$this->getContainer()->get('templating')->render(...);

#2


18  

Change

更改

$this->renderView()

to

$this->getContainer()->get('templating')->render()

#3


8  

Maybe, not exactly the question you ask, but for sure - important.

也许,不是你提出的问题,但肯定 - 重要。

Please, do remember that if you want to send emails via Command call, you need to flushQueue.

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

$mailer = $container->get('mailer');
$spool = $mailer->getTransport()->getSpool();
$transport = $container->get('swiftmailer.transport.real');
$spool->flushQueue($transport);

#1


75  

It's because renderView is method of class Controller. Instead of that try:

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

$this->getContainer()->get('templating')->render(...);

#2


18  

Change

更改

$this->renderView()

to

$this->getContainer()->get('templating')->render()

#3


8  

Maybe, not exactly the question you ask, but for sure - important.

也许,不是你提出的问题,但肯定 - 重要。

Please, do remember that if you want to send emails via Command call, you need to flushQueue.

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

$mailer = $container->get('mailer');
$spool = $mailer->getTransport()->getSpool();
$transport = $container->get('swiftmailer.transport.real');
$spool->flushQueue($transport);