Command类上的Symfony邮件-获取名为“ get”的未定义方法

时间:2019-02-27 14:03:43

标签: symfony email cron command

我尝试通过symfony命令发送邮件(swiftmail)。 这是我的代码:

class CommandMail extends Command
{
    protected static $defaultName = 'app:send-daily-mail';

    protected function configure() {
        $this
            ->setDescription('Send automatic reminders mail everyday.')

            ->setHelp('This command allows you to send automatic reminder mail to Rhys, everyday...');
    }

    protected function execute(InputInterface $input, OutputInterface $output) {
        $message = (new \Swift_Message('test auto mail cron 12 24 TEST'))
                    ->setFrom('xxxxxx.xxxxxxx@gmail.com')
                    ->setTo('wwwww.wwwwwww@gmail.com')
                    ->setBody('test body');

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

我遇到以下错误:

  

在CommandMail.php第54行中:                                                                                                                                                                                           尝试调用类的名为“ get”的未定义方法   “ AppBundle \ Command \ CommandMail”。
  您的意思是打电话给“ getAliases”,“ getApplication”,   “ getDefaultName”,“ getDefinition”,“ getDescription”,“ getHelp”,   “ getHelper”,“ getHelperSet”,“ getName”,“ getNativeDefin ition”,   “ getProcessedHelp”,“ getSynopsis”还是“ getUsages”?

我尝试了很多方法(getContainer()即其他方法),但是没有任何效果。

感谢您的帮助!

(Symfony 3,SMTP gmail)

1 个答案:

答案 0 :(得分:3)

如果您正在使用Symfony 4,请通过构造函数注入依赖项:

private $swiftMailerService;

public function __construct(\Swift_Mailer $swiftMailerService)
{
    parent::__construct();
    $this->swiftMailerService = $swiftMailerService;
}

protected function execute(InputInterface $input, OutputInterface $output) {
    $message = (new \Swift_Message('test auto mail cron 12 24 TEST'))
                ->setFrom('xxxxxx.xxxxxxx@gmail.com')
                ->setTo('wwwww.wwwwwww@gmail.com')
                ->setBody('test body');

    $this->swiftMailerService->send($message);
}