sending emails from cron tasks in symfony
<p>I am trying to send emails using cron tasks with Symfony , so my question is how would I execute my command with using swiftmailer in my execute function ?Thanks in advance</p>

<p>I want the swiftmailer to be in my execute method,  so I can send emails based on cron tasks</p>

<pre><code>                    $mail = \Swift_Message::newInstance();
                    $mail-&gt;setFrom('from@example.com')
                         -&gt;setTo('to@example.com')
                         -&gt;setSubject('Email subject')
                         -&gt;setBody('email body, can be swift template')

                    $this-&gt;get('mailer')-&gt;send($mail);
</code></pre>

<p>my CronTasksRunCommand</p>

<pre><code>protected function execute(InputInterface $input, OutputInterface $output)
{
    $output-&gt;writeln('&lt;comment&gt;Running Cron Tasks...&lt;/comment&gt;');

    $this-&gt;output = $output;
    $em = $this-&gt;getContainer()-&gt;get('doctrine.orm.entity_manager');
    $crontasks = $em-&gt;getRepository('AppBundle:CronTask')-&gt;findAll();

    foreach ($crontasks as $crontask) {
        // Get the last run time of this task, and calculate when it should run next
        $lastrun = $crontask-&gt;getLastRun() ? $crontask-&gt;getLastRun()-&gt;format('U') : 0;
        $nextrun = $lastrun + $crontask-&gt;getInterval();

        // We must run this task if:
        // * time() is larger or equal to $nextrun
        $run = (time() &gt;= $nextrun);

        if ($run) {
            $output-&gt;writeln(sprintf('Running Cron Task &lt;info&gt;%s&lt;/info&gt;', $crontask));

            // Set $lastrun for this crontask
            $crontask-&gt;setLastRun(new \DateTime());

            try {
                $commands = $crontask-&gt;getCommands();
                foreach ($commands as $command) {
                    $output-&gt;writeln(sprintf('Executing command &lt;comment&gt;%s&lt;/comment&gt;...', $command));

                    // Run the command
                    $this-&gt;runCommand($command);
                }

                $output-&gt;writeln('&lt;info&gt;SUCCESS&lt;/info&gt;');
            } catch (\Exception $e) {
                $output-&gt;writeln('&lt;error&gt;ERROR&lt;/error&gt;');
            }

            // Persist crontask
            $em-&gt;persist($crontask);
        } else {
            $output-&gt;writeln(sprintf('Skipping Cron Task &lt;info&gt;%s&lt;/info&gt;', $crontask));
        }
    }

    // Flush database changes
    $em-&gt;flush();

    $output-&gt;writeln('&lt;comment&gt;Done!&lt;/comment&gt;');
}
</code></pre>