How to get sendmail working in Alpine Docker container?

Viewed 18931

I just want to send simple email for testing purposes, but when executing sendmail inside the container, I get sendmail: can't connect to remote host (127.0.0.1): Connection refused. What do I need to take into account when using sendmail inside Alpine container?

5 Answers

Set the SMTPHOST environment variable to the hostname or IP of your smtp server. The code to use this variable exist since since 2008-09-27 in the busybox sendmail commit (https://git.busybox.net/busybox/commit/?id=bed22a01fb19de6e4b4c2c7d8c5953bc7aa2580e) but the usage page was only updated on 2016-07-14 with the commit https://git.busybox.net/busybox/commit/?id=9de7509aa013a8634b13a29008cd58ca971c9c7c. Please note that the online documentation page doesn't reflect these changeshttps://www.busybox.net/downloads/BusyBox.html. Use sendmail --help to see the corrected usage.

Adding to earlier answer of m4r10k.

  1. Install ssmtp in the docker file of the container.
RUN apk update
RUN apk add ssmtp
  1. Create a configuration file on the host
root=postmaster
mailhub=mail.privateemail.com:587
FromLineOverride=YES
rewriteDomain=<YouDomain.com>
AuthUser=<YouEMail@YourDomain.com
AuthPass=<YouUserPass>
UseSTARTTLS=YES
hostname=YourDomain.com

Use a volume when running the container to use the ssmtp.conf

See a full example here using docker-compose and SMTP from NameCheap.

This is my setup using mailhog as smtp:

docker-compose:

version: "3"

services:
  drupal:
    build: .
    container_name: ${PROJECT_NAME}-drupal
    depends_on:
      - mysql
    restart: unless-stopped
    networks:
      - internal
    volumes:
      - ./docroot:/var/www/html
      - ./config:/home/config
  mailhog:
    image: mailhog/mailhog:latest
    container_name: ${PROJECT_NAME}-mailhog
    ports:
      - "1025:1025"
      - "8025:8025"
    restart: unless-stopped
    networks:
      - internal

Don't forget to share the same network between the php and the mailhog containers.

Inside the Dockerfile install mhsendmail and change its binary mode to 0755, making it executable, Finally add the mhsendmail configuration into PHP:

Dockerfile php:7.4-fpm-alpine3.14:

RUN curl -LkSso /usr/bin/mhsendmail 'https://github.com/mailhog/mhsendmail/releases/download/v0.2.0/mhsendmail_linux_amd64'&& \
    chmod 0755 /usr/bin/mhsendmail && \
    echo 'sendmail_path = "/usr/bin/mhsendmail --from=nobody@7bd822a2c191 --smtp-addr=mailhog:1025"' >> /usr/local/etc/php/php.ini;

Now send an email from inside the php container to test the configuration:

$ php -r "mail('recipient@mail.com', 'test subject', 'test body');"

Source: https://github.com/mailhog/MailHog/issues/254

Related