Send a message with Swiftmailer from a symfony command

0

My problem is that I'm trying to send a message from a command in Symfony 2 but it's all errors, this is my code:

$message = $this->mailer
        ->setFrom('[email protected]')
        ->setTo('[email protected]')
        ->setSubject('Subject')
        ->setBody('Body')
        ->attach($xml)
    ;

    $this->mailer()->send($message);

The command class extends from the AbstractCommand which in turn extends from the ContainerAwareCommand, and the abstractCommand has a function to take the containers, and in it I have the following:

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

And this is the error that it gives me when executing my command

  

Notice: Undefined property: Project \ Libraries \ ReportsBundle \ Command \ GenerateXMLCommand :: $ mailer

I would like to be able to be told a way to send messages from a Symfony 2 command.

Greetings. Thanks.

    
asked by Sermanes 22.03.2016 в 09:41
source

1 answer

1
namespace Acme\DemoBundle\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 GreetCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        //Blah Blah configuración
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $mailer = $this->getContainer()->get('mailer');

        $message = $mailer
          ->setFrom('[email protected]')
          ->setTo('[email protected]')
          ->setSubject('Subject')
          ->setBody('Body')
          //No se de donde viene este $xml, pero ahí lo dejo según tu código
          ->attach($xml)
          ;

         $mailer->send($message);
    }
}

You may not be instantiating the mailer of container object in your class correctly (you try to call $ this-> mailer, this you can only do if you previously installed / set them). The example that I leave you is a small mod of the Symfony2 documentation for version 2.0

Note: Version 2.0 is very Deprecated, you should upgrade your version at least until 2.4

link

    
answered by 23.03.2016 в 20:29