During the development process and even when our application is in Staging waiting for the client’s approval, we need to generate notifications that may be annoying for end users: workflow steps and results, password reset process, new accounts, contact forms, etc.
What are our options? We could try using fake emails, but this option won’t work because we need to verify that the user can receive them. We could also try using derived emails (e.g. [email protected]), but this means overwriting all our customer’s emails with our own in the test database.
Mailhog is a great solution to the problem of testing outgoing email during development. It works by replacing the MTA (the outgoing SMTP server) on the local machine. It provides a web client/UI for development purposes and captures arriving messages.
You can use Mailhog in different ways:
- Install it on your development server or localhost (Linux). Just get the binary and run it. On MacOS, use homebrew to install it; you don’t have to be root to run it, but it will require ports 1025 for the service and 8025 for the web UI it provides by default, you can change them though.
- Optionally on your server you can configure a virtual host acting as a proxy to port 8025 to show the UI. Here is a sample configuration file:
# Name for your virtualhost
Allow from all
# Proxy config
# Websocket proxy needs to be defined first
ProxyPass "/api/v2/websocket" ws://localhost:8025/api/v2/websocket
ProxyPassReverse "/api/v2/websocket" ws://localhost:8025/api/v2/websocket
# General proxy
ProxyPass / http://localhost:8025/
ProxyPassReverse / http://localhost:8025/
- You can also use a Docker container for your projects, running it directly from the console or including it in your docker-compose.yml file.
- Mailhog has plenty of options to configure it. For more details, have a look at the project page: https://github.com/mailhog/MailHog.
Once you set the Mailhog instance, you can use a library, package, module, plugin, etc. that allows you to send messages from your application using SMTP, e.g. SwiftMailer for PHP projects, Easy WP SMTP plugin for WordPress, SMTP Authentication Support module for Drupal, smtplib for Python projects.
You won’t really need to deal with complex authentication to send the notifications to Mailhog. A well-formed email address and a blank password is enough but make sure the port matches your configuration (1025 by default) and the host is correct.
Mailhog also has configuration options to allow message forwarding using an external SMTP server. This way messages could reach their real recipients, but this option is not used often since we already have the WebUI where we can check all activity and don’t really need to deliver the messages to the users in our environment. If needed, the configuration is well documented on the project page.
Take a look at this great tool. We find it very useful and hope you do too.