Vapor Trail

明るく楽しく元気よく

PHP+msmtpとMailCatcherをDockerで動かす

PHP+msmtpとMailCatcherをDockerで動かす

今までPHP+ssmtpとMailCatcherを使用していた。

WSL2にしてDockerを動かそうとしたら

Package 'ssmtp' has no installation candidate

と出てインストールできなかった。

ssmtpはメンテされていないことを知ったので代わりにssmtpからmsmtpを使用することにした。

PHP + msmtpコンテナからメールを送信してMailCatcherコンテナで受信するイメージ。

MailCatcherを立ち上げる

参考 qiita.com

msmtp

PHPのコンテナのDockerfileに以下を追加。

RUN  apt-get install msmtp msmtp-mta -yqq

msmtp設定ファイルの場所

root@819b134ed4c4:/# msmtp --version
msmtp version 1.8.3
Platform: x86_64-pc-linux-gnu
TLS/SSL library: GnuTLS
Authentication library: GNU SASL
Supported authentication methods:
plain scram-sha-1 external gssapi cram-md5 digest-md5 login ntlm
IDN support: enabled
NLS: enabled, LOCALEDIR is /usr/share/locale
Keyring support: none
System configuration file name: /etc/msmtprc
User configuration file name: /root/.msmtprc

Copyright (C) 2019 Martin Lambers and others.
This is free software.  You may redistribute copies of it under the terms of
the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.
There is NO WARRANTY, to the extent permitted by law.

システムの設定ファイルは /etc/msmtprc
ユーザ個別の設定ファイルは /root/.msmtprc

  • 設定ファイルをコンテナにマウントする
    volumes:
      - ./msmtprc:/etc/msmtprc
  • msmtprcの設定
/etc/msmtprc
# Set default values for all following accounts.
defaults
auth off
tls off
tls_trust_file /etc/ssl/certs/ca-certificates.crt
syslog on
aliases /etc/aliases

# MailCatcher
account mailcatcher
# MailCatcherのコンテナ名
host mailcatcher
port 1025
from username@example.com
user username
password password

# Set a default account
account default : mailcatcher

auth と tls をoffにしないと以下のエラーが出て送信できない。

msmtp: the server does not support TLS via the STARTTLS command
msmtp: could not send mail (account default from /etc/msmtprc)

msmtp: the server does not support authentication
msmtp: could not send mail (account default from /etc/msmtprc)

送信

$ echo "Hello this is sending email using msmtp" | msmtp recipent@domain.com

php.iniの設定

[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = me@example.com

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
;sendmail_path = /usr/sbin/sendmail -t -i
sendmail_path = "/usr/bin/msmtp -C /etc/msmtprc -t"

PHPから送信

<?php
     mail("your@email.com", "Test email from PHP", "msmtp as sendmail for PHP");
?>

参考