Skip to content
Advertisement

Use the symfony/mailer component without the symfony framework

I am working on a project that doesn’t use any framework and I would like to use Symfony Mailer component to handle sending emails.

The installation part (composer require) was well handled and everything is included in my code without any error. However, I still have a problem : the documentation of the component seems to be written only for using it with the symfony framework. Indeed, it is refering to autoloaded config files that o bviously don’t exist in my app.

This implementation seems to be very tricky and I was wondering if any of you guys already faced the same problem and what solution you came up with?

Advertisement

Answer

Your question made me wonder too how it is easy to send mail only with the mailer component.

So I created a new project from scratch and tried the simplest possible version following the mailer component documentation.

use SymfonyComponentMailerMailer;
use SymfonyComponentMailerTransport;
use SymfonyComponentMimeEmail;

class MyMailer
{
    // googleDns format is gmail+smtp://USERNAME:PASSWORD@default
    public function __construct(private string $googleDsn)
    {
    }

    public function send()
    {
        $template = file_get_contents('https://raw.githubusercontent.com/leemunroe/responsive-html-email-template/master/email.html');

        $transport = Transport::fromDsn($this->googleDsn);
        $mailer = new Mailer($transport);

        $email = (new Email())
            ->from('mygmail@address.com')
            ->to('thedelivery@gmail.com')
            ->subject('Time for Symfony Mailer!')
            ->html($template);

        $mailer->send($email);
    }
}

And I successfully received my mail. I send my mail with gmail, for your information. Transport class should do the sending job for you, but if not you can have a look to inside vendor/symfony/mailer/Transport folder

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement