Symfony4中Swift_Mailer类不存在错误排查求助
Hey Sébastien, let's work through why your SwiftMailer setup in Symfony 4 is throwing that error and what to check to fix it:
1. Fix the Installation Mix-Up
First off, a critical point: running composer require mailer in Symfony 4+ installs the Symfony Mailer component (the modern, official replacement for SwiftMailer), not the legacy SwiftMailer library itself. To use SwiftMailer specifically, you need to install its dedicated bundle:
composer require swiftmailer-bundle
After installing this, re-run ./bin/console debug:config framework—you should now see SwiftMailer-related configuration entries.
2. Verify Your .env Configuration Format
SwiftMailer's MAILER_URL syntax differs slightly from Symfony Mailer. For Gmail, use this correct format:
MAILER_URL=smtp://smtp.gmail.com:587?encryption=tls&username=myaccount@gmail.com&password=mypassword
Note: If your Gmail account has 2FA enabled, you'll need to use an app-specific password instead of your regular account password.
3. Validate Dependency Injection & Clear Cache
If you've installed the bundle but still get the Swift_Mailer class not found error:
- Double-check that you're either using the full namespace
\Swift_Mailer(like you did in your code) or have added the use statement at the top of your controller:use Swift_Mailer; - Clear Symfony's cache to refresh service registrations—this is often overlooked:
./bin/console cache:clear --env=dev
4. Ensure the Bundle is Registered in bundles.php
Open config/bundles.php and confirm the SwiftMailer Bundle is listed:
return [ // ... other registered bundles Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle::class => ['all' => true], ];
If it's missing, add that line manually, then clear the cache again.
5. Optional: Switch to Symfony Mailer (Recommended)
Since you initially ran composer require mailer, you might want to switch to Symfony Mailer instead—it's the official, supported solution for Symfony 4+. Here's how to adjust your code:
First, update the controller with the new Mailer components:
use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Mime\Email; /** * @Route("/testmail", name="testmail") */ public function mailAction(MailerInterface $mailer) { $email = (new Email()) ->from('test@gmail.com') ->to('test@gmail.com') ->subject('Hello Email') ->text('Test content'); $mailer->send($email); return $this->redirectToRoute('rotta'); }
Then update your .env configuration to use the Symfony Mailer DSN format:
MAILER_DSN=smtp://myaccount@gmail.com:mypassword@smtp.gmail.com:587
Again, use an app-specific password if you have 2FA enabled.
内容的提问来源于stack exchange,提问作者Sébastien Grognuz

