Symfony命令类调用get方法报错:SwiftMailer发邮件失败(Symfony3)
解决Symfony 3中Command调用SwiftMailer时的"get方法不存在"问题
你遇到的核心问题是Symfony 3的普通Command类没有内置容器访问能力——你当前继承的是基础Command类,但它并没有get()或getContainer()方法,这就是报错的直接原因。下面给你两种可行的解决方案,再补充Gmail SMTP的配置注意事项:
方案1:改用ContainerAwareCommand继承(快速修复)
Symfony 3提供了ContainerAwareCommand类,它继承自Command并内置了容器访问功能,只需要修改类的继承关系即可:
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class CommandMail extends ContainerAwareCommand { 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'); // 现在可以通过容器获取mailer服务 $this->getContainer()->get('mailer')->send($message); $output->writeln('邮件发送成功!'); } }
方案2:使用依赖注入注入Mailer(推荐,符合Symfony最佳实践)
虽然ContainerAwareCommand能快速解决问题,但它在Symfony后续版本中已被弃用。更推荐通过构造函数注入依赖的方式,代码更清晰且易维护:
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Swift_Mailer; class CommandMail extends Command { protected static $defaultName = 'app:send-daily-mail'; private $mailer; // 通过构造函数注入Swift_Mailer服务 public function __construct(Swift_Mailer $mailer) { $this->mailer = $mailer; parent::__construct(); } 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'); // 直接使用注入的mailer实例 $this->mailer->send($message); $output->writeln('邮件发送成功!'); } }
Gmail SMTP配置注意事项
确保你在app/config/config.yml里正确配置了SwiftMailer的Gmail参数:
swiftmailer: transport: smtp host: smtp.gmail.com port: 587 encryption: tls username: 'xxxxxx.xxxxxxx@gmail.com' password: '你的Gmail密码或应用专用密码' spool: { type: memory }
- 如果你的Gmail账号开启了两步验证,不能使用普通密码,需要去Google账号设置中生成一个「应用专用密码」。
- 若未开启两步验证,需在Google账号设置里开启「允许低安全性应用访问」(不过该选项目前已逐步被移除,优先推荐使用应用专用密码)。
内容的提问来源于stack exchange,提问作者Quentin Sutkowski
相关产品推荐
相关产品推荐

