概要
本ドキュメントでは、Laravel プロジェクトに Mailgun を導入し、
外部メールサービス経由で通知・認証メールなどを送信できるようにする手順を解説します。
対象環境:
- Laravel
- Docker コンテナ構成
- composer インストール済み
1.パッケージインストール
コンテナ内で Mailgun 関連パッケージを導入
Mailgun を利用するために必要な composer パッケージを Docker コンテナ上でインストールします。
# (1) Symfony Mailer の Mailgun ブリッジと HTTP client を導入(Laravel は Symfony Mailer を使用)
docker exec -it tripost-laravel bash -lc "composer require symfony/mailgun-mailer symfony/http-client --no-interaction"
# (2) 必要に応じて Mailgun の公式 SDK を使うなら(API を直接叩く実装がある場合)
docker exec -it tripost-laravel bash -lc "composer require mailgun/mailgun-php --no-interaction"
2.config/mail.php に Mailgun mailer を追加
config/mail.php の 'mailers' 配列に Mailgun 設定を追記します。
// ...existing code...
'mailers' => [
// ...既存の mailer...
'roundrobin' => [
'transport' => 'roundrobin',
'mailers' => [
'ses',
'postmark',
],
'retry_after' => 60,
],
// ✅ Mailgun を追加
'mailgun' => [
'transport' => 'mailgun',
],
],
// ...existing code...
3.config/services.php に Mailgun 設定を追加
Mailgun の接続情報を環境変数経由で読み込むようにします。
// ...existing code...
'slack' => [
'notifications' => [
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
],
],
// ✅ Mailgun 設定追加
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
],
// ...existing code...
4.envに必要な環境変数を追加
Mailgun の API 認証情報を .envに定義します。
MAIL_MAILER=mailgun
MAILGUN_DOMAIN=mg.example.com
MAILGUN_SECRET=xxxxxxxxxxxxxxxxxxxxxxx
MAILGUN_ENDPOINT=api.mailgun.net
MAIL_FROM_ADDRESS=no-reply@example.com
MAIL_FROM_NAME="*****"
※ MAILGUN_DOMAIN と MAILGUN_SECRET は Mailgun のダッシュボードから取得。
5.テスト送信
・直接 curl で API 送信
curl -s --user "api:${MAILGUN_SECRET}" \
https://api.mailgun.net/v3/${MAILGUN_DOMAIN}/messages \
-F from="${MAIL_FROM_ADDRESS}" \
-F to="{送信先メールアドレス}" \
-F subject="{件名}" \
-F text="{本文}"
・Laravel から直接送る
php artisan tinker --execute="use Illuminate\\Support\\Facades\\Mail; Mail::raw('テスト本文', function(\$m){ \$m->to('recipient@example.com')->subject('Laravel Mailgun テスト'); });"