Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

I'm trying to send an email with dynamic SMTP connection parameters. These parameters will be retrieved from a DB. So specifying the parameters in .env file (e.g.: MAILER_DSN=smtp://user:pass@smtp.example.com:port) as explained in official docs or defining multiples transports in .yaml files don't fit my requirements.

How could I send an email defining the mailer transport programmatically? For example, I'd like to make:

// 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);
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

There are some considerations to take into account when running the program:

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

I hope it will prevent someone from wasting their time!

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!