Modern Laravel web applications rely on email delivery for critical user workflows, including account verification, password resets, order receipts, invoice notifications, and background alert notifications. Out of the box, attempting to send unauthenticated emails often leads to deliverability failures, where messages are rejected or filtered into spam folders by providers like Google Gmail, Yahoo Mail, and Microsoft Outlook.

Configuring SMTP (Simple Mail Transfer Protocol) in Laravel ensures that all transactional emails are securely routed through an authenticated mail server with SSL/TLS encryption, verified sender identity, and cryptographic DKIM signing.

In this step-by-step tutorial, you will learn how to configure SMTP credentials in Laravel’s .env file, clear configuration caches, test email dispatch using Artisan Tinker and Mailable classes, and optimize performance using asynchronous background Queues.


Prerequisites


Step-by-Step Guide: How to Set Up SMTP in Laravel

Step 1: Open Your Laravel Environment Configuration (.env)

You can edit your .env file directly through DirectAdmin File Manager or via the Terminal / SSH:

  1. Via File Manager: In DirectAdmin, go to System Info & Files > File Manager, navigate to your Laravel root directory (e.g. /home/username/domains/domain.com/laravel/), right-click .env, and select Edit.
  2. Via SSH / Terminal: Connect to your server and open the file with nano:
    nano /home/username/domains/domain.com/laravel/.env

Step 2: Configure SMTP Environment Variables

Locate the MAIL_ configuration keys in your .env file and update them with your custom domain SMTP credentials:

Option A: Secure SSL / TLS on Port 465 (Recommended)

MAIL_MAILER=smtp
MAIL_HOST=mail.domain.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD="YourStrongEmailPasswordHere"
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS="[email protected]"
MAIL_FROM_NAME="${APP_NAME}"

Option B: TLS / STARTTLS on Port 587

MAIL_MAILER=smtp
MAIL_HOST=mail.domain.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD="YourStrongEmailPasswordHere"
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="[email protected]"
MAIL_FROM_NAME="${APP_NAME}"
Variable Description Example Value
MAIL_MAILER The mail transport driver to use. smtp
MAIL_HOST Hostname of your outgoing mail server. mail.domain.com
MAIL_PORT The SMTP port for secure connections. 465 (for SSL) or 587 (for TLS)
MAIL_USERNAME Your full email address created in DirectAdmin. [email protected]
MAIL_PASSWORD The password for your email mailbox. Wrap in double quotes if it contains symbols. "YourPassword"
MAIL_ENCRYPTION Security protocol. ssl or tls
MAIL_FROM_ADDRESS Default sender email address on all outgoing emails. [email protected]
MAIL_FROM_NAME Default sender name displayed in the recipient's inbox. "${APP_NAME}"

Step 3: Clear and Rebuild Laravel Configuration Cache

Laravel aggressively caches configuration files for high performance. Whenever you modify the .env file, you must clear and rebuild the configuration cache for changes to take effect:

php artisan config:clear
php artisan cache:clear
php artisan config:cache

Step 4: Test SMTP Delivery with Artisan Tinker

You can quickly verify that your SMTP connection is functioning properly without writing custom controller code by using Artisan Tinker:

  1. In your terminal, start the interactive Tinker REPL:
    php artisan tinker
  2. Run the following one-line test command (replace with your personal email address):
    Mail::raw('Congratulations! Your Laravel application SMTP is configured and working perfectly.', function ($message) {
        $message->to('[email protected]')
                ->subject('Laravel SMTP Test Successful');
    });
  3. If the command executes and returns null or an instance of SentMessage without errors, your SMTP connection is successful! Check your inbox to confirm receipt.

Step 5: Sending Emails via Mailable Classes (Best Practice)

In production Laravel applications, standard practice is to organize emails using dedicated Mailable classes:

  1. Generate a new Mailable:
    php artisan make:mail WelcomeNotificationMail
  2. Send the email inside any Controller or Action:
    use App\Mail\WelcomeNotificationMail;
    use Illuminate\Support\Facades\Mail;
    
    // Send synchronously
    Mail::to($user->email)->send(new WelcomeNotificationMail($user));
    
    // OR send asynchronously via Queue
    Mail::to($user->email)->queue(new WelcomeNotificationMail($user));

Performance Optimization: Asynchronous Email Sending with Queues

Sending emails synchronously during a user web request (such as user registration or checkout) forces the user’s browser to wait 1 to 3 seconds for the SMTP handshake to complete. To provide instant response times, offload email sending to Laravel Queues:

  1. In .env, set your queue driver to database:
    QUEUE_CONNECTION=database
  2. Create the jobs database migration and run it:
    php artisan queue:table
    php artisan migrate
  3. In your Mailable class (e.g. app/Mail/WelcomeNotificationMail.php), implement the ShouldQueue interface:
    class WelcomeNotificationMail extends Mailable implements ShouldQueue
    {
        use Queueable, SerializesModels;
        // ...
    }
  4. Schedule the queue worker in DirectAdmin Cron Jobs to process queued emails automatically (see our guide on How to Set Up Cron Jobs in DirectAdmin).

Frequently Asked Questions & Troubleshooting

Q: Why do I get "Connection could not be established with host mail.domain.com:465"?
A: Ensure that your port and encryption match: use Port 465 with MAIL_ENCRYPTION=ssl, or Port 587 with MAIL_ENCRYPTION=tls. Also ensure that your domain has an active SSL certificate installed covering mail.domain.com.

Q: Why are my changes to .env not being applied?
A: Whenever you edit the .env file in a deployed Laravel application, always run php artisan config:clear followed by php artisan config:cache.

Q: What should I do if my email password contains special characters (like $, #, !)?
A: Always enclose your MAIL_PASSWORD in double quotes (e.g. MAIL_PASSWORD="P@$$w0rd#2026!") in the .env file to prevent bash and parser parsing issues.

Q: Why are Laravel emails landing in Gmail or Yahoo Spam folders?
A: Make sure your domain has active SPF and DKIM DNS records. In DirectAdmin, go to E-mail Manager > E-mail Accounts and click ENABLE DKIM to ensure all Laravel emails are cryptographically signed.


Need Further Assistance?

If you encounter any issues configuring SMTP in Laravel, setting up background email queues, or verifying DNS authentication records, our technical support team is available 24/7. Feel free to submit a support ticket through your client area for expert assistance.

Hasznosnak találta ezt a választ? 0 A felhasználók hasznosnak találták ezt (0 Szavazat)