Bijay Das logo

How to Set Up MailHog with Laravel and Sail for Local Email Testing

2 min read
How to Set Up MailHog with Laravel and Sail for Local Email Testing

When developing a Laravel application, sending and testing emails is often required. MailHog is a simple email-catching service that helps you test outgoing emails locally without actually sending them to real email addresses. In this guide, we will walk through how to set up MailHog with Laravel Sail, Laravel's official Docker environment for local development.

Why MailHog?

MailHog captures all outgoing emails in your application and displays them in a web interface.

Prerequisites

  1. Laravel application set up with Laravel Sail.

  2. Docker and Docker Compose installed.

Step 1: Add MailHog Service to Laravel Sail

  1. Open your docker-compose.yml file

  2. Add MailHog configuration

services: # Other services like Laravel, MySQL, etc. mailhog: image: mailhog/mailhog ports: - "1025:1025" # SMTP - "8025:8025" # Web interface

This configuration will start MailHog, exposing SMTP on port 1025 and the web interface on port 8025

Step 2: Update Laravel Environment Configuration

Modify your .env file to use MailHog for email testing. Set the following mail settings:

MAIL_MAILER=smtp MAIL_HOST=mailhog MAIL_PORT=1025 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null

This configuration tells Laravel to use MailHog as the mail server for local email sending.

Step 3: Start Sail Services

Run the following command to start Sail with MailHog:

sail up -d

This will start all the services defined in your docker-compose.yml file, including MailHog.

Step 4: Test MailHog Setup

Send a test email from your Laravel application.

Mail::to($user)->send(new EmailVerificationToken());

Step 5: Check the MailHog web interface

Open your browser and navigate to http://localhost:8025. You should see your test email in MailHog's web interface, confirming that MailHog is capturing emails correctly.

Checkout Laravel's and Mailhog site for more.