Search code examples
phpsymfonysymfony-mailer

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:[email protected]: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('[email protected]', 'Example'))
    ->to('[email protected]')
    ->subject('Subject')
    ->htmlTemplate('emails/my-template.html.twig')
    ->context([]);

$customMailer->send($email);

Solution

  • 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 = '[email protected]';
    $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('[email protected]', 'Example'))
        ->to('[email protected]')
        ->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);