Laravel Dockerization: Setting up Mailcatcher

Laravel Dockerization: Setting up Mailcatcher

Introduction

When starting a new project, many developers face challenges in testing functionalities that require sending emails. This includes tasks like email verification during registration or resetting passwords. Usually, you need to wait for the client/manager to provide testing SMTP service credentials, or set one up using a Gmail account. Fortunately, Docker offers a solution to this problem - Mailcatcher.

Mailcatcher

In a nutshell, Mailcatcher runs a simple SMTP server which intercepts all incoming emails and displays them on a web interface. It doesn’t actually send the messages to the email addresses so you don’t have to worry about inputting a valid existing email address to receive your messages, which saves considerable time during testing.

Setting up Mailcactcher for Laravel Docker

Adding the Mailcatcher service to our existing docker environment is straightforward. First, we define a service in our docker-compose.yml for dockage/mailcatcher:

Here, SMTP_PORT is the SMTP server's port, and SMTP_GUI_PORT is for the web interface. I'll use the default values and include them in docker/.env.example:

Next, update your project’s .env.example to reference the service’s host:

That’s it! Now, whenever you send an email inside your Laravel project, it will be sent to Mailcatcher and you will be able to see the email’s content using the web interface at http://localhost:1080.

Testing

To test Mailcatcher, I created a Mailable for sending a blade-rendered email:

Then, I set up a route in web.php that accepts an email address as a parameter and sends an email:

Visiting http://localhost:8082/send-test-email?email=test@example.com queues an email. Once the job is processed using horizon, the email appears in the Mailcatcher web interface:

Note: If the job doesn’t run, ensure you’ve restarted your supervisor within the ld_server container using service supervisor restart.

References