从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>');
}

如果您的Command类扩展了ContainerwareCommand类,那么只需替换

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

带有

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