2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHPで正しくEmailTransportを設定する

2
Posted at

はじめに

CakePHP4でEmailをローカルで送るようconfig/app.phpに設定していて、Emailがどうも送られないので解決法を記事にしました。

この記事の対象

  • config/app.phpconfig/app_local.phpの違いがわからない方
  • config/app.phpでEmailTransportの設定を行なったのにメールが来ない方

Emailの設定方法

以下の記事の通りにEmail設定を行います。
https://qiita.com/hajime_shoji/items/22cd78dc51932963233c

config/app.php
    'EmailTransport' => [
        'default' => [
            'className' => 'Smtp',
            'host' => 'smtp.gmail.com',
            'port' => 587,
            'timeout' => 30,
            'username' => 'myGmailAccount@gmail.com',//ここに自分のGmailアカウントを設定
            'password' => 'myPassword',//ここに自分のGmailアカウントのパスワードを設定
            'client' => null,
            'tls' => true,
//            'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),//ここはコメントアウト
        ],
    ],

この設定をして、Controller等でEmailを送る機能を実装します。
受信先もGmailアカウントを使用する場合、必ず安全性の低いアプリからのアカウントへのアクセスを許可する設定を行いましょう。詳しくは上の参考記事を見てください。

問題点

この設定をしているのにも関わらず、メールが送られない場合があります。
ここで見てほしいのは、config/app_local.phpです。というのも、CakePHPでは、config/app.phpを読み込んだ後、すぐにconfig/app_local.phpが読み込まれます。慣れていないとうっかり見落とす場合があります。自分はconfig/app_local.phpがデフォルトのままでした。

参考:https://book.cakephp.org/3/en/development/configuration.html#configuring-your-application

解決案

ローカルではconfig/app.phpではなくconfig/app_local.phpにEmailTransportの設定を書きましょう。

```php:config/app_local.php`
'EmailTransport' => [
'default' => [
'className' => 'Smtp',
'host' => 'smtp.gmail.com',
'port' => 587,
'timeout' => 30,
'username' => 'myGmailAccount@gmail.com',//ここに自分のGmailアカウントを設定
'password' => 'myPassword',//ここに自分のGmailアカウントのパスワードを設定
'client' => null,
'tls' => true,
// 'url' => env('EMAIL_TRANSPORT_DEFAULT_URL', null),//ここはコメントアウト
],
],


### 補足

ちなみに、メールを送る時はエラーが起こりうるので、SendしたらしっかりTry&Catchでエラーをログに書き込んでおきましょう。

```php:
            try {
                $this->getMailer('Mailerの名前')->send($Mailerのメゾット, [$entity]);
            } catch (\Exception $e) {
                Log::error($e->getMessage());
            }
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?