【问题标题】:sending emails from cron tasks in symfony在 symfony 中从 cron 任务发送电子邮件
【发布时间】:2016-08-04 22:59:36
【问题描述】:

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

我希望 swiftmailer 出现在我的 execute 方法中,这样我就可以根据 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>');
}

【问题讨论】:

    标签: php symfony email cron swiftmailer


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-25
      • 2012-01-29
      • 2014-06-05
      • 1970-01-01
      • 2015-04-16
      • 2022-08-15
      • 2011-04-26
      • 2018-11-15
      相关资源
      最近更新 更多