If you are relatively new to docker and are migrating php applications to containers you may notice that a lot of docker images recommend using sSMTP as a sendmail replacement / smtp transport for php. I wanted my php containers to relay mail to an EXIM4 container but most php base images do not include any type of mail transport system to allow php to relay emails.
ssmtp cannot rewrite php from header
Ssmtp does work, but not very well and one major problem I came across was that no matter what configuration settings I tried I could not rewrite the send from SMTP headers in ssmtp I wanted, resulting in all emails being sent from the default root@host address.
The solution is to use msmtp. Msmtp works well with PHP 5.x and 7.x images and allows you to rewrite the from headers. Here is how to build it into your PHP 5.x and 7.x base images.
For php7 using the official php-apache docker image you can build msmtp with the following dockerfile commands.
# Install msmtp RUN set -x \ && cd /tmp \ && curl -sSL -o msmtp.tar https://sourceforge.net/projects/msmtp/files/latest/download?source=files \ && tar -xvf msmtp.tar \ && cd msmtp-1.6.6 \ && ./configure \ && make \ && make install \ && rm -rf /tmp/msmtp-1.6.6 msmtp.tar \ && touch /var/log/msmtp.log \ && chmod 777 /var/log/msmtp.log
For PHP5.6 you can get mstmp via the apt package manager
RUN set -x \ && DEBIAN_FRONTEND=noninteractive \ && apt-get update && apt-get install -y --no-install-recommends msmtp
To configure msmtp create a configuration file and copy that to your container via your dockerfile:
COPY ./php/msmtprc /usr/local/etc/msmtprc
The msmtprc configuration file looks like this
defaults tls on tls_certcheck off tls_starttls on #tls_trust_file /etc/ssl/certs/ca-certificates.crt account default host MAIL_RELAY_1 port 25 logfile /var/log/msmtp.log auto_from on maildomain mydomain.com
Where host MAIL_RELAY_1 is the name of your mail container or smtp relay. And mydomain.com the mail domain for the container.
To tell php how to send mail include the following in your php.ini file
sendmail_path = /usr/local/bin/msmtp -t -i
You can either test mail functionality using your php application or via the command line using
echo -e "Subject: Test Mail\r\n\r\nThis is a test mail" |msmtp --debug --firstname.lastname@example.org -t email@example.com
If all is configured correctly the email will be relayed successfully.