vakunenko
vakunenko

Reputation: 11

How to use Swift Mailer in Command

I have this code...

namespace AppBundle\Command;

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

class NotificationCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this->setName('app:notif');
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $message = \Swift_Message::newInstance()
            ->setFrom([
                '[email protected]' => 'Example'
            ])
            ->setTo('[email protected]')
            ->setSubject('Subject')
            ->setBody(
                $this->getContainer()->renderView(
                    'emails/notify.html.twig', [
                        'foo' => 'bar',
                    ]
                ),
                'text/html'
            );

        $this->getContainer()->get('mailer')->send($message);
    }
}

And I get an error in response

Attempted to call an undefined method named "renderView" of class "ContainerV5drzta\appDevDebugProjectContainer".

How do I use Swift Mailer in my Command (Symfony 3.4)?

Upvotes: 0

Views: 311

Answers (1)

MylesK
MylesK

Reputation: 4419

You can dependency inject these services that should solve the problem and it's also the way Symfony is trying to turn towards.

public function __construct(
    EngineInterface $templating,
    \Swift_Mailer $mailer,
) {
    $this->templating = $templating;
    $this->mailer = $mailer;

    parent::__construct();
}

You can now in your execute() render a template like so:

$message = (new \Swift_Message('My message'))
    ->setFrom('[email protected]')
    ->setTo('[email protected]')
    ->setBody($this->templating->render('mytemplate.html.twig'), 'text/html');

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

You can read more about dependency injecting in Symfony here or a more generic article here.

Upvotes: 1

Related Questions