Laravel 9.x new Symphony Mailer Transport dynamic change

1.6k views Asked by At

Before Laravel switched to Symfony Mailer I was able to check custom SMTP server response the following way:

try {
            $transport = new Swift_SmtpTransport($request->smtp_server, $request->smtp_port, $request->secure_connection);
            $transport->setUsername($request->smtp_username);
            $transport->setPassword($request->smtp_password);
            $mailer = new Swift_Mailer($transport);
            $mailer->getTransport()->start();
            return array(
                'success' => true,
                'statusCode' => 200,
                'message' => 'Success.'
            );
        } catch (Swift_TransportException $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 500);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 500);
        }

I am currently struggling to figure out how exactly to set the DSN(apparently this is the way to go) configuration and execute a transport connection test. I have been searching around for some documentation but was unable to find anything specific.

1

There are 1 answers

0
Tim Ramsey On

I too struggled with this issue. For the time being, you can send an actual email and catch the error if it does not send like below. The issue is that Symfony transport does not have start() and stop() methods like Swift Mailer did. I added the following code in a validator closure to not allow a user to save SMTP records unless the records were valid.

try{
    $transport_factory = new \Symfony\Component\Mailer\Transport\Smtp\EsmtpTransportFactory;
    $transport = $transport_factory->create(new \Symfony\Component\Mailer\Transport\Dsn(
        !empty(request()->input('mail_encryption')) && request()->input('mail_encryption') === 'tls' ? ((request()->input('mail_port') == 465) ? 'smtps' : 'smtp') : '',
        request()->input('mail_host'),
        request()->input('mail_username'),
        request()->input('mail_password'),
        request()->input('mail_port')
    ));
    $mailer = new \Symfony\Component\Mailer\Mailer($transport);
    $email = (new \Symfony\Component\Mime\Email())
        ->from('[email protected]')
        ->to($user->email)
        ->subject('Test Email')
        ->text("Email Test was Successful");
    $mailer->send($email);
} catch (\Symfony\Component\Mailer\Exception\TransportException $e) {
    $fail($e->getMessage());
} catch (\Exception $e) {
    $fail($e->getMessage());
}