Menü schliessen
Created: November 5th 2024
Last updated: November 12th 2024
Categories: Common Web Development,  Laravel,  Php
Author: Tim Fürer

Laravel: How to Test SMTP Credentials

Tags:  guide,  Laravel,  PHP,  SMTP
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Laravel doesn't provide the functionality to directly check SMTP credentials out of the box, so one has to get creative. Having already solved this problem, I'm providing my solution here for those who are interested or have use for it. The code is tested to work with Laravel 11.

<?php

use Exception;
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
use Symfony\Component\Mailer\Transport\Smtp\Stream\SocketStream;

function test_smtp_credentials(
    string $host,
    int $port,
    string $username,
    string $password,
    ?bool $tls = null,
) {
    if (empty($host) || empty($port) || empty($username) || empty($password)) {
        return [
            'success' => false,
            'message' => 'SMTP credentials are missing or incomplete',
        ];
    }

    try {
        $stream = new SocketStream();

        $stream->setTimeout(3); // raise this if you expect a slow server

        $transport = new EsmtpTransport(
            $host,
            $port,
            $tls,
            null,
            null,
            $stream,
        );

        $transport->setUsername($username);
        $transport->setPassword($password);

        $transport->start();

        $transport->stop();

        return [
            'success' => true,
            'message' => 'SMTP credentials are correct and server is up',
        ];
    }
    catch (Exception $e) {
        return [
            'success' => false,
            'message' => $e->getMessage(),
        ];
    }

    return [
        'success' => false,
        'message' => 'Unknown error',
    ];
}

?>

Example of Usage

<?php

$result = test_smtp_credentials(
    'mail.example.com',
    465,
    'username',
    'password',
    true,
);

$success = $result['success']; // true if successful, otherwise false
$message = $result['message']; // feedback message

?>