Run Mailhog in Docker and use it in PHP
This post describes how you can install and configure Mailhog as SMTP Server for your local PHP development environment. This is useful to catch all outgoing emails.
A running PHP and Docker environment is required to follow the instructions.
Install Mailhog
On my local machine, I have docker-compose.yml file which contains a lot of services (e.g MySQL, Elastic, Redis) which I use during the daily development.
For our mailhog example we need only one service. Please create a docker-compose.yml with this content:
version: '2' services: mailhog: container_name: mailhog image: mailhog/mailhog restart: always ports: - 1025:1025 - 8025:8025
Run docker-compose up -d mailhog
to create and start the container. If the mailhog image does not exist, Docker will start to download the image from official Docker-Hub.
Verify if everything is up and running.
docker-compose ps Name Command State Ports ------------------------------------------------------------------------------------- mailhog MailHog Up 0.0.0.0:1025->1025/tcp, 0.0.0.0:8025->8025/tcp
No you can use the TCP Port 1025 for sending email over SMTP protocol. The Port 8025 contains the Web-UI.
Configure PHP
Out goal is that PHP’s intern command “mail” uses our freshly installed Mailhog server. To effect this, we need to set the “sendmail_path” setting.
Please modify your php.ini file and set the following directive:
sendmail_path = docker exec -i mailhog sendmail -S localhost:1025
From now, every “mail” command call uses the docker container with the name “mailhog” to send any email.
We can test this with a simple PHP CLI call:
php -r 'mail("foo@example.com", "test", time(), "From: Mailhog <mailhog@example.com>");'
We should now be able to see the arrived message in the Web-UI. Open your browser with the address “http://localhost:8025”.
– Creator of n98-magerun
– Fan of football club @wormatia
– Magento user since version 0.8 beta
– 8x certified Magento developer
– PHP Top 1.000 developer (yes, I’m PHP4 certified and sooooo old)
– Chief development officer at netz98