You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SwiftMailer发邮件时,MailController的get方法未定义报错求助

Fixing the "Attempted to call an undefined method named 'get'" Error in SwiftMailer Setup

Hey there, let's sort out this SwiftMailer issue you're running into!

What's causing the error?

The error message tells us your MailController doesn't have a get() method defined. In Symfony, this method is provided by the AbstractController base class—it's used to pull services (like the mailer service you're trying to use) from the service container. Since your controller isn't extending this base class, Symfony can't find the get() method, hence the error.

Solution 1: Extend the AbstractController

This is the quickest fix if you want to keep using the get() method:

  1. First, add the use statement for the base controller at the top of your mailController.php file:
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  1. Update your controller class definition to extend AbstractController:
class MailController extends AbstractController
{
    public function newMail(Mail $mail){ 
        $message = \Swift_Message::newInstance() 
            ->setSubject('Accusé de réception') 
            ->setFrom('hela.mejri@esprit.tn') 
            ->setTo($mail->getEmail()) ; 
        $this->get('mailer')->send($message); 
    }
}

Symfony now recommends dependency injection over using get()—it's more testable, cleaner, and aligns with modern Symfony best practices. Here's how to adjust your code:

  1. Add the use statement for the mailer interface (note: if you're on a newer Symfony version, SwiftMailer is replaced by Symfony Mailer, but the injection logic stays similar):
use Symfony\Component\Mailer\MailerInterface;
// For older SwiftMailer-specific setups:
// use Symfony\Bundle\SwiftmailerBundle\Mailer\SwiftMailer;
  1. Inject the mailer service directly into your newMail method:
class MailController
{
    public function newMail(Mail $mail, MailerInterface $mailer){ 
        $message = \Swift_Message::newInstance() 
            ->setSubject('Accusé de réception') 
            ->setFrom('hela.mejri@esprit.tn') 
            ->setTo($mail->getEmail()) ; 
        $mailer->send($message); 
    }
}

Symfony will automatically pass the mailer service to your method, so you don't need to call $this->get() at all.

内容的提问来源于stack exchange,提问作者Jamel Mustapha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:24:16