3

我正在尝试发送带有动态 SMTP 连接参数的电子邮件。这些参数将从数据库中检索。因此,按照官方文档中的说明在文件中指定参数.env(例如MAILER_DSN=smtp://user:pass@smtp.example.com:port:)或在文件中定义多重传输不符合我的要求。.yaml

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

// 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);
4

1 回答 1

1

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

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);

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

于 2021-07-14T13:59:15.553 回答