'Laravel 9 dynamic Email configurations
I am coming to you with a problem to which I couldn't find a solution on google after hours of googling.
I want to be able to send emails by using different SMTP email configurations which I can add or change at runtime. I am building a website which hosts a lot of projects for a lot of clients and we need be able to send emails on their behalf. I know I can set up different configurations in the .env file but that solution is not good enough because I want to keep the configurations in the database where they can be easily queried/updated etc.
One solution is to use this method from this tutorial. It uses Swift mailer to make a method which returns a new mailer object but this doesn't seem to work in Laravel 9. Apparently Swift mailer is no longer maintained and has been succeeded by Symfony Mailer. Unfortunately I couldn't find a way to use the new Symfony Mailer in the way that I just described, although I'd certainly prefer it if I could get it working.
I wonder if it's possible to use that same method with Symfony Mailer? Here's the error that I get when I use the same code as in the tutorial:
Class "Swift_SmtpTransport" not found
I added the class to the namespace and I also changed the syntax from new Swift_SmtpTransport to \Swift_SmtpTransport::newInstance but that did not resolve the error.
If anyone has any ideas/suggestions then I would highly appreciate it! I really did not expect such a simple thing to be so difficult.
Solution 1:[1]
Laravel 9.x is using symfony/mailer that might cause this conflict. Instead, you can use the mailer() option to change the mail driver on the fly.
Mail::mailer('postmark')
->to($request->user())
->send(new OrderShipped($order));
You can find the details on the documentation.
Updated
I checked the symfony/mailer documentation and i guess this is what you want. You can build your own transport on the fly with dynamic SMTP details as well.
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Email;
$transport = Transport::fromDsn('smtp://localhost');
$mailer = new Mailer($transport);
$email = (new Email())
->from('[email protected]')
->to('[email protected]')
//->cc('[email protected]')
//->bcc('[email protected]')
//->replyTo('[email protected]')
//->priority(Email::PRIORITY_HIGH)
->subject('Time for Symfony Mailer!')
->text('Sending emails is fun again!')
->html('<p>See Twig integration for better HTML integration!</p>');
$mailer->send($email);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
