从 symfony 中的 cron 任务发送电子邮件

sending emails from cron tasks in symfony

我正在尝试使用 Symfony 的 cron 任务发送电子邮件,所以我的问题是如何在我的执行函数中使用 swiftmailer 来执行我的命令?提前致谢

我希望 swiftmailer 在我的执行方法中,这样我就可以根据 cron 任务发送电子邮件

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

                    $this->get('mailer')->send($mail);

我的 CronTasksRunCommand

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

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

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

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

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

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

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

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

                $output->writeln('<info>SUCCESS</info>');
            } catch (\Exception $e) {
                $output->writeln('<error>ERROR</error>');
            }

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

    // Flush database changes
    $em->flush();

    $output->writeln('<comment>Done!</comment>');
}

如果您的命令 class 扩展了 ContainerAwareCommand class,那么只需替换

$this->get('mailer')->send($mail);

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