I have a problem with PHP send email to MailHog inside docker container.
Test with:
- Macbook M1
- php:8.1.29-cli
- maihog/mailhog:latest
- PHPMailer
// run.php
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;
use PHPMailerPHPMailerException;
//Load Composer's autoloader
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = 'localhost';
$mail->SMTPAuth = false;
$mail->Username = null;
$mail->Password = null;
$mail->Port = 1025;
//Recipients
$mail->setFrom('[email protected]', 'Test Sender');
$mail->addAddress('[email protected]', 'Test Receiver');
//Content
$mail->isHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
Successfully run on host machine
- I ran Mailhog in a container with port 1025 smtp, 8025 web.
- I was able to send email and mailhog caught that email.
Fail when running in docker.
I have docker compose file.
I have doubt that those all the ports are blocked, so I changed 1025, 8081, 51200…eg. Non of them work.
version: "1.0"
name: worker
services:
mailhog:
container_name: "mail_server"
image: mailhog/mailhog
ports:
- 8025:8025
- 1025:1025
networks:
- internet
cronjob:
container_name: "workers"
build:
context: .
dockerfile: Dockerfile
networks:
- internet
- proxy-net
volumes:
- ./src/logs:/var/www/app/logs
# command: tail -f /dev/null # Keep container running
command:
- php
- index.php
networks:
internet:
driver: bridge
and Dockerfile, I have changed different images from PHP, and other.
ARG WORKDIR=/var/www/app
FROM php:8.1.29-cli
#FROM php:8.1.29-apache
#FROM webdevops/php-apache:8.1
ARG ENV
ARG WORKDIR
RUN apt update && apt install -y libicu-dev && rm -rf /var/lib/apt/lists/*
RUN docker-php-ext-install mysqli pdo_mysql
RUN docker-php-ext-enable mysqli pdo_mysql
RUN docker-php-ext-configure intl && docker-php-ext-install intl
WORKDIR $WORKDIR
COPY ./src ./
COPY ./vendor ./vendor
And the error:
workers | 2024-06-28 04:44:45 SMTP ERROR: Failed to connect to server: Cannot assign requested address (99)
workers | 2024-06-28 04:44:45 SMTP Error: Could not connect to SMTP host. Failed to connect to server
workers | Message could not be sent. Mailer Error: SMTP Error: Could not connect to SMTP host. Failed to connect to serverSMTP server error: Failed to connect to server SMTP code: 99 Additional SMTP info: Cannot assign requested address
Does anyone happen to know what the problem here?