如何使用动态连接参数使用 Symfony Mailer 发送邮件?

How to send mail with Symfony Mailer using dynamic connection parameters?

我正在尝试发送带有动态 SMTP 连接参数的电子邮件。这些参数将从数据库中检索。因此,在 .env 文件中指定参数(例如:MAILER_DSN=smtp://user:pass@smtp.example.com:port)在 .yaml 文件中指定 as explained in official docs or defining multiples transports 不符合我的要求。

如何以编程方式发送定义邮件传输的电子邮件?例如,我想做:

// I'd like to define $customMailer with some data retrieved from DB

$email = (new TemplatedEmail())
    ->from(new Address('example-from@example.com', 'Example'))
    ->to('example-to@example.com')
    ->subject('Subject')
    ->htmlTemplate('emails/my-template.html.twig')
    ->context([]);

$customMailer->send($email);

程序运行时需要考虑一些注意事项:

use Symfony\Bridge\Twig\Mime\BodyRenderer;
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mime\Address;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;

// In my case this data is extracted from the DB
$user = 'example@gmail.com';
$pass = 'my-password';
$server = 'smtp.gmail.com';
$port = '465';

// Generate connection configuration
$dsn = "smtp://" . $user . ":" . $pass . "@" . $server . ":" . $port;
$transport = Transport::fromDsn($dsn);
$customMailer = new Mailer($transport);

// Generates the email
$email = (new TemplatedEmail())
    ->from(new Address('example-from@example.com', 'Example'))
    ->to('example-to@example.com')
    ->subject('Subject')
    ->htmlTemplate('emails/my-template.html.twig')
    ->context([]);

// IMPORTANT: as you are using a customized mailer instance, you have to make the following
// configuration as indicated in https://github.com/symfony/symfony/issues/35990.
$loader = new FilesystemLoader('../templates/');
$twigEnv = new Environment($loader);
$twigBodyRenderer = new BodyRenderer($twigEnv);
$twigBodyRenderer->render($email);

// Sends the email
$customMailer->send($email);

我希望它能防止有人浪费他们的时间!