Wordpress: Email does not work

Created on 17 Nov 2014  路  84Comments  路  Source: docker-library/wordpress

As it currently stands, anything in Wordpress that needs to send email is broken. The wp_mail function that is used for sending out email by default is a thin wrapper over PHP's mail function, which defaults to calling /usr/sbin/sendmail -t -i (cf. http://php.net/manual/en/mail.configuration.php). There are php.ini settings for SMTP, but they are only used on Windows.

For my own work based on this image, I've been installing ssmtp and configuring it to use an external relay host for SMTP, but that's clearly not a turnkey solution for everyone. It also looks like there are many Wordpress plugins that provide SMTP support, but I don't think that installing any of them by default in this image seems reasonable.

Perhaps all of this should just be documented, but I wanted to get it on your radar.

Issue

Most helpful comment

To fix this problem, I created the following files:

php.ini:

sendmail_path=sendmail -t -i 

prepare.sh:

echo "Updating /etc/hosts..."
echo "127.0.0.1 $(hostname) localhost localhost.localdomain" >> /etc/hosts
echo "Restarting sendmail..."
service sendmail restart

Dockerfile:

FROM wordpress

# sendmail
RUN apt-get update && apt-get install -y sendmail
COPY ./php.ini /usr/local/etc/php/conf.d/php.ini
COPY ./prepare.sh /prepare.sh
RUN chmod +x /prepare.sh

CMD /prepare.sh && apache2-foreground

The addition to /etc/hosts is to fix sendmail's long startup and execution time.

Hopefully this helps someone!

All 84 comments

Yeah... This was a hole we've had on our radar for a long time now, but
didn't have a good solution. Perhaps an actual issue will get some
brainshare going. We thought about something like ssmtp, but there really
is no _good_ solution that'll work for 90% of users out of the box. Email
is hard. :(

It looks like WP actually uses something called PHPMailer under the hood, which does support SMTP, but it requires a custom hook for configuration: http://codex.wordpress.org/Plugin_API/Action_Reference/phpmailer_init#Examples

@md5 An alternative is to use a service like mailchimp and Mandrill. I know these are paying services, and not on your own service but the good thing (for Mandrill) is that you can opt out at any moment.

My experience is, your server emails will be probably put in SPAM folder. This is not the case for Mandrill.

@omarabid using Mailchimp or Mandrill still requires using SMTP, which isn't supported out of the box by Wordpress under Linux. As I mentioned in an earlier comment, it would be possible to add one of the WP plugins that supports SMTP, but I don't think it would be reasonable for a generic Wordpress image to include specific plugins.

In my case, I was using ssmtp to connect to Google Apps with a dedicated mail user. This will avoid spam issues just as well as Mandrill. The case you're talking about is likely the default scenario of a PHP app using the local /usr/sbin/sendmail to send its mail out with no relay host settings. In that case, assuming the IP either isn't listed in the domain's SPF records or the IP is part of a spammy netblock, you will indeed have deliverability problems.

using Mailchimp or Mandrill still requires using SMTP

No, otherwise, what's the point of using Mandrill.

Ok, you're right that you can use Mandrill with their REST API instead of SMTP, but that requires installing this plugin or some other plugin that knows how to use that API.

As for the point of using Mandrill with SMTP, there are a ton of reasons you might want to do that, including open tracking, click tracking, deliverability concerns, email volume, etc. Not of those advantages of the Mandrill service rely on using the REST API.

@md5 I was just suggesting a solution. Obviously, this should be available/fixed for the official Docker repo.

Wondering how modular you can make the smtp solution> A nice implementation that I've seen is this one https://github.com/catatnight/docker-postfix , but it does bolt on TLS and and OpenDKIM. Perhaps it could be paired down to just postfix? I'm assuming it would only be used via container link so you don't need TLS. DKIM is fall back to avoid DNS shenanigans, admittedly not having it or SSP will probably cause some filters to flag you as spammy.

Thoughts? I think it's time to retreat to the lab :grinning:

We are using SSMTP to relay to our main mailserver.
We have a php sendmail.ini file that contains the single line:

sendmail_path = /usr/sbin/ssmtp -t

We have a sed in the Dockerfile that changes the mailhub, rewritedomain and removes the hostname line from the ssmtp file (this way it gets the container id as the hostname)

RUN sed -i -e 's/mailhub=mail/mailhub=ourmailrelay.domain/' \
    -e 's/#rewriteDomain=/rewriteDomain=ourdomain/' \
    -e '/hostname=/d' \
    /etc/ssmtp/ssmtp.conf

This works really well, and as ssmtp isn't a daemon, it doesn't require any process management

@booyaa I don't like that the Postfix container you mention is using supervisord and running its own rsyslog, but that's a moot point probably.

I think the real issue is that PHP is still going to expect a working sendmail-compatible command which will need to be configured to talk to the linked SMTP container (whether it's postfix or some other SMTP server). Getting such a setup working and maintaining it would be error prone.

I still think the best that can be done here without assuming too much is simply to document the options.

Random musing: this problem would be a great candidate for a mail service docker-compose.yml firing up smtp, imap, spam assassin, clamav and webmail

@booyaa :+1:

One good option is to configure SSMTP with ENV variables.
This way, you could put your GMAIL or Mandrill cred, and it would work out of the box!

If this is an old post, or there has previously been a resolution please disregard.

One quick way of getting mail working inside the container is to install msmtp.

Then, in a configuration file(example: msmtp):

account default
host 172.17.42.1
auto_from on

Copy this to /etc/ inside the container

Update the php.ini or set the sendmail_path variable like so:

sendmail_path = "/usr/bin/msmtp -t -i"

TL;DR
Use msmtp to point to the guest machine or some other container.

@md5 Any updates on this? I like the new container for SMTP approach. It separates concerns. However, this seems like a WordPress issue for me.

@omarabid I'm not aware of any developments on this issue other than what you can read in this thread.

Perhaps since a bunch of you have been able to successfully run ssmtp in the container alongside Wordpress, I thought I'd pose the question here. My install, even after properly configuring /etc/ssmtp/ssmtp.conf with the main SMTP server to relay to still errors out.

Via a simple mail() function test it fails, via wp_mail as well. When I try sendmail from the command line (inside the container) it locks after sending the last <CR>.<CR> and after a timeout period errors with sendmail: Cannot open server-address:port, which matches what I have in the .conf file. I'm using SSL on the other endpoint so wondering if that could play any part in the issue.

Have you tried telnet server-address port to see if that hangs as well?

Try something like this:

$ docker run -t --rm debian:jessie 'apt-get update && apt-get install -y telnet && telnet server-address port'

If that hangs too, then the problem is probably being caused by firewall rules on the host (outside the container). This can happen if the server you're trying to contact is on an RFC 1918 private subnet like something under 192.168.0.0/16 and your host thinks it should drop packets from the Docker bridge network.

Yeah, did it, and it works fine. it responds. so don't think it's networking related.

Anyways ended up ditching ssmtp completely on the container and just configured WordPress to use the external mailer directly via a plugin that intercepts the calls to mail(): http://coffee2code.com/wp-plugins/configure-smtp/

That's odd. I haven't seen sendmail time out for reasons other than packet drops, but perhaps the SMTP server was overloaded or something?

It would be good to get to the bottom of the issue if only for the sake of other users who hit problems using ssmtp.

BTW, I should point out that sendmail inside the container will be a symlink to ssmtp if that's all you have installed.

Ok, just to continue the discussion, here is a working example with ssmtp configured with env variables:

https://github.com/indiehosters/wordpress/

So I've managed to come up with a solution that involves another container and a WordPress plugin. The container is running an SMTP client that I wrote (named Hectane) and the WordPress plugin routes all calls to wp_mail() through the container.

Here are the commands to get it up and running:

docker run -d --name db mysql:latest
docker run -d --name mail hectane/hectane:0.2.1
docker run \
    -d -P \
    --link db:db \
    --link mail:mail \
    wordpress:latest

Once the containers are up and running, it's simply a matter of installing and activating this WordPress plugin and changing the hostname to "mail" in "Settings".

WordPress Configuration

Once that's done, all emails will be sent through Hectane and delivered via SMTP.

Hi @nathan-osman, is it possible use hectane/hectane container with Drupal 8 ?

I am using SendGrid for emails. It is super easy to set up with one of the many WP plugins and then you will send emails through an API while getting insights on open rate, bounce rate etc.

I presume you could use anyone of the smtp plugins to get this to work?
E.g. https://wordpress.org/plugins/wp-smtp/

I'm far from an email expert, but we pulled down this repo some time ago and just set up sendmail to work with it. We're actually looking for another solution which centralizes it so we can spam check and rate limit outgoing email, but we've had the sendmail solution up for the better part of a year on production sites. The trick is that you have to fully qualify your host name, which you can pass in from docker and re-install sendmail.

We've totally rewritten the dockerfile/start.sh to use wp-cli, php 7.0 and getting services working in lieu of supervisord, but here are the tweaks for this repo :

[Dockerfile]
# Sendmail Installation
RUN apt-get -y install sendmail

[Start.sh]
/etc/init.d/sendmail start
supervisord -n

You have to make sure the host name of the docker instance is a FQDN. We use the scheme host-dock-{port}.hostingcompany.com. If you set this through docker -h then it will configure the host file that sendmail requires. If you don't do this then sendmail will time out (10 sec), which is probably the problem mentioned earlier in this thread.

@sashman-jaspin - Thank you. Did just that in the bitnami/php-fpm container and it works just fine.

Managed to get it working with this setup :

  • install sendmail
  • edit containers's hosts file to add this line :
    container_IP container_ID container_ID.localdomain
  • Install a wordpress smtp plugin

But i want to do it without the plugin, i think i'm near the solution proposed by @sashman-jaspin !
Problem : it work with the plugin but not without ! while sendmail is working in the container (command line) i just can't make wordpress using it... I think my solution is in the last part of @sashman-jaspin method (maybe i'm wrong) but i don't fully understand it, can someone ELI5 ?

UPDATE
With some tricks i managed to make it work without plugin, also updated my blog post about it, (in french) envoyer des emails avec wordpress sur docker.

Ok, I found an acceptable solution \o/ without anything installed!

The idea is to use a "must use plugin". The advantage is that we don't have to activate it. And it is quiet hidden from the user perspective.

So, this configures SMTP support for WordPress using ENV variables:
https://github.com/indiehosters/docker-wordpress/blob/master/run.sh

Should I PR to make this available to everybody?

I'm trying with hectane as mentioned by @nathan-osman , but it seems that wp still tryes to send emails with mail(). Anyone else has tryed it?
I put the link as suggested and set "mail" as host. Also tryed to put the mail container/service endpoint as host. Nothing works...

@pierreozoux I'm using something similar, but sticking it in wp-config.php

Is there a reason why you use it via an extension?

@lazyfrosch I wanted to put it in wp-config.php, but I saw no way to do it.

Could you show your code? If you have a way to configure SMTP from wp-config, then this would be amazing!

@pierreozoux At the end of wp-config:

// configure phpmailer
add_action( 'phpmailer_init', 'mail_relay' );
function mail_relay( $phpmailer ) {
    $phpmailer->isSMTP();
    $phpmailer->Host = '1.1.1.1';
    $phpmailer->SMTPAutoTLS = false;
    //$phpmailer->SMTPAuth = true; // Force it to use Username and Password to authenticate
    //$phpmailer->Port = 25;
    //$phpmailer->Username = 'yourusername';
    //$phpmailer->Password = 'yourpassword';

    // Additional settings
    //$phpmailer->SMTPSecure = "tls"; // Choose SSL or TLS, if necessary for your server
    //$phpmailer->From = "[email protected]";
    //$phpmailer->FromName = "Your Name";
}

I'm only setting a relay host, it's the host system running Debian. I'm just trusting my Docker containers as of now.

@tianon what do you think of a PR to ease smtp configuration inside the container via env variables?

Or do you think it would be more suitable to add this in the documentation?

Either way, I think we need to do something to close this issue.

@alessiovmagri oh my! You're right, there seems to be a bug with the latest release of the WordPress plugin. I'll have that fixed immediately and let you know when the update is published.

I'm +1 to documenting this better, especially if there's a good plugin or
two we can link to. :smile:

@alessiovmagri sorry about that. The latest version of the plugin (0.1.6) fixes the bug and your container should be able to send emails again.

@tianon let me know if you are interested in mentioning the Hectane plugin - I'd be happy to write up some documentation for using it with the WordPress container if needed.

not sure how to get it working with this image but to get it working with the default php image I changed the default CMD in my Dockerfile to

FROM php:5.6-apache
RUN apt-get update && apt-get install -y sendmail
CMD /usr/sbin/service sendmail restart && /usr/local/bin/apache2-foreground

It would be something similar for this image, The main reason is hostname is not set until the container is running.

thanks @lazyfrosch for the code. I found this solution the most efficient and also the cleanest.

Would that help any one whishing to use a gmail account: you would need to create an "application password", somewhere around here: https://security.google.com/settings/security/apppasswords

The working piece of code will look like:

// configure phpmailer
add_action( 'phpmailer_init', 'mail_relay' );
function mail_relay( $phpmailer ) {
    $phpmailer->isSMTP();
    $phpmailer->Host = 'smtp.gmail.com';
    $phpmailer->SMTPAutoTLS = true;
    $phpmailer->SMTPAuth = true; 
    $phpmailer->Port = 465;
    $phpmailer->Username = '<admin email>';
    $phpmailer->Password = '<app password>';

    // Additional settings
    $phpmailer->SMTPSecure = "ssl"; 
    $phpmailer->From = "<admin email>";
    $phpmailer->FromName = "<your name>";
}

Cheers,
Manu

Hey all, i've opened an answer at Stack Overflow.

Is any good news we will have in image updates or we need to bypass routes?

I hope this comment will help somehow : https://github.com/docker-library/php/issues/135#issuecomment-277199026

Has anyone figured out a neat way to solve this without too much overhead?
I'd rather have it all baked into a Dockerfile that adds everything that is needed on top, without having to exec into the container and then fiddle with its settings (for automated deploys).
Or perhaps I'm overthinking this and a WP plugin is the way to go? Has anyone ever had the need for this container itself to send emails, which a plugin would not resolve?

I've been running two instances of WordPress in production with Hectane for almost a year now with no issues. The WordPress plugin isn't even really needed now that Hectane accepts mail for delivery directly via SMTP.

To fix this problem, I created the following files:

php.ini:

sendmail_path=sendmail -t -i 

prepare.sh:

echo "Updating /etc/hosts..."
echo "127.0.0.1 $(hostname) localhost localhost.localdomain" >> /etc/hosts
echo "Restarting sendmail..."
service sendmail restart

Dockerfile:

FROM wordpress

# sendmail
RUN apt-get update && apt-get install -y sendmail
COPY ./php.ini /usr/local/etc/php/conf.d/php.ini
COPY ./prepare.sh /prepare.sh
RUN chmod +x /prepare.sh

CMD /prepare.sh && apache2-foreground

The addition to /etc/hosts is to fix sendmail's long startup and execution time.

Hopefully this helps someone!

Thanks @abrichr for amazingly simple solution. Didn't catch that /etc/hosts was the villain.

If you'd like to have all the goodness of @abrichr's above post https://github.com/docker-library/wordpress/issues/30#issuecomment-317511836 (thank you!) without messing with several files, here it is all in one single Dockerfile RUN command.

Bonus: Container will stop when hitting Ctrl+C.

FROM wordpress:apache

RUN \
  #
  # Install sendmail
    apt-get update \
 && apt-get install -y --no-install-recommends sendmail \
 && rm -rf /var/lib/apt/lists/* \
  #
  # Configure php to use sendmail
 && echo "sendmail_path=sendmail -t -i" >> /usr/local/etc/php/conf.d/sendmail.ini \
  #
  # Create script to use as new entrypoint, which
  # 1. Creates a localhost entry for container hostname in /etc/hosts
  # 2. Restarts sendmail to discover this entry
  # 3. Calls original docker-entrypoint.sh
 && echo '#!/bin/bash' >> /usr/local/bin/docker-entrypoint-wrapper.sh \
 && echo 'set -euo pipefail' >> /usr/local/bin/docker-entrypoint-wrapper.sh \
 && echo 'echo "127.0.0.1 $(hostname) localhost localhost.localdomain" >> /etc/hosts' >> /usr/local/bin/docker-entrypoint-wrapper.sh \
 && echo 'service sendmail restart' >> /usr/local/bin/docker-entrypoint-wrapper.sh \
 && echo 'exec docker-entrypoint.sh "$@"' >> /usr/local/bin/docker-entrypoint-wrapper.sh \
 && chmod +x /usr/local/bin/docker-entrypoint-wrapper.sh

ENTRYPOINT ["docker-entrypoint-wrapper.sh"]
CMD ["apache2-foreground"]

Hi @janpapenbrock as i am quite new to Docker, just to be clear: what would be the steps to make this work?
Until now i used a docker-compose.yml. Should i add something like (see inside the code)

version: '3'

services:
   db:
     container_name: ${CONTAINER_DB_NAME}
     image: mysql:5.7
     restart: unless-stopped
     volumes:
        - ${DB_PATH}:/var/lib/mysql
     environment:
       MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
       MYSQL_DATABASE: ${MYSQL_DATABASE}
       MYSQL_USER: ${MYSQL_USER}
       MYSQL_PASSWORD: ${MYSQL_PASSWORD}

   wordpress:
     depends_on:
       - db
     container_name: ${CONTAINER_WP_NAME}
     image: wordpress:${WORDPRESS_IMAGE}
     restart: unless-stopped
     volumes:
       - ${WP_CORE}:/var/www/html
       - ${WP_CONTENT}:/var/www/html/wp-content
     environment:
       WORDPRESS_DB_HOST: ${CONTAINER_DB_NAME}:3306
       WORDPRESS_DB_NAME: ${MYSQL_DATABASE}
       WORDPRESS_DB_USER: ${MYSQL_USER}
       WORDPRESS_DB_PASSWORD: ${MYSQL_PASSWORD}
       WORDPRESS_TABLE_PREFIX: ${WORDPRESS_TABLE_PREFIX}
       VIRTUAL_HOST: ${DOMAINS}
       LETSENCRYPT_HOST: ${DOMAINS}
       LETSENCRYPT_EMAIL: ${LETSENCRYPT_EMAIL}
     build:
      context: .
      dockerfile: Dockerfile
# I added the Dockerfile you suggested as it is
# and added this build part

networks:
    default:
       external:
         name: ${NETWORK}


I'm confortable with docker-compose and setting up containers but i can't make the mail part working on my wordpress containers :/

Just to be clear the thing i want the server to be able to is for example send a "forgotten password" email confirmation. No newsletters or anything like that.
@abrichr maybe you can guide me a little here. Should i rebuild an image with the info you provided and mount a container with that said image?

@Julianoe

Yes, it should work. I spotted in your docker-compose.yml you have both image and build defined for wordpress service.

However, I decided to publish this exact image to Docker Hub and I am successfully using it like so:

services:
  wordpress:
    image: hochzehn/wordpress-sendmail:4.9-php7.1-apache

If you have further questions I'm happy to help on Gitter.

@janpapenbrock

it works on my new site!

but I think SPF should be added to domain

Any chance to see @pierreozoux plugin been bundled and configurable via environment?
Those who want to do it the docker way can still use an external docker image for the MTA, but the WP plugin/hooks would be needed anyway.

@lazyfrosch thank you !

This is what I ended up doing to get working SMTP with environment variables, I'm appending this code to wp-config.php

/* SMTP Settings */
add_action( 'phpmailer_init', 'mail_smtp' );
function mail_smtp( $phpmailer ) {
  $phpmailer->isSMTP();
  $phpmailer->Host = getenv('WORDPRESS_SMTP_HOST');
  $phpmailer->SMTPAutoTLS = true;
  $phpmailer->SMTPAuth = true;
  $phpmailer->Port = getenv('WORDPRESS_SMTP_PORT');
  $phpmailer->Username = getenv('WORDPRESS_SMTP_USERNAME');
  $phpmailer->Password = getenv('WORDPRESS_SMTP_PASSWORD');

  // Additional settings
  $phpmailer->SMTPSecure = "tls";
  $phpmailer->From = getenv('WORDPRESS_SMTP_FROM');
  $phpmailer->FromName = getenv('WORDPRESS_SMTP_FROM_NAME');
}

You can check how it's integrated in the Dockerfile in this repo (https://github.com/debtcollective/docker-wordpress/)

@orlando: Could you please send a PR to get your code into the project? Sounds like the integration of @lazyfrosch code base.

@controlcde not sure if they want to merge something like this. but if they want to, it's easier to modify the Dockerfile and the main script instead

Attempted the solution that @janpapenbrock graciously provided and sendmail is setup and appears to work from PHP WP functions but mail internally fails with a "SMTP; 550 Host unknown" diagnostic code.

What am I missing?

Can confirm @orlando 's solution works. Any chance this might be committed to the repo? Would the admins be open to a PR?

Here is my solution in the Dockerfile:

RUN apt-get install -y ssmtp
RUN echo "sendmail_path = /usr/sbin/ssmtp -t" >> /usr/local/etc/php/conf.d/sendmail.ini
RUN sed -i -e 's/mailhub=mail/mailhub=[MY-RELAY-IP]/' /etc/ssmtp/ssmtp.conf
RUN sed -i -e 's/#rewriteDomain=/rewriteDomain=[MY-RELAY-IP]/' /etc/ssmtp/ssmtp.conf
RUN sed -i -e 's/#FromLineOverride=/FromLineOverride=/' /etc/ssmtp/ssmtp.conf
RUN sed -i -e '/hostname=/d' /etc/ssmtp/ssmtp.conf

ssmtp is propably the best solution as it is very small, does not require a service to be running and installs as the sendmail binary. If the official Wordpress image would include this package, then the entrypoint script could populate the ssmtp.conf via ENV variables at container start.

Can't you guys don't just install ssmtp with the official Image? Then we all would be satisfied and wouldn't have to maintain child images. We'd mount our ssmtp.conf in the container and voila.

I try to realize the configuration with WORDPRESS_CONFIG_EXTRA but the _$phpmailer_ variable will be resolved (or not in this case)

WARNING: The phpmailer variable is not set. Defaulting to a blank string.

and the config looks like

// WORDPRESS_CONFIG_EXTRA
/* SMTP Settings */
add_action( 'phpmailer_init', 'mail_smtp' );
function mail_smtp(  ) {
->isSMTP();
->Host = 'mailServer';
->SMTPAutoTLS = true;
->SMTPAuth = true;
->Port = 587;
...

How could I escape the variable _$phpmailer_?

@controlcde, Are you setting WORDPRESS_CONFIG_EXTRA via a compose or stack file? If so you would need to put $$phpmailer so that docker-compose / docker stack will put a literal $ rather than trying to replace the variable in the yaml. (https://docs.docker.com/v17.09/compose/compose-file/#variable-substitution)

@yosifkit You're right. With the Double-$ the correct entries will be made in the config file. But it doesn't work - I think the WORDPRESS_CONFIG_EXTRA should be add at the end of wp-config.php to get the email settings working.

Hi @pcmanprogrammeur, @timwsuqld, @md5,
(sorry for spamming you guys, but I am bit desperate)
I am trying to follow your suggestions here to setup E-Mail in a Wordpress container using ssmtp. Unfortunately without success thusfar.
Here is what I have:

wordpress docker file content:

FROM wordpress:4.9

RUN apt-get update
RUN apt-get install -y ssmtp

COPY ssmtp.conf /etc/ssmtp/ssmtp.conf

RUN echo "sendmail_path = /usr/sbin/ssmtp -t" >> /usr/local/etc/php/conf.d/sendmail.ini

ssmtp.conf:

[email protected]
mailhub=smtp.gmail.com:587
AuthUser=myuser
AuthPass=mypassword
UseSTARTTLS=Yes
UseTLS=Yes
hostname=localhost

When I test things out by requesting a password recovery E-mail I get the following error message in the browser:

The email could not be sent.
Possible reason: your host may have disabled the mail() function.

with this URL: https://mydomain.com/wp-login.php?action=lostpassword

However I can send mails using ssmtp by logging into the container using

docker exec -it my_wordpress_docker_container /bin/bash

and doing

echo "This message is sent correctly!" | ssmtp -vvv [email protected]

Can anyone tell me what I am missing? Any help is much appreciated, thanks!

@packoman I had the same problem when I didn't have the sendmail.ini in place before php start. Also, I've seen many places that they put quotes around the command:
RUN echo "sendmail_path = \"/usr/sbin/ssmtp -t\"" >> /usr/local/etc/php/conf.d/sendmail.ini

@packoman need allow www-data to send mail

FROM wordpress:4.9

RUN apt-get update
RUN apt-get install -y ssmtp

COPY ssmtp.conf /etc/ssmtp/ssmtp.conf
COPY revaliases /etc/ssmtp/revaliases

RUN echo "sendmail_path = /usr/sbin/ssmtp -t" >> /usr/local/etc/php/conf.d/sendmail.ini

revaliases

root:[email protected]:smtp.gmail.com:465
www-data:[email protected]:smtp.gmail.com:465

Also for gmail read this:

https://support.google.com/mail/answer/7126229

https://www.google.com/accounts/DisplayUnlockCaptcha

I found the following postfix relay: https://github.com/wader/postfix-relay

I found the maintainer still is working on it and it has support for DKIM which is all i needed. I just added to the functions.php file the following:

add_action( 'phpmailer_init', 'wpse8170_phpmailer_init' );
function wpse8170_phpmailer_init( PHPMailer $phpmailer ) {
    // connect to the SMTP server running in our internal network
    $phpmailer->Host = 'smtp';
    $phpmailer->Port = 25;
    $phpmailer->SMTPAuth = false;
    $phpmailer->SMTPSecure = false;
    $phpmailer->IsSMTP();
}

Where smtp is the name of my postfix relay container (which thus resolves to the correct IP without exposing to the internets)

I then used the following config inside of my docker-compose.yml to get the image up n running

  volumes:
    dkim-data:

  wordpress:
    ...
    depends_on:
      ...
      - smtp # added depends_on because wordpress depends on it.. that being said probably not required
    ...

  smtp:
    image: mwader/postfix-relay
    restart: always
    container_name: sova-smtp
    environment:
      - POSTFIX_myhostname=awesomesite.com.au
      - OPENDKIM_DOMAINS=awesomesite.com.au
    volumes:
      - dkim-data:/etc/opendkim/keys
    expose:
      - "25"

I would consider msmtp instead. It is probably a little better than ssmtp, because ssmtp afaik is unmaintained.

https://marlam.de/msmtp/
https://wiki.archlinux.org/index.php/msmtp

I would consider msmtp instead. It is probably a little better than ssmtp, because ssmtp afaik is unmaintained.

https://marlam.de/msmtp/
https://wiki.archlinux.org/index.php/msmtp

@joeldeteves I researched this separately and have come to the same conclusion. msmtp seems to be the way forward and fills largely the same exact role as ssmtp, only better (fewer bugs, improved system compatability) and more recently maintained. It appears Arch has completely dropped ssmtp from its repositories and I see Cygwin apparently supports msmtp now as well, which was apparently one of the platforms keeping ssmtp alive.

(Edited because I was being aggressive.)
I'd like to see a mention of the missing emailing in the image's README!

@Adrien-Luxey, Not a very inviting tone to take on an old issue; please be respectful.

If you have concrete suggestions for how it can be improved, a PR is welcome (here is the source of the Docker Hub description: https://github.com/docker-library/docs/blob/master/wordpress/content.md)

You are right, please forgive me. I'll propose a (gentle) modification to the README myself. I will edit my previous comment if you don't mind.

Don't use ssmtp on new setups. It isn't serviced and debian packages are orphaned. Use msmtp instead.

/etc/msmtprc

# Set default values for all following accounts.
defaults
auth           on
tls            on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile        /tmp/msmtp.log

# Custom Mailserver
account        mymailserver
host           mail.example.com
port           587
from           [email protected]
user           [email protected]
password       12345678

# Set a default account
account default : mymailserver

With recent versions (not yet available in alpine and debian) you can also set set_from_header to overwrite wordpress@localhost from address.

Also set this php configuration value:
sendmail_path = "/usr/bin/msmtp -t"

I agree with the above. Let me propose my simple configuration that only forwards mail to my host's postfix (you could also have a dedicated container for sending mail, which would alleviate the need for fixed container network configuration):

/etc/msmtprc (container)

account default
host 172.27.0.1 # IP of my host: the network's gateway from the container's point of view
port 25
from [email protected]

You also need to configure your host's postfix to accept requests from docker:

/etc/postfix/main.cf (host)

# [...]
mynetworks = ... 172.27.0.0/24

This is minimal: expect your mails to end in spam folders. But it works!
Your comments are welcome.

EDIT: I ran into trouble setting mynetworks = ... 172.0.0.0/8. Be specific with your network addresses!

I had the same problem. So I tried to find a solution. I've found several solutions and tested all of them at my site (to make sure they worked). It would be too long to post them here. So I have created a separate article:

https://www.wpdiaries.com/mail-functionality-for-official-docker-wordpress-image/

The article contains detailed examples of adding Postfix in a separate container. There are 2 such examples based on 2 different images (one has digital signing e-mails with DKIM and the other one works without DKIM). Also, I have added an example of adding Postfix directly to a WordPress container, but this solution is not recommended (it is better to have 1 responsibility for 1 container as it is described in the official Docker best practices).

I've made sure the e-mail sending functionality works in each of the listed examples.

I hope this will be useful for people who got problems with sending e-mail from WordPress in Docker. At least I did my best to provide as detailed and clear examples as I could.

possibly use Mailhog? Other images have used this
dockerfile:

Forward Message to mailhog

RUN curl --location --output /usr/local/bin/mhsendmail https://github.com/mailhog/mhsendmail/releases/download/v0.2.0/mhsendmail_linux_amd64 && \
chmod +x /usr/local/bin/mhsendmail
RUN echo 'sendmail_path="/usr/local/bin/mhsendmail --smtp-addr=mailhog:1025 [email protected]"' > /usr/local/etc/php/conf.d/mailhog.ini

docker-compose:
mailhog:
container_name: ${APP_NAME}-mailhog
image: mailhog/mailhog
ports:
- "8025:8025"
- "1025:1025"

I would consider msmtp instead. It is probably a little better than ssmtp, because ssmtp afaik is unmaintained.

https://marlam.de/msmtp/
https://wiki.archlinux.org/index.php/msmtp

Hello, I have found a much better solution than using msmtp, ssmtp, mailhog or any other SMTP client for that matter.

Wordpress is apparently bundled with PHPMailer - I did not realize that it came included with Wordpress by default.

This means with a little creativity we are able to configure it using the WORDPRESS_CONFIG_EXTRA environment variable that is baked into the docker image.

Here is an example written in YAML for our Kubernetes deployment:

          env:
            - name: SMTP_HOSTNAME
              value: "smtp.office365.com"
            - name: SMTP_PORT
              value: "587"
            - name: SMTP_USER
              value: "[email protected]"
            - name: SMTP_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: "wordpress-smtp-password"
                  key: smtp-password
                  optional: true
            - name: SMTP_FROM
              value: "[email protected]"
            - name: WORDPRESS_CONFIG_EXTRA
              value: |
                // SMTP Settings
                require_once( ABSPATH .'wp-includes/plugin.php' );
                add_action( 'phpmailer_init', 'mail_smtp' );
                function mail_smtp( $phpmailer ) {
                  $phpmailer->isSMTP();
                  $phpmailer->Host = getenv('SMTP_HOSTNAME');
                  $phpmailer->Port = getenv('SMTP_PORT');
                  $phpmailer->Username = getenv('SMTP_USER');
                  $phpmailer->Password = getenv('SMTP_PASSWORD');
                  $phpmailer->From = getenv('SMTP_FROM');
                  $phpmailer->FromName = getenv('SMTP_FROM_NAME');

                  // Additional settings
                  $phpmailer->SMTPAuth = true;
                  $phpmailer->SMTPSecure = "tls";
                  $phpmailer->SMTPAutoTLS = true;
                }
                // Prevent Wordpress from overriding the SMTP FROM address (Office 365 compatibility)
                add_filter( 'wp_mail_from', function( $email ) {
                  return $_ENV["SMTP_FROM"];
                });

Of course, with a little tweaking you can apply the same setup in Docker, docker-compose and more, and at least in our case this eliminates the need for building a custom Docker image or running an MTA in a separate container.

Hope this helps,

I would consider msmtp instead. It is probably a little better than ssmtp, because ssmtp afaik is unmaintained.
https://marlam.de/msmtp/
https://wiki.archlinux.org/index.php/msmtp

Hello, I have found a much better solution than using msmtp, ssmtp, mailhog or any other SMTP client for that matter.

Wordpress is apparently bundled with PHPMailer - I did not realize that it came included with Wordpress by default.

This means with a little creativity we are able to configure it using the WORDPRESS_CONFIG_EXTRA environment variable that is baked into the docker image.

Here is an example written in YAML for our Kubernetes deployment:

          env:
            - name: SMTP_HOSTNAME
              value: "smtp.office365.com"
            - name: SMTP_PORT
              value: "587"
            - name: SMTP_USER
              value: "[email protected]"
            - name: SMTP_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: "wordpress-smtp-password"
                  key: smtp-password
                  optional: true
            - name: SMTP_FROM
              value: "[email protected]"
            - name: WORDPRESS_CONFIG_EXTRA
              value: |
                // SMTP Settings
                require_once( ABSPATH .'wp-includes/plugin.php' );
                add_action( 'phpmailer_init', 'mail_smtp' );
                function mail_smtp( $phpmailer ) {
                  $phpmailer->isSMTP();
                  $phpmailer->Host = getenv('SMTP_HOSTNAME');
                  $phpmailer->Port = getenv('SMTP_PORT');
                  $phpmailer->Username = getenv('SMTP_USER');
                  $phpmailer->Password = getenv('SMTP_PASSWORD');
                  $phpmailer->From = getenv('SMTP_FROM');
                  $phpmailer->FromName = getenv('SMTP_FROM_NAME');

                  // Additional settings
                  $phpmailer->SMTPAuth = true;
                  $phpmailer->SMTPSecure = "tls";
                  $phpmailer->SMTPAutoTLS = true;
                }
                // Prevent Wordpress from overriding the SMTP FROM address (Office 365 compatibility)
                add_filter( 'wp_mail_from', function( $email ) {
                  return $_ENV["SMTP_FROM"];
                });

Of course, with a little tweaking you can apply the same setup in Docker, docker-compose and more, and at least in our case this eliminates the need for building a custom Docker image or running an MTA in a separate container.

Hope this helps,

does anyone know how to translate this into a docker-compose.yml? Thank you so much!

does anyone know how to translate this into a docker-compose.yml? Thank you so much!

Hi @derspotter, you could try something like this (note the double $$ to prevent docker compose from interpreting environment variables in the PHP code):

(NOTE: I do not use Docker compose and I don't know the best way to handle storing sensitive info such as secrets. This is just a proof of concept showing how to translate a quick setup to a docker-compose file:

version: "3.9"
services:
  wordpress:
    image: wordpress:latest
    ports:
      - 8080:80
    environment:
      SMTP_HOSTNAME: smtp.office365.com
      SMTP_PORT: "587"
      SMTP_USER: [email protected]
      SMTP_PASSWORD: /run/secrets/smtp_password
      SMTP_FROM: [email protected]
      WORDPRESS_DB_HOST: wordpress-db
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: /run/secrets/db_password
      WORDPRESS_DB_NAME: wordpress
      WORDPRESS_CONFIG_EXTRA: |
          // SMTP Settings
          require_once( ABSPATH .'wp-includes/plugin.php' );
          add_action( 'phpmailer_init', 'mail_smtp' );
          function mail_smtp( $$phpmailer ) {
              $$phpmailer->isSMTP();
              $$phpmailer->Host = getenv('SMTP_HOSTNAME');
              $$phpmailer->Port = getenv('SMTP_PORT');
              $$phpmailer->Username = getenv('SMTP_USER');
              $$phpmailer->Password = getenv('SMTP_PASSWORD');
              $$phpmailer->From = getenv('SMTP_FROM');
              $$phpmailer->FromName = getenv('SMTP_FROM_NAME');

              // Additional settings
              $$phpmailer->SMTPAuth = true;
              $$phpmailer->SMTPSecure = "tls";
              $$phpmailer->SMTPAutoTLS = true;

              // Filter out client message body and output debug info to the logs
              // NOTE: Log level must be set to '2' or higher in order for the filter to work
              $$phpmailer->SMTPDebug = 2;

              $$phpmailer->Debugoutput = function($$str) {
                  static $$logging = true;
                  if ($$logging === false && strpos($$str, 'SERVER -> CLIENT') !== false) {
                      $$logging = true;
                  }
                  if ($$logging) {
                      error_log("SMTP " . "$$str");
                  }
                  if (strpos($$str, 'SERVER -> CLIENT: 354') !== false) {
                      $$logging = false;
                  }
              };
          }
          // Prevent Wordpress from overriding the SMTP FROM address (Office 365 compatibility)
          add_filter( 'wp_mail_from', function( $$email ) {
              return $$_ENV["SMTP_FROM"];
          });
    volumes:
      - wp-data:/var/www/html
    secrets:
      - db_password
      - smtp_password
    depends_on:
      - wordpress-db

  wordpress-db:
    image: mariadb:latest
    environment:
      MYSQL_ROOT_PASSWORD: /run/secrets/db_root_password
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: /run/secrets/db_password
    volumes:
      - db-data:/var/lib/mysql
    secrets:
      - db_root_password
      - db_password

volumes:
  wp-data:
  db-data:

secrets:
  db_password:
    file: db_password.secret
  db_root_password:
    file: db_root_password.secret
  smtp_password:
    file: smtp_password.secret

does anyone know how to translate this into a docker-compose.yml? Thank you so much!

Hi @derspotter, you could try something like this (note the double $$ to prevent docker compose from interpreting environment variables in the PHP code):

Thank you so much!!! it works :))

Thanks @joeldeteves for the WORDPRESS_CONFIG_EXTRA + PHPMailer solution, it is working for me.

In case it saves someone else a few frustrating hours, it seems like the *-alpine Docker WP images are not able to do external networking (like connecting to remote external SMTP hosts). I'm talking about external connections to public internet hosts (like smtp.mailgun.org), not to your local Docker containers. Maybe that's common knowledge but it was news to me.

I am not sure what exactly is missing but from inside a container using the wordpress:5.6-php7.4-fpm-alpine image, I was not able to either resolve an IP for my mail host (smtp.mailgun.org), nor ping it. Switching to wordpress:5.6-php7.4-fpm solved the problem, though it took much hair pulling and gnashing of teeth to get there.

it seems like the *-alpine Docker WP images are not able to do external networking (like connecting to remote external SMTP hosts)

I'm not able to reproduce this problem; I use alpine versions for all my deployments (currently running wordpress:5.6.2-php7.4-fpm-alpine).

You might want to double-check your config and/or firewall.

I'm not able to reproduce this problem; I use alpine versions for all my deployments (currently running wordpress:5.6.2-php7.4-fpm-alpine).

@joeldeteves Interesting. I'm on macOS. It doesn't work for me. I'm not sure this is the right place for this tangent but maybe it is relevant and helps others. Super-simple docker-compose.yml demonstrating the problem:

version: '3'
services:
  wordpress1:
    image: wordpress:5.6-php7.4-fpm
  wordpress2:
    image: wordpress:5.6-php7.4-fpm-alpine
$ docker-compose up -d
Starting test_wordpress1_1 ... done
Starting test_wordpress2_1 ... done

$ docker exec -it test_wordpress1_1 bash
root@36939bbe8fcb:/var/www/html# curl -I https://github.com/docker-library/wordpress/issues/30
HTTP/2 200
server: GitHub.com
date: Sun, 14 Mar 2021 18:12:44 GMT
... lots of headers, clearly works fine
root@36939bbe8fcb:/var/www/html# exit

$ docker exec -it test_wordpress2_1 bash
bash-5.1# curl -I https://github.com/docker-library/wordpress/issues/30
curl: (6) Could not resolve host: github.com

@joeldeteves Interesting. I'm on macOS. It doesn't work for me. I'm not sure this is the right place for this tangent but maybe it is relevant and helps others.

I still can't reproduce this (I used the compose example you provided above, both containers are able to resolve just fine) however I am running Ubuntu.

It is very probable that this is something specific to your environment, quite possibly Mac-OS specific.

You may want to run some more tests such as testing from a VM, but I do not believe it is related to the alpine image.

does anyone know how to translate this into a docker-compose.yml? Thank you so much!

Hi @derspotter, you could try something like this (note the double $$ to prevent docker compose from interpreting environment variables in the PHP code):

(NOTE: I do not use Docker compose and I don't know the best way to handle storing sensitive info such as secrets. This is just a proof of concept showing how to translate a quick setup to a docker-compose file:

version: "3.9"
services:
  wordpress:
    image: wordpress:latest
    ports:
      - 8080:80
    environment:
      SMTP_HOSTNAME: smtp.office365.com
      SMTP_PORT: "587"
      SMTP_USER: [email protected]
      SMTP_PASSWORD: /run/secrets/smtp_password
      SMTP_FROM: [email protected]
      WORDPRESS_DB_HOST: wordpress-db
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: /run/secrets/db_password
      WORDPRESS_DB_NAME: wordpress
      WORDPRESS_CONFIG_EXTRA: |
          // SMTP Settings
          require_once( ABSPATH .'wp-includes/plugin.php' );
          add_action( 'phpmailer_init', 'mail_smtp' );
          function mail_smtp( $$phpmailer ) {
              $$phpmailer->isSMTP();
              $$phpmailer->Host = getenv('SMTP_HOSTNAME');
              $$phpmailer->Port = getenv('SMTP_PORT');
              $$phpmailer->Username = getenv('SMTP_USER');
              $$phpmailer->Password = getenv('SMTP_PASSWORD');
              $$phpmailer->From = getenv('SMTP_FROM');
              $$phpmailer->FromName = getenv('SMTP_FROM_NAME');

              // Additional settings
              $$phpmailer->SMTPAuth = true;
              $$phpmailer->SMTPSecure = "tls";
              $$phpmailer->SMTPAutoTLS = true;

              // Filter out client message body and output debug info to the logs
              // NOTE: Log level must be set to '2' or higher in order for the filter to work
              $$phpmailer->SMTPDebug = 2;

              $$phpmailer->Debugoutput = function($$str) {
                  static $$logging = true;
                  if ($$logging === false && strpos($$str, 'SERVER -> CLIENT') !== false) {
                      $$logging = true;
                  }
                  if ($$logging) {
                      error_log("SMTP " . "$$str");
                  }
                  if (strpos($$str, 'SERVER -> CLIENT: 354') !== false) {
                      $$logging = false;
                  }
              };
          }
          // Prevent Wordpress from overriding the SMTP FROM address (Office 365 compatibility)
          add_filter( 'wp_mail_from', function( $$email ) {
              return $$_ENV["SMTP_FROM"];
          });
    volumes:
      - wp-data:/var/www/html
    secrets:
      - db_password
      - smtp_password
    depends_on:
      - wordpress-db

  wordpress-db:
    image: mariadb:latest
    environment:
      MYSQL_ROOT_PASSWORD: /run/secrets/db_root_password
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: /run/secrets/db_password
    volumes:
      - db-data:/var/lib/mysql
    secrets:
      - db_root_password
      - db_password

volumes:
  wp-data:
  db-data:

secrets:
  db_password:
    file: db_password.secret
  db_root_password:
    file: db_root_password.secret
  smtp_password:
    file: smtp_password.secret

Thank you this worked with docker-compose! I created a separate gmail account that's only used to send mails on a wp-site of mine. If you use gmail as I did, you have to enable less secure apps in your gmail settings https://support.google.com/accounts/answer/6010255?hl=en

Was this page helpful?
0 / 5 - 0 ratings

Related issues

danyork picture danyork  路  4Comments

chrissound picture chrissound  路  5Comments

TeachMeHowToUse2FA picture TeachMeHowToUse2FA  路  4Comments

haszari picture haszari  路  4Comments

myuseringithub picture myuseringithub  路  5Comments