Install Mailhog on Ubuntu with postfix

Nguyễn Tuấn Phúc
2 min readJul 21, 2021

Setup Mailhog service to receive emails

Install MailHog

with apt

sudo apt-get -y install golang-go
sudo apt-get install git
go get github.com/mailhog/MailHog

If server cannot access github, we can download directly from Mailhog

wget https://github.com/mailhog/MailHog/releases/download/v1.0.1/MailHog_linux_amd64

then make the file executable

sudo chmod +x MailHog_linux_amd64

Add MailHog as system service

sudo vim /etc/systemd/system/mailhog.service

add content below

[Unit]
Description=MailHog for local
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/path_to_your_MailHog_linux_amd64
[Install]
WantedBy=multi-user.target

start service

sudo systemctl start mailhog.service

Ok, we can visit MailHog client by open

http://localhost:8025

If you setup it in remote server, check firewall on port 8025 to make sure others can access it.

sudo firewall-cmd --zone=public --add-port=8025/tcp --permanent
sudo firewall-cmd --reload

That’s a half way. Now we will config to send email

We need to download mhsendmail and make it executable

wget https://github.com/mailhog/mhsendmail/releases/download/v0.2.0/mhsendmail_linux_amd64sudo chmod +x mhsendmail_linux_amd64

move it to system service

sudo mv mhsendmail_linux_amd64 /usr/local/bin/mhsendmail

Config php

Find php ini file by this command

php -i | grep "php.ini"

Update sendmail_path value as below

sendmail_path = /usr/local/bin/mhsendmail

php sample code to send email

<?php
$to = "to_email@sample.com";
$subject = "Hey, I’m mailer!";
$body = "Hello, Receiver!\nCoffee is amazing thing people have found.\nLet's enjoy it everyday";
$headers = "From: aloha@other-sample.com" . "\r\n";
mail($to,$subject,$body,$headers);

With some other php mail libraries they use mail or sendmail services, we have to config postfix to make it work

Edit postfix config file

sudo vim /etc/postfix/main.cf

Update these variables, 1025 is the port that MailHog will capture email and send to MailHog service.

myhostname = localhost
relayhost = [localhost]:1025

Restart postfix

sudo systemctl restart postfix

Send test email from command (we can use mhsendmail as the same)

sendmail tree@universe.com <<EOF
> From: human@earth.com
> To: tree@moon.com
> Subject: Hello Tree
> I'm coming
> EOF

Check your MailHog mailbox

Enjoy

--

--